blob: a1f2e1f4ab63d3a943540cccf7335457524eea4f [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
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000794ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000795 ExternalSource.reset(Source.take());
796}
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
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000849 if (ExternalSource.get()) {
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
Eli Friedman7ab09572009-05-25 21:27:19 +00001764 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001765 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001766 T = CT->getElementType().getTypePtr();
1767 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001768 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1769 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001770 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1771
Chris Lattnera3402cd2009-01-27 18:08:34 +00001772 return ABIAlign;
1773}
1774
Ulrich Weigandfa806422013-05-06 16:23:57 +00001775/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1776/// to a global variable of the specified type.
1777unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1778 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1779}
1780
1781/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1782/// should be given to a global variable of the specified type.
1783CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1784 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1785}
1786
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001787/// DeepCollectObjCIvars -
1788/// This routine first collects all declared, but not synthesized, ivars in
1789/// super class and then collects all ivars, including those synthesized for
1790/// current class. This routine is used for implementation of current class
1791/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001792///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001793void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1794 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001795 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001796 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1797 DeepCollectObjCIvars(SuperClass, false, Ivars);
1798 if (!leafClass) {
1799 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1800 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001801 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001802 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001803 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001804 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001805 Iv= Iv->getNextIvar())
1806 Ivars.push_back(Iv);
1807 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001808}
1809
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001810/// CollectInheritedProtocols - Collect all protocols in current class and
1811/// those inherited by it.
1812void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001813 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001814 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001815 // We can use protocol_iterator here instead of
1816 // all_referenced_protocol_iterator since we are walking all categories.
1817 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1818 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001819 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001820 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001821 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001822 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001823 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001824 CollectInheritedProtocols(*P, Protocols);
1825 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001826 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001827
1828 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001829 for (ObjCInterfaceDecl::visible_categories_iterator
1830 Cat = OI->visible_categories_begin(),
1831 CatEnd = OI->visible_categories_end();
1832 Cat != CatEnd; ++Cat) {
1833 CollectInheritedProtocols(*Cat, Protocols);
1834 }
1835
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001836 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1837 while (SD) {
1838 CollectInheritedProtocols(SD, Protocols);
1839 SD = SD->getSuperClass();
1840 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001841 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001842 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001843 PE = OC->protocol_end(); P != PE; ++P) {
1844 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001845 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001846 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1847 PE = Proto->protocol_end(); P != PE; ++P)
1848 CollectInheritedProtocols(*P, Protocols);
1849 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001850 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001851 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1852 PE = OP->protocol_end(); P != PE; ++P) {
1853 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001854 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001855 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1856 PE = Proto->protocol_end(); P != PE; ++P)
1857 CollectInheritedProtocols(*P, Protocols);
1858 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001859 }
1860}
1861
Jay Foad39c79802011-01-12 09:06:06 +00001862unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001863 unsigned count = 0;
1864 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001865 for (ObjCInterfaceDecl::known_extensions_iterator
1866 Ext = OI->known_extensions_begin(),
1867 ExtEnd = OI->known_extensions_end();
1868 Ext != ExtEnd; ++Ext) {
1869 count += Ext->ivar_size();
1870 }
1871
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001872 // Count ivar defined in this class's implementation. This
1873 // includes synthesized ivars.
1874 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001875 count += ImplDecl->ivar_size();
1876
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001877 return count;
1878}
1879
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001880bool ASTContext::isSentinelNullExpr(const Expr *E) {
1881 if (!E)
1882 return false;
1883
1884 // nullptr_t is always treated as null.
1885 if (E->getType()->isNullPtrType()) return true;
1886
1887 if (E->getType()->isAnyPointerType() &&
1888 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1889 Expr::NPC_ValueDependentIsNull))
1890 return true;
1891
1892 // Unfortunately, __null has type 'int'.
1893 if (isa<GNUNullExpr>(E)) return true;
1894
1895 return false;
1896}
1897
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001898/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1899ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1901 I = ObjCImpls.find(D);
1902 if (I != ObjCImpls.end())
1903 return cast<ObjCImplementationDecl>(I->second);
1904 return 0;
1905}
1906/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1907ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1908 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1909 I = ObjCImpls.find(D);
1910 if (I != ObjCImpls.end())
1911 return cast<ObjCCategoryImplDecl>(I->second);
1912 return 0;
1913}
1914
1915/// \brief Set the implementation of ObjCInterfaceDecl.
1916void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1917 ObjCImplementationDecl *ImplD) {
1918 assert(IFaceD && ImplD && "Passed null params");
1919 ObjCImpls[IFaceD] = ImplD;
1920}
1921/// \brief Set the implementation of ObjCCategoryDecl.
1922void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1923 ObjCCategoryImplDecl *ImplD) {
1924 assert(CatD && ImplD && "Passed null params");
1925 ObjCImpls[CatD] = ImplD;
1926}
1927
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001928const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1929 const NamedDecl *ND) const {
1930 if (const ObjCInterfaceDecl *ID =
1931 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001932 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001933 if (const ObjCCategoryDecl *CD =
1934 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001935 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001936 if (const ObjCImplDecl *IMD =
1937 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001938 return IMD->getClassInterface();
1939
1940 return 0;
1941}
1942
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001943/// \brief Get the copy initialization expression of VarDecl,or NULL if
1944/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001945Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001946 assert(VD && "Passed null params");
1947 assert(VD->hasAttr<BlocksAttr>() &&
1948 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001949 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001950 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001951 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1952}
1953
1954/// \brief Set the copy inialization expression of a block var decl.
1955void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1956 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001957 assert(VD->hasAttr<BlocksAttr>() &&
1958 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001959 BlockVarCopyInits[VD] = Init;
1960}
1961
John McCallbcd03502009-12-07 02:54:59 +00001962TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001963 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001964 if (!DataSize)
1965 DataSize = TypeLoc::getFullDataSizeForType(T);
1966 else
1967 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001968 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001969
John McCallbcd03502009-12-07 02:54:59 +00001970 TypeSourceInfo *TInfo =
1971 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1972 new (TInfo) TypeSourceInfo(T);
1973 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001974}
1975
John McCallbcd03502009-12-07 02:54:59 +00001976TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001977 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001978 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001979 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001980 return DI;
1981}
1982
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001983const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001984ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001985 return getObjCLayout(D, 0);
1986}
1987
1988const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001989ASTContext::getASTObjCImplementationLayout(
1990 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001991 return getObjCLayout(D->getClassInterface(), D);
1992}
1993
Chris Lattner983a8bb2007-07-13 22:13:22 +00001994//===----------------------------------------------------------------------===//
1995// Type creation/memoization methods
1996//===----------------------------------------------------------------------===//
1997
Jay Foad39c79802011-01-12 09:06:06 +00001998QualType
John McCall33ddac02011-01-19 10:06:00 +00001999ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2000 unsigned fastQuals = quals.getFastQualifiers();
2001 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002002
2003 // Check if we've already instantiated this type.
2004 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002005 ExtQuals::Profile(ID, baseType, quals);
2006 void *insertPos = 0;
2007 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2008 assert(eq->getQualifiers() == quals);
2009 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002010 }
2011
John McCall33ddac02011-01-19 10:06:00 +00002012 // If the base type is not canonical, make the appropriate canonical type.
2013 QualType canon;
2014 if (!baseType->isCanonicalUnqualified()) {
2015 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002016 canonSplit.Quals.addConsistentQualifiers(quals);
2017 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002018
2019 // Re-find the insert position.
2020 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2021 }
2022
2023 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2024 ExtQualNodes.InsertNode(eq, insertPos);
2025 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002026}
2027
Jay Foad39c79802011-01-12 09:06:06 +00002028QualType
2029ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002030 QualType CanT = getCanonicalType(T);
2031 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002032 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002033
John McCall8ccfcb52009-09-24 19:53:00 +00002034 // If we are composing extended qualifiers together, merge together
2035 // into one ExtQuals node.
2036 QualifierCollector Quals;
2037 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002038
John McCall8ccfcb52009-09-24 19:53:00 +00002039 // If this type already has an address space specified, it cannot get
2040 // another one.
2041 assert(!Quals.hasAddressSpace() &&
2042 "Type cannot be in multiple addr spaces!");
2043 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002044
John McCall8ccfcb52009-09-24 19:53:00 +00002045 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002046}
2047
Chris Lattnerd60183d2009-02-18 22:53:11 +00002048QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002049 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002050 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002051 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002052 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002053
John McCall53fa7142010-12-24 02:08:15 +00002054 if (const PointerType *ptr = T->getAs<PointerType>()) {
2055 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002056 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002057 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2058 return getPointerType(ResultType);
2059 }
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
John McCall8ccfcb52009-09-24 19:53:00 +00002062 // If we are composing extended qualifiers together, merge together
2063 // into one ExtQuals node.
2064 QualifierCollector Quals;
2065 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002066
John McCall8ccfcb52009-09-24 19:53:00 +00002067 // If this type already has an ObjCGC specified, it cannot get
2068 // another one.
2069 assert(!Quals.hasObjCGCAttr() &&
2070 "Type cannot have multiple ObjCGCs!");
2071 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCall8ccfcb52009-09-24 19:53:00 +00002073 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002074}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002075
John McCall4f5019e2010-12-19 02:44:49 +00002076const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2077 FunctionType::ExtInfo Info) {
2078 if (T->getExtInfo() == Info)
2079 return T;
2080
2081 QualType Result;
2082 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002083 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002084 } else {
2085 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2086 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2087 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002088 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002089 }
2090
2091 return cast<FunctionType>(Result.getTypePtr());
2092}
2093
Richard Smith2a7d4812013-05-04 07:00:32 +00002094void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2095 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002096 FD = FD->getMostRecentDecl();
2097 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002098 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2099 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002100 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002101 if (FunctionDecl *Next = FD->getPreviousDecl())
2102 FD = Next;
2103 else
2104 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002105 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002106 if (ASTMutationListener *L = getASTMutationListener())
2107 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002108}
2109
Chris Lattnerc6395932007-06-22 20:56:16 +00002110/// getComplexType - Return the uniqued reference to the type for a complex
2111/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002112QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002113 // Unique pointers, to guarantee there is only one pointer of a particular
2114 // structure.
2115 llvm::FoldingSetNodeID ID;
2116 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattnerc6395932007-06-22 20:56:16 +00002118 void *InsertPos = 0;
2119 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2120 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattnerc6395932007-06-22 20:56:16 +00002122 // If the pointee type isn't canonical, this won't be a canonical type either,
2123 // so fill in the canonical type field.
2124 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002125 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002126 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002127
Chris Lattnerc6395932007-06-22 20:56:16 +00002128 // Get the new insert position for the node we care about.
2129 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002130 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002131 }
John McCall90d1c2d2009-09-24 23:30:46 +00002132 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002133 Types.push_back(New);
2134 ComplexTypes.InsertNode(New, InsertPos);
2135 return QualType(New, 0);
2136}
2137
Chris Lattner970e54e2006-11-12 00:37:36 +00002138/// getPointerType - Return the uniqued reference to the type for a pointer to
2139/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002140QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002141 // Unique pointers, to guarantee there is only one pointer of a particular
2142 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002143 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002144 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattner67521df2007-01-27 01:29:36 +00002146 void *InsertPos = 0;
2147 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002148 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002149
Chris Lattner7ccecb92006-11-12 08:50:50 +00002150 // If the pointee type isn't canonical, this won't be a canonical type either,
2151 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002152 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002153 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002154 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002155
Bob Wilsonc8541f22013-03-15 17:12:43 +00002156 // Get the new insert position for the node we care about.
2157 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2158 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2159 }
John McCall90d1c2d2009-09-24 23:30:46 +00002160 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002161 Types.push_back(New);
2162 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002163 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002164}
2165
Reid Kleckner0503a872013-12-05 01:23:43 +00002166QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2167 llvm::FoldingSetNodeID ID;
2168 AdjustedType::Profile(ID, Orig, New);
2169 void *InsertPos = 0;
2170 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2171 if (AT)
2172 return QualType(AT, 0);
2173
2174 QualType Canonical = getCanonicalType(New);
2175
2176 // Get the new insert position for the node we care about.
2177 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2178 assert(AT == 0 && "Shouldn't be in the map!");
2179
2180 AT = new (*this, TypeAlignment)
2181 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2182 Types.push_back(AT);
2183 AdjustedTypes.InsertNode(AT, InsertPos);
2184 return QualType(AT, 0);
2185}
2186
Reid Kleckner8a365022013-06-24 17:51:48 +00002187QualType ASTContext::getDecayedType(QualType T) const {
2188 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2189
Reid Kleckner8a365022013-06-24 17:51:48 +00002190 QualType Decayed;
2191
2192 // C99 6.7.5.3p7:
2193 // A declaration of a parameter as "array of type" shall be
2194 // adjusted to "qualified pointer to type", where the type
2195 // qualifiers (if any) are those specified within the [ and ] of
2196 // the array type derivation.
2197 if (T->isArrayType())
2198 Decayed = getArrayDecayedType(T);
2199
2200 // C99 6.7.5.3p8:
2201 // A declaration of a parameter as "function returning type"
2202 // shall be adjusted to "pointer to function returning type", as
2203 // in 6.3.2.1.
2204 if (T->isFunctionType())
2205 Decayed = getPointerType(T);
2206
Reid Kleckner0503a872013-12-05 01:23:43 +00002207 llvm::FoldingSetNodeID ID;
2208 AdjustedType::Profile(ID, T, Decayed);
2209 void *InsertPos = 0;
2210 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2211 if (AT)
2212 return QualType(AT, 0);
2213
Reid Kleckner8a365022013-06-24 17:51:48 +00002214 QualType Canonical = getCanonicalType(Decayed);
2215
2216 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002217 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2218 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002219
Reid Kleckner0503a872013-12-05 01:23:43 +00002220 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2221 Types.push_back(AT);
2222 AdjustedTypes.InsertNode(AT, InsertPos);
2223 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002224}
2225
Mike Stump11289f42009-09-09 15:08:12 +00002226/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002227/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002228QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002229 assert(T->isFunctionType() && "block of function types only");
2230 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002231 // structure.
2232 llvm::FoldingSetNodeID ID;
2233 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002234
Steve Naroffec33ed92008-08-27 16:04:49 +00002235 void *InsertPos = 0;
2236 if (BlockPointerType *PT =
2237 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2238 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002239
2240 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002241 // type either so fill in the canonical type field.
2242 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002243 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002244 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002245
Steve Naroffec33ed92008-08-27 16:04:49 +00002246 // Get the new insert position for the node we care about.
2247 BlockPointerType *NewIP =
2248 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002249 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002250 }
John McCall90d1c2d2009-09-24 23:30:46 +00002251 BlockPointerType *New
2252 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002253 Types.push_back(New);
2254 BlockPointerTypes.InsertNode(New, InsertPos);
2255 return QualType(New, 0);
2256}
2257
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002258/// getLValueReferenceType - Return the uniqued reference to the type for an
2259/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002260QualType
2261ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002262 assert(getCanonicalType(T) != OverloadTy &&
2263 "Unresolved overloaded function type");
2264
Bill Wendling3708c182007-05-27 10:15:43 +00002265 // Unique pointers, to guarantee there is only one pointer of a particular
2266 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002267 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002268 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002269
2270 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002271 if (LValueReferenceType *RT =
2272 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002273 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002274
John McCallfc93cf92009-10-22 22:37:11 +00002275 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2276
Bill Wendling3708c182007-05-27 10:15:43 +00002277 // If the referencee type isn't canonical, this won't be a canonical type
2278 // either, so fill in the canonical type field.
2279 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002280 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2281 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2282 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002283
Bill Wendling3708c182007-05-27 10:15:43 +00002284 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002285 LValueReferenceType *NewIP =
2286 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002287 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002288 }
2289
John McCall90d1c2d2009-09-24 23:30:46 +00002290 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002291 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2292 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002293 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002294 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002295
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002296 return QualType(New, 0);
2297}
2298
2299/// getRValueReferenceType - Return the uniqued reference to the type for an
2300/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002301QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002302 // Unique pointers, to guarantee there is only one pointer of a particular
2303 // structure.
2304 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002305 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002306
2307 void *InsertPos = 0;
2308 if (RValueReferenceType *RT =
2309 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2310 return QualType(RT, 0);
2311
John McCallfc93cf92009-10-22 22:37:11 +00002312 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2313
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002314 // If the referencee type isn't canonical, this won't be a canonical type
2315 // either, so fill in the canonical type field.
2316 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002317 if (InnerRef || !T.isCanonical()) {
2318 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2319 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002320
2321 // Get the new insert position for the node we care about.
2322 RValueReferenceType *NewIP =
2323 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002324 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002325 }
2326
John McCall90d1c2d2009-09-24 23:30:46 +00002327 RValueReferenceType *New
2328 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002329 Types.push_back(New);
2330 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002331 return QualType(New, 0);
2332}
2333
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002334/// getMemberPointerType - Return the uniqued reference to the type for a
2335/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002336QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002337 // Unique pointers, to guarantee there is only one pointer of a particular
2338 // structure.
2339 llvm::FoldingSetNodeID ID;
2340 MemberPointerType::Profile(ID, T, Cls);
2341
2342 void *InsertPos = 0;
2343 if (MemberPointerType *PT =
2344 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2345 return QualType(PT, 0);
2346
2347 // If the pointee or class type isn't canonical, this won't be a canonical
2348 // type either, so fill in the canonical type field.
2349 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002350 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002351 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2352
2353 // Get the new insert position for the node we care about.
2354 MemberPointerType *NewIP =
2355 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002356 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002357 }
John McCall90d1c2d2009-09-24 23:30:46 +00002358 MemberPointerType *New
2359 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002360 Types.push_back(New);
2361 MemberPointerTypes.InsertNode(New, InsertPos);
2362 return QualType(New, 0);
2363}
2364
Mike Stump11289f42009-09-09 15:08:12 +00002365/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002366/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002367QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002368 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002369 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002370 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002371 assert((EltTy->isDependentType() ||
2372 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002373 "Constant array of VLAs is illegal!");
2374
Chris Lattnere2df3f92009-05-13 04:12:56 +00002375 // Convert the array size into a canonical width matching the pointer size for
2376 // the target.
2377 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002378 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002379 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002380
Chris Lattner23b7eb62007-06-15 23:05:46 +00002381 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002382 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002383
Chris Lattner36f8e652007-01-27 08:31:04 +00002384 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002385 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002386 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002387 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002388
John McCall33ddac02011-01-19 10:06:00 +00002389 // If the element type isn't canonical or has qualifiers, this won't
2390 // be a canonical type either, so fill in the canonical type field.
2391 QualType Canon;
2392 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2393 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002394 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002395 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002396 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002397
Chris Lattner36f8e652007-01-27 08:31:04 +00002398 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002399 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002400 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002401 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002402 }
Mike Stump11289f42009-09-09 15:08:12 +00002403
John McCall90d1c2d2009-09-24 23:30:46 +00002404 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002405 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002406 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002407 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002408 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002409}
2410
John McCall06549462011-01-18 08:40:38 +00002411/// getVariableArrayDecayedType - Turns the given type, which may be
2412/// variably-modified, into the corresponding type with all the known
2413/// sizes replaced with [*].
2414QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2415 // Vastly most common case.
2416 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002417
John McCall06549462011-01-18 08:40:38 +00002418 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002419
John McCall06549462011-01-18 08:40:38 +00002420 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002421 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002422 switch (ty->getTypeClass()) {
2423#define TYPE(Class, Base)
2424#define ABSTRACT_TYPE(Class, Base)
2425#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2426#include "clang/AST/TypeNodes.def"
2427 llvm_unreachable("didn't desugar past all non-canonical types?");
2428
2429 // These types should never be variably-modified.
2430 case Type::Builtin:
2431 case Type::Complex:
2432 case Type::Vector:
2433 case Type::ExtVector:
2434 case Type::DependentSizedExtVector:
2435 case Type::ObjCObject:
2436 case Type::ObjCInterface:
2437 case Type::ObjCObjectPointer:
2438 case Type::Record:
2439 case Type::Enum:
2440 case Type::UnresolvedUsing:
2441 case Type::TypeOfExpr:
2442 case Type::TypeOf:
2443 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002444 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002445 case Type::DependentName:
2446 case Type::InjectedClassName:
2447 case Type::TemplateSpecialization:
2448 case Type::DependentTemplateSpecialization:
2449 case Type::TemplateTypeParm:
2450 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002451 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002452 case Type::PackExpansion:
2453 llvm_unreachable("type should never be variably-modified");
2454
2455 // These types can be variably-modified but should never need to
2456 // further decay.
2457 case Type::FunctionNoProto:
2458 case Type::FunctionProto:
2459 case Type::BlockPointer:
2460 case Type::MemberPointer:
2461 return type;
2462
2463 // These types can be variably-modified. All these modifications
2464 // preserve structure except as noted by comments.
2465 // TODO: if we ever care about optimizing VLAs, there are no-op
2466 // optimizations available here.
2467 case Type::Pointer:
2468 result = getPointerType(getVariableArrayDecayedType(
2469 cast<PointerType>(ty)->getPointeeType()));
2470 break;
2471
2472 case Type::LValueReference: {
2473 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2474 result = getLValueReferenceType(
2475 getVariableArrayDecayedType(lv->getPointeeType()),
2476 lv->isSpelledAsLValue());
2477 break;
2478 }
2479
2480 case Type::RValueReference: {
2481 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2482 result = getRValueReferenceType(
2483 getVariableArrayDecayedType(lv->getPointeeType()));
2484 break;
2485 }
2486
Eli Friedman0dfb8892011-10-06 23:00:33 +00002487 case Type::Atomic: {
2488 const AtomicType *at = cast<AtomicType>(ty);
2489 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2490 break;
2491 }
2492
John McCall06549462011-01-18 08:40:38 +00002493 case Type::ConstantArray: {
2494 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2495 result = getConstantArrayType(
2496 getVariableArrayDecayedType(cat->getElementType()),
2497 cat->getSize(),
2498 cat->getSizeModifier(),
2499 cat->getIndexTypeCVRQualifiers());
2500 break;
2501 }
2502
2503 case Type::DependentSizedArray: {
2504 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2505 result = getDependentSizedArrayType(
2506 getVariableArrayDecayedType(dat->getElementType()),
2507 dat->getSizeExpr(),
2508 dat->getSizeModifier(),
2509 dat->getIndexTypeCVRQualifiers(),
2510 dat->getBracketsRange());
2511 break;
2512 }
2513
2514 // Turn incomplete types into [*] types.
2515 case Type::IncompleteArray: {
2516 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2517 result = getVariableArrayType(
2518 getVariableArrayDecayedType(iat->getElementType()),
2519 /*size*/ 0,
2520 ArrayType::Normal,
2521 iat->getIndexTypeCVRQualifiers(),
2522 SourceRange());
2523 break;
2524 }
2525
2526 // Turn VLA types into [*] types.
2527 case Type::VariableArray: {
2528 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2529 result = getVariableArrayType(
2530 getVariableArrayDecayedType(vat->getElementType()),
2531 /*size*/ 0,
2532 ArrayType::Star,
2533 vat->getIndexTypeCVRQualifiers(),
2534 vat->getBracketsRange());
2535 break;
2536 }
2537 }
2538
2539 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002540 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002541}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002542
Steve Naroffcadebd02007-08-30 18:14:25 +00002543/// getVariableArrayType - Returns a non-unique reference to the type for a
2544/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002545QualType ASTContext::getVariableArrayType(QualType EltTy,
2546 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002547 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002548 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002549 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002550 // Since we don't unique expressions, it isn't possible to unique VLA's
2551 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002552 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002553
John McCall33ddac02011-01-19 10:06:00 +00002554 // Be sure to pull qualifiers off the element type.
2555 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2556 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002557 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002558 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002559 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002560 }
2561
John McCall90d1c2d2009-09-24 23:30:46 +00002562 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002563 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002564
2565 VariableArrayTypes.push_back(New);
2566 Types.push_back(New);
2567 return QualType(New, 0);
2568}
2569
Douglas Gregor4619e432008-12-05 23:32:09 +00002570/// getDependentSizedArrayType - Returns a non-unique reference to
2571/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002572/// type.
John McCall33ddac02011-01-19 10:06:00 +00002573QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2574 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002575 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002576 unsigned elementTypeQuals,
2577 SourceRange brackets) const {
2578 assert((!numElements || numElements->isTypeDependent() ||
2579 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002580 "Size must be type- or value-dependent!");
2581
John McCall33ddac02011-01-19 10:06:00 +00002582 // Dependently-sized array types that do not have a specified number
2583 // of elements will have their sizes deduced from a dependent
2584 // initializer. We do no canonicalization here at all, which is okay
2585 // because they can't be used in most locations.
2586 if (!numElements) {
2587 DependentSizedArrayType *newType
2588 = new (*this, TypeAlignment)
2589 DependentSizedArrayType(*this, elementType, QualType(),
2590 numElements, ASM, elementTypeQuals,
2591 brackets);
2592 Types.push_back(newType);
2593 return QualType(newType, 0);
2594 }
2595
2596 // Otherwise, we actually build a new type every time, but we
2597 // also build a canonical type.
2598
2599 SplitQualType canonElementType = getCanonicalType(elementType).split();
2600
2601 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002602 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002603 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002604 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002605 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002606
John McCall33ddac02011-01-19 10:06:00 +00002607 // Look for an existing type with these properties.
2608 DependentSizedArrayType *canonTy =
2609 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002610
John McCall33ddac02011-01-19 10:06:00 +00002611 // If we don't have one, build one.
2612 if (!canonTy) {
2613 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002614 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002615 QualType(), numElements, ASM, elementTypeQuals,
2616 brackets);
2617 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2618 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002619 }
2620
John McCall33ddac02011-01-19 10:06:00 +00002621 // Apply qualifiers from the element type to the array.
2622 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002623 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002624
John McCall33ddac02011-01-19 10:06:00 +00002625 // If we didn't need extra canonicalization for the element type,
2626 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002627 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002628 return canon;
2629
2630 // Otherwise, we need to build a type which follows the spelling
2631 // of the element type.
2632 DependentSizedArrayType *sugaredType
2633 = new (*this, TypeAlignment)
2634 DependentSizedArrayType(*this, elementType, canon, numElements,
2635 ASM, elementTypeQuals, brackets);
2636 Types.push_back(sugaredType);
2637 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002638}
2639
John McCall33ddac02011-01-19 10:06:00 +00002640QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002641 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002642 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002643 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002644 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002645
John McCall33ddac02011-01-19 10:06:00 +00002646 void *insertPos = 0;
2647 if (IncompleteArrayType *iat =
2648 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2649 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002650
2651 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002652 // either, so fill in the canonical type field. We also have to pull
2653 // qualifiers off the element type.
2654 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002655
John McCall33ddac02011-01-19 10:06:00 +00002656 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2657 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002658 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002659 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002660 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002661
2662 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002663 IncompleteArrayType *existing =
2664 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2665 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002666 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002667
John McCall33ddac02011-01-19 10:06:00 +00002668 IncompleteArrayType *newType = new (*this, TypeAlignment)
2669 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002670
John McCall33ddac02011-01-19 10:06:00 +00002671 IncompleteArrayTypes.InsertNode(newType, insertPos);
2672 Types.push_back(newType);
2673 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002674}
2675
Steve Naroff91fcddb2007-07-18 18:00:27 +00002676/// getVectorType - Return the unique reference to a vector type of
2677/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002678QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002679 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002680 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002681
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002682 // Check if we've already instantiated a vector of this type.
2683 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002684 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002685
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002686 void *InsertPos = 0;
2687 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2688 return QualType(VTP, 0);
2689
2690 // If the element type isn't canonical, this won't be a canonical type either,
2691 // so fill in the canonical type field.
2692 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002693 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002694 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002695
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002696 // Get the new insert position for the node we care about.
2697 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002698 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002699 }
John McCall90d1c2d2009-09-24 23:30:46 +00002700 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002701 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002702 VectorTypes.InsertNode(New, InsertPos);
2703 Types.push_back(New);
2704 return QualType(New, 0);
2705}
2706
Nate Begemance4d7fc2008-04-18 23:10:10 +00002707/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002708/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002709QualType
2710ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002711 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002712
Steve Naroff91fcddb2007-07-18 18:00:27 +00002713 // Check if we've already instantiated a vector of this type.
2714 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002715 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002716 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002717 void *InsertPos = 0;
2718 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2719 return QualType(VTP, 0);
2720
2721 // If the element type isn't canonical, this won't be a canonical type either,
2722 // so fill in the canonical type field.
2723 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002724 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002725 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002726
Steve Naroff91fcddb2007-07-18 18:00:27 +00002727 // Get the new insert position for the node we care about.
2728 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002729 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002730 }
John McCall90d1c2d2009-09-24 23:30:46 +00002731 ExtVectorType *New = new (*this, TypeAlignment)
2732 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002733 VectorTypes.InsertNode(New, InsertPos);
2734 Types.push_back(New);
2735 return QualType(New, 0);
2736}
2737
Jay Foad39c79802011-01-12 09:06:06 +00002738QualType
2739ASTContext::getDependentSizedExtVectorType(QualType vecType,
2740 Expr *SizeExpr,
2741 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002742 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002743 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002744 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002745
Douglas Gregor352169a2009-07-31 03:54:25 +00002746 void *InsertPos = 0;
2747 DependentSizedExtVectorType *Canon
2748 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2749 DependentSizedExtVectorType *New;
2750 if (Canon) {
2751 // We already have a canonical version of this array type; use it as
2752 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002753 New = new (*this, TypeAlignment)
2754 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2755 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002756 } else {
2757 QualType CanonVecTy = getCanonicalType(vecType);
2758 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002759 New = new (*this, TypeAlignment)
2760 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2761 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002762
2763 DependentSizedExtVectorType *CanonCheck
2764 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2765 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2766 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002767 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2768 } else {
2769 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2770 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002771 New = new (*this, TypeAlignment)
2772 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002773 }
2774 }
Mike Stump11289f42009-09-09 15:08:12 +00002775
Douglas Gregor758a8692009-06-17 21:51:59 +00002776 Types.push_back(New);
2777 return QualType(New, 0);
2778}
2779
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002780/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002781///
Jay Foad39c79802011-01-12 09:06:06 +00002782QualType
2783ASTContext::getFunctionNoProtoType(QualType ResultTy,
2784 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002785 const CallingConv CallConv = Info.getCC();
2786
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002787 // Unique functions, to guarantee there is only one function of a particular
2788 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002789 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002790 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002791
Chris Lattner47955de2007-01-27 08:37:20 +00002792 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002793 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002794 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002795 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002796
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002797 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002798 if (!ResultTy.isCanonical()) {
2799 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002800
Chris Lattner47955de2007-01-27 08:37:20 +00002801 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002802 FunctionNoProtoType *NewIP =
2803 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002804 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002805 }
Mike Stump11289f42009-09-09 15:08:12 +00002806
Roman Divacky65b88cd2011-03-01 17:40:53 +00002807 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002808 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002809 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002810 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002811 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002812 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002813}
2814
Douglas Gregorcd780372013-01-17 23:36:45 +00002815/// \brief Determine whether \p T is canonical as the result type of a function.
2816static bool isCanonicalResultType(QualType T) {
2817 return T.isCanonical() &&
2818 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2819 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2820}
2821
Jay Foad39c79802011-01-12 09:06:06 +00002822QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002823ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002824 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002825 size_t NumArgs = ArgArray.size();
2826
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002827 // Unique functions, to guarantee there is only one function of a particular
2828 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002829 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002830 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2831 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002832
2833 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002834 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002835 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002836 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002837
2838 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002839 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002840 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002841 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002842 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002843 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002844 isCanonical = false;
2845
2846 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002847 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002848 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002849 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002850 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002851 CanonicalArgs.reserve(NumArgs);
2852 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002853 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002854
John McCalldb40c7f2010-12-14 08:05:40 +00002855 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002856 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002857 CanonicalEPI.ExceptionSpecType = EST_None;
2858 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002859
Douglas Gregorcd780372013-01-17 23:36:45 +00002860 // Result types do not have ARC lifetime qualifiers.
2861 QualType CanResultTy = getCanonicalType(ResultTy);
2862 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2863 Qualifiers Qs = CanResultTy.getQualifiers();
2864 Qs.removeObjCLifetime();
2865 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2866 }
2867
Jordan Rose5c382722013-03-08 21:51:21 +00002868 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002869
Chris Lattnerfd4de792007-01-27 01:15:32 +00002870 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002871 FunctionProtoType *NewIP =
2872 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002873 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002874 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002875
John McCall31168b02011-06-15 23:02:42 +00002876 // FunctionProtoType objects are allocated with extra bytes after
2877 // them for three variable size arrays at the end:
2878 // - parameter types
2879 // - exception types
2880 // - consumed-arguments flags
2881 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002882 // expression, or information used to resolve the exception
2883 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002884 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002885 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002886 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002887 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002888 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002889 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002890 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002891 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002892 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2893 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002894 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002895 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002896 Size += NumArgs * sizeof(bool);
2897
John McCalldb40c7f2010-12-14 08:05:40 +00002898 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002899 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002900 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002901 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002902 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002903 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002904}
Chris Lattneref51c202006-11-10 07:17:23 +00002905
John McCalle78aac42010-03-10 03:28:59 +00002906#ifndef NDEBUG
2907static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2908 if (!isa<CXXRecordDecl>(D)) return false;
2909 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2910 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2911 return true;
2912 if (RD->getDescribedClassTemplate() &&
2913 !isa<ClassTemplateSpecializationDecl>(RD))
2914 return true;
2915 return false;
2916}
2917#endif
2918
2919/// getInjectedClassNameType - Return the unique reference to the
2920/// injected class name type for the specified templated declaration.
2921QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002922 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002923 assert(NeedsInjectedClassNameType(Decl));
2924 if (Decl->TypeForDecl) {
2925 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002926 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002927 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2928 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2929 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2930 } else {
John McCall424cec92011-01-19 06:33:43 +00002931 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002932 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002933 Decl->TypeForDecl = newType;
2934 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002935 }
2936 return QualType(Decl->TypeForDecl, 0);
2937}
2938
Douglas Gregor83a586e2008-04-13 21:07:44 +00002939/// getTypeDeclType - Return the unique reference to the type for the
2940/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002941QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002942 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002943 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002944
Richard Smithdda56e42011-04-15 14:24:37 +00002945 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002946 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002947
John McCall96f0b5f2010-03-10 06:48:02 +00002948 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2949 "Template type parameter types are always available.");
2950
John McCall81e38502010-02-16 03:57:14 +00002951 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002952 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002953 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002954 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002955 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002956 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002957 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002958 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002959 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002960 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2961 Decl->TypeForDecl = newType;
2962 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002963 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002964 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002965
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002966 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002967}
2968
Chris Lattner32d920b2007-01-26 02:01:53 +00002969/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002970/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002971QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002972ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2973 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002974 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002975
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002976 if (Canonical.isNull())
2977 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002978 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002979 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002980 Decl->TypeForDecl = newType;
2981 Types.push_back(newType);
2982 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002983}
2984
Jay Foad39c79802011-01-12 09:06:06 +00002985QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002986 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2987
Douglas Gregorec9fd132012-01-14 16:38:05 +00002988 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002989 if (PrevDecl->TypeForDecl)
2990 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2991
John McCall424cec92011-01-19 06:33:43 +00002992 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2993 Decl->TypeForDecl = newType;
2994 Types.push_back(newType);
2995 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002996}
2997
Jay Foad39c79802011-01-12 09:06:06 +00002998QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002999 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3000
Douglas Gregorec9fd132012-01-14 16:38:05 +00003001 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003002 if (PrevDecl->TypeForDecl)
3003 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3004
John McCall424cec92011-01-19 06:33:43 +00003005 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3006 Decl->TypeForDecl = newType;
3007 Types.push_back(newType);
3008 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003009}
3010
John McCall81904512011-01-06 01:58:22 +00003011QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3012 QualType modifiedType,
3013 QualType equivalentType) {
3014 llvm::FoldingSetNodeID id;
3015 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3016
3017 void *insertPos = 0;
3018 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3019 if (type) return QualType(type, 0);
3020
3021 QualType canon = getCanonicalType(equivalentType);
3022 type = new (*this, TypeAlignment)
3023 AttributedType(canon, attrKind, modifiedType, equivalentType);
3024
3025 Types.push_back(type);
3026 AttributedTypes.InsertNode(type, insertPos);
3027
3028 return QualType(type, 0);
3029}
3030
3031
John McCallcebee162009-10-18 09:09:24 +00003032/// \brief Retrieve a substitution-result type.
3033QualType
3034ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003035 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003036 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003037 && "replacement types must always be canonical");
3038
3039 llvm::FoldingSetNodeID ID;
3040 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3041 void *InsertPos = 0;
3042 SubstTemplateTypeParmType *SubstParm
3043 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3044
3045 if (!SubstParm) {
3046 SubstParm = new (*this, TypeAlignment)
3047 SubstTemplateTypeParmType(Parm, Replacement);
3048 Types.push_back(SubstParm);
3049 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3050 }
3051
3052 return QualType(SubstParm, 0);
3053}
3054
Douglas Gregorada4b792011-01-14 02:55:32 +00003055/// \brief Retrieve a
3056QualType ASTContext::getSubstTemplateTypeParmPackType(
3057 const TemplateTypeParmType *Parm,
3058 const TemplateArgument &ArgPack) {
3059#ifndef NDEBUG
3060 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3061 PEnd = ArgPack.pack_end();
3062 P != PEnd; ++P) {
3063 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3064 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3065 }
3066#endif
3067
3068 llvm::FoldingSetNodeID ID;
3069 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3070 void *InsertPos = 0;
3071 if (SubstTemplateTypeParmPackType *SubstParm
3072 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3073 return QualType(SubstParm, 0);
3074
3075 QualType Canon;
3076 if (!Parm->isCanonicalUnqualified()) {
3077 Canon = getCanonicalType(QualType(Parm, 0));
3078 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3079 ArgPack);
3080 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3081 }
3082
3083 SubstTemplateTypeParmPackType *SubstParm
3084 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3085 ArgPack);
3086 Types.push_back(SubstParm);
3087 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3088 return QualType(SubstParm, 0);
3089}
3090
Douglas Gregoreff93e02009-02-05 23:33:38 +00003091/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003092/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003093/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003094QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003095 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003096 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003097 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003098 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003099 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003100 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003101 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3102
3103 if (TypeParm)
3104 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003105
Chandler Carruth08836322011-05-01 00:51:33 +00003106 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003107 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003108 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003109
3110 TemplateTypeParmType *TypeCheck
3111 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3112 assert(!TypeCheck && "Template type parameter canonical type broken");
3113 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003114 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003115 TypeParm = new (*this, TypeAlignment)
3116 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003117
3118 Types.push_back(TypeParm);
3119 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3120
3121 return QualType(TypeParm, 0);
3122}
3123
John McCalle78aac42010-03-10 03:28:59 +00003124TypeSourceInfo *
3125ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3126 SourceLocation NameLoc,
3127 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003128 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003129 assert(!Name.getAsDependentTemplateName() &&
3130 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003131 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003132
3133 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003134 TemplateSpecializationTypeLoc TL =
3135 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003136 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003137 TL.setTemplateNameLoc(NameLoc);
3138 TL.setLAngleLoc(Args.getLAngleLoc());
3139 TL.setRAngleLoc(Args.getRAngleLoc());
3140 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3141 TL.setArgLocInfo(i, Args[i].getLocInfo());
3142 return DI;
3143}
3144
Mike Stump11289f42009-09-09 15:08:12 +00003145QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003146ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003147 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003148 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003149 assert(!Template.getAsDependentTemplateName() &&
3150 "No dependent template names here!");
3151
John McCall6b51f282009-11-23 01:53:49 +00003152 unsigned NumArgs = Args.size();
3153
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003154 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003155 ArgVec.reserve(NumArgs);
3156 for (unsigned i = 0; i != NumArgs; ++i)
3157 ArgVec.push_back(Args[i].getArgument());
3158
John McCall2408e322010-04-27 00:57:59 +00003159 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003160 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003161}
3162
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003163#ifndef NDEBUG
3164static bool hasAnyPackExpansions(const TemplateArgument *Args,
3165 unsigned NumArgs) {
3166 for (unsigned I = 0; I != NumArgs; ++I)
3167 if (Args[I].isPackExpansion())
3168 return true;
3169
3170 return true;
3171}
3172#endif
3173
John McCall0ad16662009-10-29 08:12:44 +00003174QualType
3175ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003176 const TemplateArgument *Args,
3177 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003178 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003179 assert(!Template.getAsDependentTemplateName() &&
3180 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003181 // Look through qualified template names.
3182 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3183 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003184
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003185 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003186 Template.getAsTemplateDecl() &&
3187 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003188 QualType CanonType;
3189 if (!Underlying.isNull())
3190 CanonType = getCanonicalType(Underlying);
3191 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003192 // We can get here with an alias template when the specialization contains
3193 // a pack expansion that does not match up with a parameter pack.
3194 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3195 "Caller must compute aliased type");
3196 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003197 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3198 NumArgs);
3199 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003200
Douglas Gregora8e02e72009-07-28 23:00:59 +00003201 // Allocate the (non-canonical) template specialization type, but don't
3202 // try to unique it: these types typically have location information that
3203 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003204 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3205 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003206 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003207 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003208 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003209 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3210 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003211
Douglas Gregor8bf42052009-02-09 18:46:07 +00003212 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003213 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003214}
3215
Mike Stump11289f42009-09-09 15:08:12 +00003216QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003217ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3218 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003219 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003220 assert(!Template.getAsDependentTemplateName() &&
3221 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003222
Douglas Gregore29139c2011-03-03 17:04:51 +00003223 // Look through qualified template names.
3224 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3225 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003226
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003227 // Build the canonical template specialization type.
3228 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003229 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003230 CanonArgs.reserve(NumArgs);
3231 for (unsigned I = 0; I != NumArgs; ++I)
3232 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3233
3234 // Determine whether this canonical template specialization type already
3235 // exists.
3236 llvm::FoldingSetNodeID ID;
3237 TemplateSpecializationType::Profile(ID, CanonTemplate,
3238 CanonArgs.data(), NumArgs, *this);
3239
3240 void *InsertPos = 0;
3241 TemplateSpecializationType *Spec
3242 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3243
3244 if (!Spec) {
3245 // Allocate a new canonical template specialization type.
3246 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3247 sizeof(TemplateArgument) * NumArgs),
3248 TypeAlignment);
3249 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3250 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003251 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003252 Types.push_back(Spec);
3253 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3254 }
3255
3256 assert(Spec->isDependentType() &&
3257 "Non-dependent template-id type must have a canonical type");
3258 return QualType(Spec, 0);
3259}
3260
3261QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003262ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3263 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003264 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003265 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003266 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003267
3268 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003269 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003270 if (T)
3271 return QualType(T, 0);
3272
Douglas Gregorc42075a2010-02-04 18:10:26 +00003273 QualType Canon = NamedType;
3274 if (!Canon.isCanonical()) {
3275 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003276 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3277 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003278 (void)CheckT;
3279 }
3280
Abramo Bagnara6150c882010-05-11 21:36:43 +00003281 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003282 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003283 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003284 return QualType(T, 0);
3285}
3286
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003287QualType
Jay Foad39c79802011-01-12 09:06:06 +00003288ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003289 llvm::FoldingSetNodeID ID;
3290 ParenType::Profile(ID, InnerType);
3291
3292 void *InsertPos = 0;
3293 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3294 if (T)
3295 return QualType(T, 0);
3296
3297 QualType Canon = InnerType;
3298 if (!Canon.isCanonical()) {
3299 Canon = getCanonicalType(InnerType);
3300 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3301 assert(!CheckT && "Paren canonical type broken");
3302 (void)CheckT;
3303 }
3304
3305 T = new (*this) ParenType(InnerType, Canon);
3306 Types.push_back(T);
3307 ParenTypes.InsertNode(T, InsertPos);
3308 return QualType(T, 0);
3309}
3310
Douglas Gregor02085352010-03-31 20:19:30 +00003311QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3312 NestedNameSpecifier *NNS,
3313 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003314 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003315 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3316
3317 if (Canon.isNull()) {
3318 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003319 ElaboratedTypeKeyword CanonKeyword = Keyword;
3320 if (Keyword == ETK_None)
3321 CanonKeyword = ETK_Typename;
3322
3323 if (CanonNNS != NNS || CanonKeyword != Keyword)
3324 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003325 }
3326
3327 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003328 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003329
3330 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003331 DependentNameType *T
3332 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003333 if (T)
3334 return QualType(T, 0);
3335
Douglas Gregor02085352010-03-31 20:19:30 +00003336 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003337 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003338 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003339 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003340}
3341
Mike Stump11289f42009-09-09 15:08:12 +00003342QualType
John McCallc392f372010-06-11 00:33:02 +00003343ASTContext::getDependentTemplateSpecializationType(
3344 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003345 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003346 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003347 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003348 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003349 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003350 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3351 ArgCopy.push_back(Args[I].getArgument());
3352 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3353 ArgCopy.size(),
3354 ArgCopy.data());
3355}
3356
3357QualType
3358ASTContext::getDependentTemplateSpecializationType(
3359 ElaboratedTypeKeyword Keyword,
3360 NestedNameSpecifier *NNS,
3361 const IdentifierInfo *Name,
3362 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003363 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003364 assert((!NNS || NNS->isDependent()) &&
3365 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003366
Douglas Gregorc42075a2010-02-04 18:10:26 +00003367 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003368 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3369 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003370
3371 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003372 DependentTemplateSpecializationType *T
3373 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003374 if (T)
3375 return QualType(T, 0);
3376
John McCallc392f372010-06-11 00:33:02 +00003377 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003378
John McCallc392f372010-06-11 00:33:02 +00003379 ElaboratedTypeKeyword CanonKeyword = Keyword;
3380 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3381
3382 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003383 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003384 for (unsigned I = 0; I != NumArgs; ++I) {
3385 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3386 if (!CanonArgs[I].structurallyEquals(Args[I]))
3387 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003388 }
3389
John McCallc392f372010-06-11 00:33:02 +00003390 QualType Canon;
3391 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3392 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3393 Name, NumArgs,
3394 CanonArgs.data());
3395
3396 // Find the insert position again.
3397 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3398 }
3399
3400 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3401 sizeof(TemplateArgument) * NumArgs),
3402 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003403 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003404 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003405 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003406 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003407 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003408}
3409
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003410QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003411 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003412 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003413 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003414
3415 assert(Pattern->containsUnexpandedParameterPack() &&
3416 "Pack expansions must expand one or more parameter packs");
3417 void *InsertPos = 0;
3418 PackExpansionType *T
3419 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3420 if (T)
3421 return QualType(T, 0);
3422
3423 QualType Canon;
3424 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003425 Canon = getCanonicalType(Pattern);
3426 // The canonical type might not contain an unexpanded parameter pack, if it
3427 // contains an alias template specialization which ignores one of its
3428 // parameters.
3429 if (Canon->containsUnexpandedParameterPack()) {
3430 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003431
Richard Smith68eea502012-07-16 00:20:35 +00003432 // Find the insert position again, in case we inserted an element into
3433 // PackExpansionTypes and invalidated our insert position.
3434 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3435 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003436 }
3437
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003438 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003439 Types.push_back(T);
3440 PackExpansionTypes.InsertNode(T, InsertPos);
3441 return QualType(T, 0);
3442}
3443
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003444/// CmpProtocolNames - Comparison predicate for sorting protocols
3445/// alphabetically.
3446static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3447 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003448 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003449}
3450
John McCall8b07ec22010-05-15 11:32:37 +00003451static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003452 unsigned NumProtocols) {
3453 if (NumProtocols == 0) return true;
3454
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003455 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3456 return false;
3457
John McCallfc93cf92009-10-22 22:37:11 +00003458 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003459 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3460 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003461 return false;
3462 return true;
3463}
3464
3465static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003466 unsigned &NumProtocols) {
3467 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003468
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003469 // Sort protocols, keyed by name.
3470 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3471
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003472 // Canonicalize.
3473 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3474 Protocols[I] = Protocols[I]->getCanonicalDecl();
3475
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003476 // Remove duplicates.
3477 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3478 NumProtocols = ProtocolsEnd-Protocols;
3479}
3480
John McCall8b07ec22010-05-15 11:32:37 +00003481QualType ASTContext::getObjCObjectType(QualType BaseType,
3482 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003483 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003484 // If the base type is an interface and there aren't any protocols
3485 // to add, then the interface type will do just fine.
3486 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3487 return BaseType;
3488
3489 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003490 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003491 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003492 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003493 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3494 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003495
John McCall8b07ec22010-05-15 11:32:37 +00003496 // Build the canonical type, which has the canonical base type and
3497 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003498 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003499 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3500 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3501 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003502 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003503 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003504 unsigned UniqueCount = NumProtocols;
3505
John McCallfc93cf92009-10-22 22:37:11 +00003506 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003507 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3508 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003509 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003510 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3511 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003512 }
3513
3514 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003515 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3516 }
3517
3518 unsigned Size = sizeof(ObjCObjectTypeImpl);
3519 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3520 void *Mem = Allocate(Size, TypeAlignment);
3521 ObjCObjectTypeImpl *T =
3522 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3523
3524 Types.push_back(T);
3525 ObjCObjectTypes.InsertNode(T, InsertPos);
3526 return QualType(T, 0);
3527}
3528
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003529/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3530/// protocol list adopt all protocols in QT's qualified-id protocol
3531/// list.
3532bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3533 ObjCInterfaceDecl *IC) {
3534 if (!QT->isObjCQualifiedIdType())
3535 return false;
3536
3537 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3538 // If both the right and left sides have qualifiers.
3539 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3540 E = OPT->qual_end(); I != E; ++I) {
3541 ObjCProtocolDecl *Proto = *I;
3542 if (!IC->ClassImplementsProtocol(Proto, false))
3543 return false;
3544 }
3545 return true;
3546 }
3547 return false;
3548}
3549
3550/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3551/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3552/// of protocols.
3553bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3554 ObjCInterfaceDecl *IDecl) {
3555 if (!QT->isObjCQualifiedIdType())
3556 return false;
3557 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3558 if (!OPT)
3559 return false;
3560 if (!IDecl->hasDefinition())
3561 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003562 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3563 CollectInheritedProtocols(IDecl, InheritedProtocols);
3564 if (InheritedProtocols.empty())
3565 return false;
3566
3567 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3568 InheritedProtocols.begin(),
3569 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003570 // If both the right and left sides have qualifiers.
3571 bool Adopts = false;
3572 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3573 E = OPT->qual_end(); I != E; ++I) {
3574 ObjCProtocolDecl *Proto = *I;
3575 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3576 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3577 break;
3578 }
3579 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003580 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003581 }
3582 return true;
3583}
3584
John McCall8b07ec22010-05-15 11:32:37 +00003585/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3586/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003587QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003588 llvm::FoldingSetNodeID ID;
3589 ObjCObjectPointerType::Profile(ID, ObjectT);
3590
3591 void *InsertPos = 0;
3592 if (ObjCObjectPointerType *QT =
3593 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3594 return QualType(QT, 0);
3595
3596 // Find the canonical object type.
3597 QualType Canonical;
3598 if (!ObjectT.isCanonical()) {
3599 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3600
3601 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003602 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3603 }
3604
Douglas Gregorf85bee62010-02-08 22:59:26 +00003605 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003606 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3607 ObjCObjectPointerType *QType =
3608 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003609
Steve Narofffb4330f2009-06-17 22:40:22 +00003610 Types.push_back(QType);
3611 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003612 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003613}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003614
Douglas Gregor1c283312010-08-11 12:19:30 +00003615/// getObjCInterfaceType - Return the unique reference to the type for the
3616/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003617QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3618 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003619 if (Decl->TypeForDecl)
3620 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003621
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003622 if (PrevDecl) {
3623 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3624 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3625 return QualType(PrevDecl->TypeForDecl, 0);
3626 }
3627
Douglas Gregor7671e532011-12-16 16:34:57 +00003628 // Prefer the definition, if there is one.
3629 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3630 Decl = Def;
3631
Douglas Gregor1c283312010-08-11 12:19:30 +00003632 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3633 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3634 Decl->TypeForDecl = T;
3635 Types.push_back(T);
3636 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003637}
3638
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003639/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3640/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003641/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003642/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003643/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003644QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003645 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003646 if (tofExpr->isTypeDependent()) {
3647 llvm::FoldingSetNodeID ID;
3648 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003649
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003650 void *InsertPos = 0;
3651 DependentTypeOfExprType *Canon
3652 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3653 if (Canon) {
3654 // We already have a "canonical" version of an identical, dependent
3655 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003656 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003657 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003658 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003659 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003660 Canon
3661 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003662 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3663 toe = Canon;
3664 }
3665 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003666 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003667 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003668 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003669 Types.push_back(toe);
3670 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003671}
3672
Steve Naroffa773cd52007-08-01 18:02:17 +00003673/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3674/// TypeOfType AST's. The only motivation to unique these nodes would be
3675/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003676/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003677/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003678QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003679 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003680 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003681 Types.push_back(tot);
3682 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003683}
3684
Anders Carlssonad6bd352009-06-24 21:24:56 +00003685
Anders Carlsson81df7b82009-06-24 19:06:50 +00003686/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3687/// DecltypeType AST's. The only motivation to unique these nodes would be
3688/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003689/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003690/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003691QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003692 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003693
3694 // C++0x [temp.type]p2:
3695 // If an expression e involves a template parameter, decltype(e) denotes a
3696 // unique dependent type. Two such decltype-specifiers refer to the same
3697 // type only if their expressions are equivalent (14.5.6.1).
3698 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003699 llvm::FoldingSetNodeID ID;
3700 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregora21f6c32009-07-30 23:36:40 +00003702 void *InsertPos = 0;
3703 DependentDecltypeType *Canon
3704 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3705 if (Canon) {
3706 // We already have a "canonical" version of an equivalent, dependent
3707 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003708 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003709 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003710 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003711 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003712 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003713 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3714 dt = Canon;
3715 }
3716 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003717 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3718 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003719 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003720 Types.push_back(dt);
3721 return QualType(dt, 0);
3722}
3723
Alexis Hunte852b102011-05-24 22:41:36 +00003724/// getUnaryTransformationType - We don't unique these, since the memory
3725/// savings are minimal and these are rare.
3726QualType ASTContext::getUnaryTransformType(QualType BaseType,
3727 QualType UnderlyingType,
3728 UnaryTransformType::UTTKind Kind)
3729 const {
3730 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003731 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3732 Kind,
3733 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003734 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003735 Types.push_back(Ty);
3736 return QualType(Ty, 0);
3737}
3738
Richard Smith2a7d4812013-05-04 07:00:32 +00003739/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3740/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3741/// canonical deduced-but-dependent 'auto' type.
3742QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003743 bool IsDependent) const {
3744 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003745 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003746
Richard Smith2a7d4812013-05-04 07:00:32 +00003747 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003748 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003749 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003750 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003751 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3752 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003753
Richard Smith74aeef52013-04-26 16:15:35 +00003754 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003755 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003756 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003757 Types.push_back(AT);
3758 if (InsertPos)
3759 AutoTypes.InsertNode(AT, InsertPos);
3760 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003761}
3762
Eli Friedman0dfb8892011-10-06 23:00:33 +00003763/// getAtomicType - Return the uniqued reference to the atomic type for
3764/// the given value type.
3765QualType ASTContext::getAtomicType(QualType T) const {
3766 // Unique pointers, to guarantee there is only one pointer of a particular
3767 // structure.
3768 llvm::FoldingSetNodeID ID;
3769 AtomicType::Profile(ID, T);
3770
3771 void *InsertPos = 0;
3772 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3773 return QualType(AT, 0);
3774
3775 // If the atomic value type isn't canonical, this won't be a canonical type
3776 // either, so fill in the canonical type field.
3777 QualType Canonical;
3778 if (!T.isCanonical()) {
3779 Canonical = getAtomicType(getCanonicalType(T));
3780
3781 // Get the new insert position for the node we care about.
3782 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3783 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3784 }
3785 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3786 Types.push_back(New);
3787 AtomicTypes.InsertNode(New, InsertPos);
3788 return QualType(New, 0);
3789}
3790
Richard Smith02e85f32011-04-14 22:09:26 +00003791/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3792QualType ASTContext::getAutoDeductType() const {
3793 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003794 AutoDeductTy = QualType(
3795 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003796 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003797 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003798 return AutoDeductTy;
3799}
3800
3801/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3802QualType ASTContext::getAutoRRefDeductType() const {
3803 if (AutoRRefDeductTy.isNull())
3804 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3805 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3806 return AutoRRefDeductTy;
3807}
3808
Chris Lattnerfb072462007-01-23 05:45:31 +00003809/// getTagDeclType - Return the unique reference to the type for the
3810/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003811QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003812 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003813 // FIXME: What is the design on getTagDeclType when it requires casting
3814 // away const? mutable?
3815 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003816}
3817
Mike Stump11289f42009-09-09 15:08:12 +00003818/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3819/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3820/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003821CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003822 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003823}
Chris Lattnerfb072462007-01-23 05:45:31 +00003824
Hans Wennborg27541db2011-10-27 08:29:09 +00003825/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3826CanQualType ASTContext::getIntMaxType() const {
3827 return getFromTargetType(Target->getIntMaxType());
3828}
3829
3830/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3831CanQualType ASTContext::getUIntMaxType() const {
3832 return getFromTargetType(Target->getUIntMaxType());
3833}
3834
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003835/// getSignedWCharType - Return the type of "signed wchar_t".
3836/// Used when in C++, as a GCC extension.
3837QualType ASTContext::getSignedWCharType() const {
3838 // FIXME: derive from "Target" ?
3839 return WCharTy;
3840}
3841
3842/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3843/// Used when in C++, as a GCC extension.
3844QualType ASTContext::getUnsignedWCharType() const {
3845 // FIXME: derive from "Target" ?
3846 return UnsignedIntTy;
3847}
3848
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003849QualType ASTContext::getIntPtrType() const {
3850 return getFromTargetType(Target->getIntPtrType());
3851}
3852
3853QualType ASTContext::getUIntPtrType() const {
3854 return getCorrespondingUnsignedType(getIntPtrType());
3855}
3856
Hans Wennborg27541db2011-10-27 08:29:09 +00003857/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003858/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3859QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003860 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003861}
3862
Eli Friedman4e91899e2012-11-27 02:58:24 +00003863/// \brief Return the unique type for "pid_t" defined in
3864/// <sys/types.h>. We need this to compute the correct type for vfork().
3865QualType ASTContext::getProcessIDType() const {
3866 return getFromTargetType(Target->getProcessIDType());
3867}
3868
Chris Lattnera21ad802008-04-02 05:18:44 +00003869//===----------------------------------------------------------------------===//
3870// Type Operators
3871//===----------------------------------------------------------------------===//
3872
Jay Foad39c79802011-01-12 09:06:06 +00003873CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003874 // Push qualifiers into arrays, and then discard any remaining
3875 // qualifiers.
3876 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003877 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003878 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003879 QualType Result;
3880 if (isa<ArrayType>(Ty)) {
3881 Result = getArrayDecayedType(QualType(Ty,0));
3882 } else if (isa<FunctionType>(Ty)) {
3883 Result = getPointerType(QualType(Ty, 0));
3884 } else {
3885 Result = QualType(Ty, 0);
3886 }
3887
3888 return CanQualType::CreateUnsafe(Result);
3889}
3890
John McCall6c9dd522011-01-18 07:41:22 +00003891QualType ASTContext::getUnqualifiedArrayType(QualType type,
3892 Qualifiers &quals) {
3893 SplitQualType splitType = type.getSplitUnqualifiedType();
3894
3895 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3896 // the unqualified desugared type and then drops it on the floor.
3897 // We then have to strip that sugar back off with
3898 // getUnqualifiedDesugaredType(), which is silly.
3899 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003900 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003901
3902 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003903 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003904 quals = splitType.Quals;
3905 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003906 }
3907
John McCall6c9dd522011-01-18 07:41:22 +00003908 // Otherwise, recurse on the array's element type.
3909 QualType elementType = AT->getElementType();
3910 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3911
3912 // If that didn't change the element type, AT has no qualifiers, so we
3913 // can just use the results in splitType.
3914 if (elementType == unqualElementType) {
3915 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003916 quals = splitType.Quals;
3917 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003918 }
3919
3920 // Otherwise, add in the qualifiers from the outermost type, then
3921 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003922 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003923
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003924 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003925 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003926 CAT->getSizeModifier(), 0);
3927 }
3928
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003929 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003930 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003931 }
3932
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003933 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003934 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003935 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003936 VAT->getSizeModifier(),
3937 VAT->getIndexTypeCVRQualifiers(),
3938 VAT->getBracketsRange());
3939 }
3940
3941 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003942 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003943 DSAT->getSizeModifier(), 0,
3944 SourceRange());
3945}
3946
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003947/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3948/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3949/// they point to and return true. If T1 and T2 aren't pointer types
3950/// or pointer-to-member types, or if they are not similar at this
3951/// level, returns false and leaves T1 and T2 unchanged. Top-level
3952/// qualifiers on T1 and T2 are ignored. This function will typically
3953/// be called in a loop that successively "unwraps" pointer and
3954/// pointer-to-member types to compare them at each level.
3955bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3956 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3957 *T2PtrType = T2->getAs<PointerType>();
3958 if (T1PtrType && T2PtrType) {
3959 T1 = T1PtrType->getPointeeType();
3960 T2 = T2PtrType->getPointeeType();
3961 return true;
3962 }
3963
3964 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3965 *T2MPType = T2->getAs<MemberPointerType>();
3966 if (T1MPType && T2MPType &&
3967 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3968 QualType(T2MPType->getClass(), 0))) {
3969 T1 = T1MPType->getPointeeType();
3970 T2 = T2MPType->getPointeeType();
3971 return true;
3972 }
3973
David Blaikiebbafb8a2012-03-11 07:00:24 +00003974 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003975 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3976 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3977 if (T1OPType && T2OPType) {
3978 T1 = T1OPType->getPointeeType();
3979 T2 = T2OPType->getPointeeType();
3980 return true;
3981 }
3982 }
3983
3984 // FIXME: Block pointers, too?
3985
3986 return false;
3987}
3988
Jay Foad39c79802011-01-12 09:06:06 +00003989DeclarationNameInfo
3990ASTContext::getNameForTemplate(TemplateName Name,
3991 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003992 switch (Name.getKind()) {
3993 case TemplateName::QualifiedTemplate:
3994 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003995 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003996 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3997 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003998
John McCalld9dfe3a2011-06-30 08:33:18 +00003999 case TemplateName::OverloadedTemplate: {
4000 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4001 // DNInfo work in progress: CHECKME: what about DNLoc?
4002 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4003 }
4004
4005 case TemplateName::DependentTemplate: {
4006 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004007 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004008 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004009 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4010 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004011 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004012 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4013 // DNInfo work in progress: FIXME: source locations?
4014 DeclarationNameLoc DNLoc;
4015 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4016 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4017 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004018 }
4019 }
4020
John McCalld9dfe3a2011-06-30 08:33:18 +00004021 case TemplateName::SubstTemplateTemplateParm: {
4022 SubstTemplateTemplateParmStorage *subst
4023 = Name.getAsSubstTemplateTemplateParm();
4024 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4025 NameLoc);
4026 }
4027
4028 case TemplateName::SubstTemplateTemplateParmPack: {
4029 SubstTemplateTemplateParmPackStorage *subst
4030 = Name.getAsSubstTemplateTemplateParmPack();
4031 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4032 NameLoc);
4033 }
4034 }
4035
4036 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004037}
4038
Jay Foad39c79802011-01-12 09:06:06 +00004039TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004040 switch (Name.getKind()) {
4041 case TemplateName::QualifiedTemplate:
4042 case TemplateName::Template: {
4043 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004044 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004045 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004046 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4047
4048 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004049 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004050 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004051
John McCalld9dfe3a2011-06-30 08:33:18 +00004052 case TemplateName::OverloadedTemplate:
4053 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004054
John McCalld9dfe3a2011-06-30 08:33:18 +00004055 case TemplateName::DependentTemplate: {
4056 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4057 assert(DTN && "Non-dependent template names must refer to template decls.");
4058 return DTN->CanonicalTemplateName;
4059 }
4060
4061 case TemplateName::SubstTemplateTemplateParm: {
4062 SubstTemplateTemplateParmStorage *subst
4063 = Name.getAsSubstTemplateTemplateParm();
4064 return getCanonicalTemplateName(subst->getReplacement());
4065 }
4066
4067 case TemplateName::SubstTemplateTemplateParmPack: {
4068 SubstTemplateTemplateParmPackStorage *subst
4069 = Name.getAsSubstTemplateTemplateParmPack();
4070 TemplateTemplateParmDecl *canonParameter
4071 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4072 TemplateArgument canonArgPack
4073 = getCanonicalTemplateArgument(subst->getArgumentPack());
4074 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4075 }
4076 }
4077
4078 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004079}
4080
Douglas Gregoradee3e32009-11-11 23:06:43 +00004081bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4082 X = getCanonicalTemplateName(X);
4083 Y = getCanonicalTemplateName(Y);
4084 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4085}
4086
Mike Stump11289f42009-09-09 15:08:12 +00004087TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004088ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004089 switch (Arg.getKind()) {
4090 case TemplateArgument::Null:
4091 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004092
Douglas Gregora8e02e72009-07-28 23:00:59 +00004093 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004094 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004095
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004096 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004097 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4098 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004099 }
Mike Stump11289f42009-09-09 15:08:12 +00004100
Eli Friedmanb826a002012-09-26 02:36:12 +00004101 case TemplateArgument::NullPtr:
4102 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4103 /*isNullPtr*/true);
4104
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004105 case TemplateArgument::Template:
4106 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004107
4108 case TemplateArgument::TemplateExpansion:
4109 return TemplateArgument(getCanonicalTemplateName(
4110 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004111 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004112
Douglas Gregora8e02e72009-07-28 23:00:59 +00004113 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004114 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004115
Douglas Gregora8e02e72009-07-28 23:00:59 +00004116 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004117 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004118
Douglas Gregora8e02e72009-07-28 23:00:59 +00004119 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004120 if (Arg.pack_size() == 0)
4121 return Arg;
4122
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004123 TemplateArgument *CanonArgs
4124 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004125 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004126 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004127 AEnd = Arg.pack_end();
4128 A != AEnd; (void)++A, ++Idx)
4129 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004130
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004131 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004132 }
4133 }
4134
4135 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004136 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004137}
4138
Douglas Gregor333489b2009-03-27 23:10:48 +00004139NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004140ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004141 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004142 return 0;
4143
4144 switch (NNS->getKind()) {
4145 case NestedNameSpecifier::Identifier:
4146 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004147 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004148 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4149 NNS->getAsIdentifier());
4150
4151 case NestedNameSpecifier::Namespace:
4152 // A namespace is canonical; build a nested-name-specifier with
4153 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004154 return NestedNameSpecifier::Create(*this, 0,
4155 NNS->getAsNamespace()->getOriginalNamespace());
4156
4157 case NestedNameSpecifier::NamespaceAlias:
4158 // A namespace is canonical; build a nested-name-specifier with
4159 // this namespace and no prefix.
4160 return NestedNameSpecifier::Create(*this, 0,
4161 NNS->getAsNamespaceAlias()->getNamespace()
4162 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004163
4164 case NestedNameSpecifier::TypeSpec:
4165 case NestedNameSpecifier::TypeSpecWithTemplate: {
4166 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004167
4168 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4169 // break it apart into its prefix and identifier, then reconsititute those
4170 // as the canonical nested-name-specifier. This is required to canonicalize
4171 // a dependent nested-name-specifier involving typedefs of dependent-name
4172 // types, e.g.,
4173 // typedef typename T::type T1;
4174 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004175 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4176 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004177 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004178
Eli Friedman5358a0a2012-03-03 04:09:56 +00004179 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4180 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4181 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004182 return NestedNameSpecifier::Create(*this, 0, false,
4183 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004184 }
4185
4186 case NestedNameSpecifier::Global:
4187 // The global specifier is canonical and unique.
4188 return NNS;
4189 }
4190
David Blaikie8a40f702012-01-17 06:56:22 +00004191 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004192}
4193
Chris Lattner7adf0762008-08-04 07:31:14 +00004194
Jay Foad39c79802011-01-12 09:06:06 +00004195const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004196 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004197 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004198 // Handle the common positive case fast.
4199 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4200 return AT;
4201 }
Mike Stump11289f42009-09-09 15:08:12 +00004202
John McCall8ccfcb52009-09-24 19:53:00 +00004203 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004204 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004205 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004206
John McCall8ccfcb52009-09-24 19:53:00 +00004207 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004208 // implements C99 6.7.3p8: "If the specification of an array type includes
4209 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004210
Chris Lattner7adf0762008-08-04 07:31:14 +00004211 // If we get here, we either have type qualifiers on the type, or we have
4212 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004213 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004214
John McCall33ddac02011-01-19 10:06:00 +00004215 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004216 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004217
Chris Lattner7adf0762008-08-04 07:31:14 +00004218 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004219 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004220 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004221 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004222
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 // Otherwise, we have an array and we have qualifiers on it. Push the
4224 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004225 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004226
Chris Lattner7adf0762008-08-04 07:31:14 +00004227 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4228 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4229 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004230 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004231 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4232 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4233 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004234 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004235
Mike Stump11289f42009-09-09 15:08:12 +00004236 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004237 = dyn_cast<DependentSizedArrayType>(ATy))
4238 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004239 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004240 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004241 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004242 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004243 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004244
Chris Lattner7adf0762008-08-04 07:31:14 +00004245 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004246 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004247 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004248 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004249 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004250 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004251}
4252
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004253QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004254 if (T->isArrayType() || T->isFunctionType())
4255 return getDecayedType(T);
4256 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004257}
4258
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004259QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004260 T = getVariableArrayDecayedType(T);
4261 T = getAdjustedParameterType(T);
4262 return T.getUnqualifiedType();
4263}
4264
Chris Lattnera21ad802008-04-02 05:18:44 +00004265/// getArrayDecayedType - Return the properly qualified result of decaying the
4266/// specified array type to a pointer. This operation is non-trivial when
4267/// handling typedefs etc. The canonical type of "T" must be an array type,
4268/// this returns a pointer to a properly qualified element of the array.
4269///
4270/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004271QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004272 // Get the element type with 'getAsArrayType' so that we don't lose any
4273 // typedefs in the element type of the array. This also handles propagation
4274 // of type qualifiers from the array type into the element type if present
4275 // (C99 6.7.3p8).
4276 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4277 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004278
Chris Lattner7adf0762008-08-04 07:31:14 +00004279 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004280
4281 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004282 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004283}
4284
John McCall33ddac02011-01-19 10:06:00 +00004285QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4286 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004287}
4288
John McCall33ddac02011-01-19 10:06:00 +00004289QualType ASTContext::getBaseElementType(QualType type) const {
4290 Qualifiers qs;
4291 while (true) {
4292 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004293 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004294 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004295
John McCall33ddac02011-01-19 10:06:00 +00004296 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004297 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004298 }
Mike Stump11289f42009-09-09 15:08:12 +00004299
John McCall33ddac02011-01-19 10:06:00 +00004300 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004301}
4302
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004303/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004304uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004305ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4306 uint64_t ElementCount = 1;
4307 do {
4308 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004309 CA = dyn_cast_or_null<ConstantArrayType>(
4310 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004311 } while (CA);
4312 return ElementCount;
4313}
4314
Steve Naroff0af91202007-04-27 21:51:21 +00004315/// getFloatingRank - Return a relative rank for floating point types.
4316/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004317static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004318 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004319 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004320
John McCall9dd450b2009-09-21 23:43:11 +00004321 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4322 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004323 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004324 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004325 case BuiltinType::Float: return FloatRank;
4326 case BuiltinType::Double: return DoubleRank;
4327 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004328 }
4329}
4330
Mike Stump11289f42009-09-09 15:08:12 +00004331/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4332/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004333/// 'typeDomain' is a real floating point or complex type.
4334/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004335QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4336 QualType Domain) const {
4337 FloatingRank EltRank = getFloatingRank(Size);
4338 if (Domain->isComplexType()) {
4339 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004340 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004341 case FloatRank: return FloatComplexTy;
4342 case DoubleRank: return DoubleComplexTy;
4343 case LongDoubleRank: return LongDoubleComplexTy;
4344 }
Steve Naroff0af91202007-04-27 21:51:21 +00004345 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004346
4347 assert(Domain->isRealFloatingType() && "Unknown domain!");
4348 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004349 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004350 case FloatRank: return FloatTy;
4351 case DoubleRank: return DoubleTy;
4352 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004353 }
David Blaikief47fa302012-01-17 02:30:50 +00004354 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004355}
4356
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004357/// getFloatingTypeOrder - Compare the rank of the two specified floating
4358/// point types, ignoring the domain of the type (i.e. 'double' ==
4359/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004360/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004361int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004362 FloatingRank LHSR = getFloatingRank(LHS);
4363 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004364
Chris Lattnerb90739d2008-04-06 23:38:49 +00004365 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004366 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004367 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004368 return 1;
4369 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004370}
4371
Chris Lattner76a00cf2008-04-06 22:59:24 +00004372/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4373/// routine will assert if passed a built-in type that isn't an integer or enum,
4374/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004375unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004376 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004377
Chris Lattner76a00cf2008-04-06 22:59:24 +00004378 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004379 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004380 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004381 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004382 case BuiltinType::Char_S:
4383 case BuiltinType::Char_U:
4384 case BuiltinType::SChar:
4385 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004386 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004387 case BuiltinType::Short:
4388 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004389 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004390 case BuiltinType::Int:
4391 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004392 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004393 case BuiltinType::Long:
4394 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004395 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004396 case BuiltinType::LongLong:
4397 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004398 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004399 case BuiltinType::Int128:
4400 case BuiltinType::UInt128:
4401 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004402 }
4403}
4404
Eli Friedman629ffb92009-08-20 04:21:42 +00004405/// \brief Whether this is a promotable bitfield reference according
4406/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4407///
4408/// \returns the type this bit-field will promote to, or NULL if no
4409/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004410QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004411 if (E->isTypeDependent() || E->isValueDependent())
4412 return QualType();
4413
John McCalld25db7e2013-05-06 21:39:12 +00004414 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004415 if (!Field)
4416 return QualType();
4417
4418 QualType FT = Field->getType();
4419
Richard Smithcaf33902011-10-10 18:28:20 +00004420 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004421 uint64_t IntSize = getTypeSize(IntTy);
4422 // GCC extension compatibility: if the bit-field size is less than or equal
4423 // to the size of int, it gets promoted no matter what its type is.
4424 // For instance, unsigned long bf : 4 gets promoted to signed int.
4425 if (BitWidth < IntSize)
4426 return IntTy;
4427
4428 if (BitWidth == IntSize)
4429 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4430
4431 // Types bigger than int are not subject to promotions, and therefore act
4432 // like the base type.
4433 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4434 // is ridiculous.
4435 return QualType();
4436}
4437
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004438/// getPromotedIntegerType - Returns the type that Promotable will
4439/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4440/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004441QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004442 assert(!Promotable.isNull());
4443 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004444 if (const EnumType *ET = Promotable->getAs<EnumType>())
4445 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004446
4447 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4448 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4449 // (3.9.1) can be converted to a prvalue of the first of the following
4450 // types that can represent all the values of its underlying type:
4451 // int, unsigned int, long int, unsigned long int, long long int, or
4452 // unsigned long long int [...]
4453 // FIXME: Is there some better way to compute this?
4454 if (BT->getKind() == BuiltinType::WChar_S ||
4455 BT->getKind() == BuiltinType::WChar_U ||
4456 BT->getKind() == BuiltinType::Char16 ||
4457 BT->getKind() == BuiltinType::Char32) {
4458 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4459 uint64_t FromSize = getTypeSize(BT);
4460 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4461 LongLongTy, UnsignedLongLongTy };
4462 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4463 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4464 if (FromSize < ToSize ||
4465 (FromSize == ToSize &&
4466 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4467 return PromoteTypes[Idx];
4468 }
4469 llvm_unreachable("char type should fit into long long");
4470 }
4471 }
4472
4473 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004474 if (Promotable->isSignedIntegerType())
4475 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004476 uint64_t PromotableSize = getIntWidth(Promotable);
4477 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004478 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4479 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4480}
4481
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004482/// \brief Recurses in pointer/array types until it finds an objc retainable
4483/// type and returns its ownership.
4484Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4485 while (!T.isNull()) {
4486 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4487 return T.getObjCLifetime();
4488 if (T->isArrayType())
4489 T = getBaseElementType(T);
4490 else if (const PointerType *PT = T->getAs<PointerType>())
4491 T = PT->getPointeeType();
4492 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004493 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004494 else
4495 break;
4496 }
4497
4498 return Qualifiers::OCL_None;
4499}
4500
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004501static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4502 // Incomplete enum types are not treated as integer types.
4503 // FIXME: In C++, enum types are never integer types.
4504 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4505 return ET->getDecl()->getIntegerType().getTypePtr();
4506 return NULL;
4507}
4508
Mike Stump11289f42009-09-09 15:08:12 +00004509/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004510/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004511/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004512int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004513 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4514 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004515
4516 // Unwrap enums to their underlying type.
4517 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4518 LHSC = getIntegerTypeForEnum(ET);
4519 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4520 RHSC = getIntegerTypeForEnum(ET);
4521
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004522 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004523
Chris Lattner76a00cf2008-04-06 22:59:24 +00004524 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4525 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004526
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004527 unsigned LHSRank = getIntegerRank(LHSC);
4528 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004529
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004530 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4531 if (LHSRank == RHSRank) return 0;
4532 return LHSRank > RHSRank ? 1 : -1;
4533 }
Mike Stump11289f42009-09-09 15:08:12 +00004534
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004535 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4536 if (LHSUnsigned) {
4537 // If the unsigned [LHS] type is larger, return it.
4538 if (LHSRank >= RHSRank)
4539 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004540
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004541 // If the signed type can represent all values of the unsigned type, it
4542 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004543 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004544 return -1;
4545 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004546
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004547 // If the unsigned [RHS] type is larger, return it.
4548 if (RHSRank >= LHSRank)
4549 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004550
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004551 // If the signed type can represent all values of the unsigned type, it
4552 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004553 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004554 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004555}
Anders Carlsson98f07902007-08-17 05:31:46 +00004556
Mike Stump11289f42009-09-09 15:08:12 +00004557// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004558QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004559 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004560 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004561 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004562
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004563 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004564
Anders Carlsson98f07902007-08-17 05:31:46 +00004565 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004566 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004567 // int flags;
4568 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004569 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004570 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004571 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004572 FieldTypes[3] = LongTy;
4573
Anders Carlsson98f07902007-08-17 05:31:46 +00004574 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004575 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004576 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004577 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004578 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004579 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004580 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004581 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004582 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004583 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004584 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004585 }
4586
Douglas Gregord5058122010-02-11 01:19:42 +00004587 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004588 }
Mike Stump11289f42009-09-09 15:08:12 +00004589
Anders Carlsson98f07902007-08-17 05:31:46 +00004590 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004591}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004592
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004593QualType ASTContext::getObjCSuperType() const {
4594 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004595 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004596 TUDecl->addDecl(ObjCSuperTypeDecl);
4597 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4598 }
4599 return ObjCSuperType;
4600}
4601
Douglas Gregor512b0772009-04-23 22:29:11 +00004602void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004603 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004604 assert(Rec && "Invalid CFConstantStringType");
4605 CFConstantStringTypeDecl = Rec->getDecl();
4606}
4607
Jay Foad39c79802011-01-12 09:06:06 +00004608QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004609 if (BlockDescriptorType)
4610 return getTagDeclType(BlockDescriptorType);
4611
Alp Toker2dea15b2013-12-17 01:22:38 +00004612 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004613 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004614 RD = buildImplicitRecord("__block_descriptor");
4615 RD->startDefinition();
4616
Mike Stumpd0153282009-10-20 02:12:22 +00004617 QualType FieldTypes[] = {
4618 UnsignedLongTy,
4619 UnsignedLongTy,
4620 };
4621
Craig Topperd6d31ac2013-07-15 08:24:27 +00004622 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004623 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004624 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004625 };
4626
4627 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004628 FieldDecl *Field = FieldDecl::Create(
4629 *this, RD, SourceLocation(), SourceLocation(),
4630 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4631 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004632 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004633 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004634 }
4635
Alp Toker2dea15b2013-12-17 01:22:38 +00004636 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004637
Alp Toker2dea15b2013-12-17 01:22:38 +00004638 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004639
4640 return getTagDeclType(BlockDescriptorType);
4641}
4642
Jay Foad39c79802011-01-12 09:06:06 +00004643QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004644 if (BlockDescriptorExtendedType)
4645 return getTagDeclType(BlockDescriptorExtendedType);
4646
Alp Toker2dea15b2013-12-17 01:22:38 +00004647 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004648 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004649 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4650 RD->startDefinition();
4651
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004652 QualType FieldTypes[] = {
4653 UnsignedLongTy,
4654 UnsignedLongTy,
4655 getPointerType(VoidPtrTy),
4656 getPointerType(VoidPtrTy)
4657 };
4658
Craig Topperd6d31ac2013-07-15 08:24:27 +00004659 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004660 "reserved",
4661 "Size",
4662 "CopyFuncPtr",
4663 "DestroyFuncPtr"
4664 };
4665
4666 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004667 FieldDecl *Field = FieldDecl::Create(
4668 *this, RD, SourceLocation(), SourceLocation(),
4669 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4670 /*BitWidth=*/0,
4671 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004672 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004673 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004674 }
4675
Alp Toker2dea15b2013-12-17 01:22:38 +00004676 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004677
Alp Toker2dea15b2013-12-17 01:22:38 +00004678 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004679 return getTagDeclType(BlockDescriptorExtendedType);
4680}
4681
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004682/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4683/// requires copy/dispose. Note that this must match the logic
4684/// in buildByrefHelpers.
4685bool ASTContext::BlockRequiresCopying(QualType Ty,
4686 const VarDecl *D) {
4687 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4688 const Expr *copyExpr = getBlockVarCopyInits(D);
4689 if (!copyExpr && record->hasTrivialDestructor()) return false;
4690
Mike Stump94967902009-10-21 18:16:27 +00004691 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004692 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004693
4694 if (!Ty->isObjCRetainableType()) return false;
4695
4696 Qualifiers qs = Ty.getQualifiers();
4697
4698 // If we have lifetime, that dominates.
4699 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4700 assert(getLangOpts().ObjCAutoRefCount);
4701
4702 switch (lifetime) {
4703 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4704
4705 // These are just bits as far as the runtime is concerned.
4706 case Qualifiers::OCL_ExplicitNone:
4707 case Qualifiers::OCL_Autoreleasing:
4708 return false;
4709
4710 // Tell the runtime that this is ARC __weak, called by the
4711 // byref routines.
4712 case Qualifiers::OCL_Weak:
4713 // ARC __strong __block variables need to be retained.
4714 case Qualifiers::OCL_Strong:
4715 return true;
4716 }
4717 llvm_unreachable("fell out of lifetime switch!");
4718 }
4719 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4720 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004721}
4722
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004723bool ASTContext::getByrefLifetime(QualType Ty,
4724 Qualifiers::ObjCLifetime &LifeTime,
4725 bool &HasByrefExtendedLayout) const {
4726
4727 if (!getLangOpts().ObjC1 ||
4728 getLangOpts().getGC() != LangOptions::NonGC)
4729 return false;
4730
4731 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004732 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004733 HasByrefExtendedLayout = true;
4734 LifeTime = Qualifiers::OCL_None;
4735 }
4736 else if (getLangOpts().ObjCAutoRefCount)
4737 LifeTime = Ty.getObjCLifetime();
4738 // MRR.
4739 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4740 LifeTime = Qualifiers::OCL_ExplicitNone;
4741 else
4742 LifeTime = Qualifiers::OCL_None;
4743 return true;
4744}
4745
Douglas Gregorbab8a962011-09-08 01:46:34 +00004746TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4747 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004748 ObjCInstanceTypeDecl =
4749 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004750 return ObjCInstanceTypeDecl;
4751}
4752
Anders Carlsson18acd442007-10-29 06:33:42 +00004753// This returns true if a type has been typedefed to BOOL:
4754// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004755static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004756 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004757 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4758 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004759
Anders Carlssond8499822007-10-29 05:01:08 +00004760 return false;
4761}
4762
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004763/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004764/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004765CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004766 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4767 return CharUnits::Zero();
4768
Ken Dyck40775002010-01-11 17:06:35 +00004769 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004770
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004771 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004772 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004773 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004774 // Treat arrays as pointers, since that's how they're passed in.
4775 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004776 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004777 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004778}
4779
4780static inline
4781std::string charUnitsToString(const CharUnits &CU) {
4782 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004783}
4784
John McCall351762c2011-02-07 10:33:21 +00004785/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004786/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004787std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4788 std::string S;
4789
David Chisnall950a9512009-11-17 19:33:30 +00004790 const BlockDecl *Decl = Expr->getBlockDecl();
4791 QualType BlockTy =
4792 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4793 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004794 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004795 getObjCEncodingForMethodParameter(
4796 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4797 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004798 else
Alp Toker314cc812014-01-25 16:55:45 +00004799 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004800 // Compute size of all parameters.
4801 // Start with computing size of a pointer in number of bytes.
4802 // FIXME: There might(should) be a better way of doing this computation!
4803 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004804 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4805 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004806 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004807 E = Decl->param_end(); PI != E; ++PI) {
4808 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004809 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004810 if (sz.isZero())
4811 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004812 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004813 ParmOffset += sz;
4814 }
4815 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004816 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004817 // Block pointer and offset.
4818 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004819
4820 // Argument types.
4821 ParmOffset = PtrSize;
4822 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4823 Decl->param_end(); PI != E; ++PI) {
4824 ParmVarDecl *PVDecl = *PI;
4825 QualType PType = PVDecl->getOriginalType();
4826 if (const ArrayType *AT =
4827 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4828 // Use array's original type only if it has known number of
4829 // elements.
4830 if (!isa<ConstantArrayType>(AT))
4831 PType = PVDecl->getType();
4832 } else if (PType->isFunctionType())
4833 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004834 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004835 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4836 S, true /*Extended*/);
4837 else
4838 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004839 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004840 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004841 }
John McCall351762c2011-02-07 10:33:21 +00004842
4843 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004844}
4845
Douglas Gregora9d84932011-05-27 01:19:52 +00004846bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004847 std::string& S) {
4848 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004849 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004850 CharUnits ParmOffset;
4851 // Compute size of all parameters.
4852 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4853 E = Decl->param_end(); PI != E; ++PI) {
4854 QualType PType = (*PI)->getType();
4855 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004856 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004857 continue;
4858
David Chisnall50e4eba2010-12-30 14:05:53 +00004859 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004860 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004861 ParmOffset += sz;
4862 }
4863 S += charUnitsToString(ParmOffset);
4864 ParmOffset = CharUnits::Zero();
4865
4866 // Argument types.
4867 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4868 E = Decl->param_end(); PI != E; ++PI) {
4869 ParmVarDecl *PVDecl = *PI;
4870 QualType PType = PVDecl->getOriginalType();
4871 if (const ArrayType *AT =
4872 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4873 // Use array's original type only if it has known number of
4874 // elements.
4875 if (!isa<ConstantArrayType>(AT))
4876 PType = PVDecl->getType();
4877 } else if (PType->isFunctionType())
4878 PType = PVDecl->getType();
4879 getObjCEncodingForType(PType, S);
4880 S += charUnitsToString(ParmOffset);
4881 ParmOffset += getObjCEncodingTypeSize(PType);
4882 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004883
4884 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004885}
4886
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004887/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4888/// method parameter or return type. If Extended, include class names and
4889/// block object types.
4890void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4891 QualType T, std::string& S,
4892 bool Extended) const {
4893 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4894 getObjCEncodingForTypeQualifier(QT, S);
4895 // Encode parameter type.
4896 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4897 true /*OutermostType*/,
4898 false /*EncodingProperty*/,
4899 false /*StructField*/,
4900 Extended /*EncodeBlockParameters*/,
4901 Extended /*EncodeClassNames*/);
4902}
4903
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004904/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004905/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004906bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004907 std::string& S,
4908 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004909 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004910 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004911 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4912 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004913 // Compute size of all parameters.
4914 // Start with computing size of a pointer in number of bytes.
4915 // FIXME: There might(should) be a better way of doing this computation!
4916 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004917 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004918 // The first two arguments (self and _cmd) are pointers; account for
4919 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004920 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004921 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004922 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004923 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004924 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004925 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004926 continue;
4927
Ken Dyck40775002010-01-11 17:06:35 +00004928 assert (sz.isPositive() &&
4929 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004930 ParmOffset += sz;
4931 }
Ken Dyck40775002010-01-11 17:06:35 +00004932 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004933 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004934 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004935
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004936 // Argument types.
4937 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004938 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004939 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004940 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004941 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004942 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004943 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4944 // Use array's original type only if it has known number of
4945 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004946 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004947 PType = PVDecl->getType();
4948 } else if (PType->isFunctionType())
4949 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004950 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4951 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004952 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004953 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004954 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004955
4956 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004957}
4958
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004959ObjCPropertyImplDecl *
4960ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4961 const ObjCPropertyDecl *PD,
4962 const Decl *Container) const {
4963 if (!Container)
4964 return 0;
4965 if (const ObjCCategoryImplDecl *CID =
4966 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4967 for (ObjCCategoryImplDecl::propimpl_iterator
4968 i = CID->propimpl_begin(), e = CID->propimpl_end();
4969 i != e; ++i) {
4970 ObjCPropertyImplDecl *PID = *i;
4971 if (PID->getPropertyDecl() == PD)
4972 return PID;
4973 }
4974 } else {
4975 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4976 for (ObjCCategoryImplDecl::propimpl_iterator
4977 i = OID->propimpl_begin(), e = OID->propimpl_end();
4978 i != e; ++i) {
4979 ObjCPropertyImplDecl *PID = *i;
4980 if (PID->getPropertyDecl() == PD)
4981 return PID;
4982 }
4983 }
4984 return 0;
4985}
4986
Daniel Dunbar4932b362008-08-28 04:38:10 +00004987/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004988/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004989/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4990/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004991/// Property attributes are stored as a comma-delimited C string. The simple
4992/// attributes readonly and bycopy are encoded as single characters. The
4993/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4994/// encoded as single characters, followed by an identifier. Property types
4995/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004996/// these attributes are defined by the following enumeration:
4997/// @code
4998/// enum PropertyAttributes {
4999/// kPropertyReadOnly = 'R', // property is read-only.
5000/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5001/// kPropertyByref = '&', // property is a reference to the value last assigned
5002/// kPropertyDynamic = 'D', // property is dynamic
5003/// kPropertyGetter = 'G', // followed by getter selector name
5004/// kPropertySetter = 'S', // followed by setter selector name
5005/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005006/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005007/// kPropertyWeak = 'W' // 'weak' property
5008/// kPropertyStrong = 'P' // property GC'able
5009/// kPropertyNonAtomic = 'N' // property non-atomic
5010/// };
5011/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005012void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005013 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005014 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005015 // Collect information from the property implementation decl(s).
5016 bool Dynamic = false;
5017 ObjCPropertyImplDecl *SynthesizePID = 0;
5018
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005019 if (ObjCPropertyImplDecl *PropertyImpDecl =
5020 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5021 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5022 Dynamic = true;
5023 else
5024 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005025 }
5026
5027 // FIXME: This is not very efficient.
5028 S = "T";
5029
5030 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005031 // GCC has some special rules regarding encoding of properties which
5032 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005033 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005034 true /* outermost type */,
5035 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005036
5037 if (PD->isReadOnly()) {
5038 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005039 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5040 S += ",C";
5041 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5042 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005043 } else {
5044 switch (PD->getSetterKind()) {
5045 case ObjCPropertyDecl::Assign: break;
5046 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005047 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005048 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005049 }
5050 }
5051
5052 // It really isn't clear at all what this means, since properties
5053 // are "dynamic by default".
5054 if (Dynamic)
5055 S += ",D";
5056
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005057 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5058 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005059
Daniel Dunbar4932b362008-08-28 04:38:10 +00005060 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5061 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005062 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005063 }
5064
5065 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5066 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005067 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005068 }
5069
5070 if (SynthesizePID) {
5071 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5072 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005073 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005074 }
5075
5076 // FIXME: OBJCGC: weak & strong
5077}
5078
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005079/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005080/// Another legacy compatibility encoding: 32-bit longs are encoded as
5081/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005082/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5083///
5084void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005085 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005086 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005087 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005088 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005089 else
Jay Foad39c79802011-01-12 09:06:06 +00005090 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005091 PointeeTy = IntTy;
5092 }
5093 }
5094}
5095
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005096void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005097 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005098 // We follow the behavior of gcc, expanding structures which are
5099 // directly pointed to, and expanding embedded structures. Note that
5100 // these rules are sufficient to prevent recursive encoding of the
5101 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005102 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005103 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005104}
5105
John McCall393a78d2012-12-20 02:45:14 +00005106static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5107 BuiltinType::Kind kind) {
5108 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005109 case BuiltinType::Void: return 'v';
5110 case BuiltinType::Bool: return 'B';
5111 case BuiltinType::Char_U:
5112 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005113 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005114 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005115 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005116 case BuiltinType::UInt: return 'I';
5117 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005118 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005119 case BuiltinType::UInt128: return 'T';
5120 case BuiltinType::ULongLong: return 'Q';
5121 case BuiltinType::Char_S:
5122 case BuiltinType::SChar: return 'c';
5123 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005124 case BuiltinType::WChar_S:
5125 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005126 case BuiltinType::Int: return 'i';
5127 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005128 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005129 case BuiltinType::LongLong: return 'q';
5130 case BuiltinType::Int128: return 't';
5131 case BuiltinType::Float: return 'f';
5132 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005133 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005134 case BuiltinType::NullPtr: return '*'; // like char*
5135
5136 case BuiltinType::Half:
5137 // FIXME: potentially need @encodes for these!
5138 return ' ';
5139
5140 case BuiltinType::ObjCId:
5141 case BuiltinType::ObjCClass:
5142 case BuiltinType::ObjCSel:
5143 llvm_unreachable("@encoding ObjC primitive type");
5144
5145 // OpenCL and placeholder types don't need @encodings.
5146 case BuiltinType::OCLImage1d:
5147 case BuiltinType::OCLImage1dArray:
5148 case BuiltinType::OCLImage1dBuffer:
5149 case BuiltinType::OCLImage2d:
5150 case BuiltinType::OCLImage2dArray:
5151 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005152 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005153 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005154 case BuiltinType::Dependent:
5155#define BUILTIN_TYPE(KIND, ID)
5156#define PLACEHOLDER_TYPE(KIND, ID) \
5157 case BuiltinType::KIND:
5158#include "clang/AST/BuiltinTypes.def"
5159 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005160 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005161 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005162}
5163
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005164static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5165 EnumDecl *Enum = ET->getDecl();
5166
5167 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5168 if (!Enum->isFixed())
5169 return 'i';
5170
5171 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005172 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5173 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005174}
5175
Jay Foad39c79802011-01-12 09:06:06 +00005176static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005177 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005178 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005179 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005180 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5181 // The GNU runtime requires more information; bitfields are encoded as b,
5182 // then the offset (in bits) of the first element, then the type of the
5183 // bitfield, then the size in bits. For example, in this structure:
5184 //
5185 // struct
5186 // {
5187 // int integer;
5188 // int flags:2;
5189 // };
5190 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5191 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5192 // information is not especially sensible, but we're stuck with it for
5193 // compatibility with GCC, although providing it breaks anything that
5194 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005195 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005196 const RecordDecl *RD = FD->getParent();
5197 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005198 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005199 if (const EnumType *ET = T->getAs<EnumType>())
5200 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005201 else {
5202 const BuiltinType *BT = T->castAs<BuiltinType>();
5203 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5204 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005205 }
Richard Smithcaf33902011-10-10 18:28:20 +00005206 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005207}
5208
Daniel Dunbar07d07852009-10-18 21:17:35 +00005209// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005210void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5211 bool ExpandPointedToStructures,
5212 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005213 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005214 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005215 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005216 bool StructField,
5217 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005218 bool EncodeClassNames,
5219 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005220 CanQualType CT = getCanonicalType(T);
5221 switch (CT->getTypeClass()) {
5222 case Type::Builtin:
5223 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005224 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005225 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005226 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5227 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5228 else
5229 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005230 return;
Mike Stump11289f42009-09-09 15:08:12 +00005231
John McCall393a78d2012-12-20 02:45:14 +00005232 case Type::Complex: {
5233 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005234 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005235 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005236 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005237 return;
5238 }
John McCall393a78d2012-12-20 02:45:14 +00005239
5240 case Type::Atomic: {
5241 const AtomicType *AT = T->castAs<AtomicType>();
5242 S += 'A';
5243 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5244 false, false);
5245 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005246 }
John McCall393a78d2012-12-20 02:45:14 +00005247
5248 // encoding for pointer or reference types.
5249 case Type::Pointer:
5250 case Type::LValueReference:
5251 case Type::RValueReference: {
5252 QualType PointeeTy;
5253 if (isa<PointerType>(CT)) {
5254 const PointerType *PT = T->castAs<PointerType>();
5255 if (PT->isObjCSelType()) {
5256 S += ':';
5257 return;
5258 }
5259 PointeeTy = PT->getPointeeType();
5260 } else {
5261 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5262 }
5263
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005264 bool isReadOnly = false;
5265 // For historical/compatibility reasons, the read-only qualifier of the
5266 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5267 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005268 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005269 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005270 if (OutermostType && T.isConstQualified()) {
5271 isReadOnly = true;
5272 S += 'r';
5273 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005274 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005275 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005276 while (P->getAs<PointerType>())
5277 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005278 if (P.isConstQualified()) {
5279 isReadOnly = true;
5280 S += 'r';
5281 }
5282 }
5283 if (isReadOnly) {
5284 // Another legacy compatibility encoding. Some ObjC qualifier and type
5285 // combinations need to be rearranged.
5286 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005287 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005288 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005289 }
Mike Stump11289f42009-09-09 15:08:12 +00005290
Anders Carlssond8499822007-10-29 05:01:08 +00005291 if (PointeeTy->isCharType()) {
5292 // char pointer types should be encoded as '*' unless it is a
5293 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005294 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005295 S += '*';
5296 return;
5297 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005298 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005299 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5300 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5301 S += '#';
5302 return;
5303 }
5304 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5305 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5306 S += '@';
5307 return;
5308 }
5309 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005310 }
Anders Carlssond8499822007-10-29 05:01:08 +00005311 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005312 getLegacyIntegralTypeEncoding(PointeeTy);
5313
Mike Stump11289f42009-09-09 15:08:12 +00005314 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005315 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005316 return;
5317 }
John McCall393a78d2012-12-20 02:45:14 +00005318
5319 case Type::ConstantArray:
5320 case Type::IncompleteArray:
5321 case Type::VariableArray: {
5322 const ArrayType *AT = cast<ArrayType>(CT);
5323
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005324 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005325 // Incomplete arrays are encoded as a pointer to the array element.
5326 S += '^';
5327
Mike Stump11289f42009-09-09 15:08:12 +00005328 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005329 false, ExpandStructures, FD);
5330 } else {
5331 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005332
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005333 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5334 S += llvm::utostr(CAT->getSize().getZExtValue());
5335 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005336 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005337 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5338 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005339 S += '0';
5340 }
Mike Stump11289f42009-09-09 15:08:12 +00005341
5342 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005343 false, ExpandStructures, FD);
5344 S += ']';
5345 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005346 return;
5347 }
Mike Stump11289f42009-09-09 15:08:12 +00005348
John McCall393a78d2012-12-20 02:45:14 +00005349 case Type::FunctionNoProto:
5350 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005351 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005352 return;
Mike Stump11289f42009-09-09 15:08:12 +00005353
John McCall393a78d2012-12-20 02:45:14 +00005354 case Type::Record: {
5355 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005356 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005357 // Anonymous structures print as '?'
5358 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5359 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005360 if (ClassTemplateSpecializationDecl *Spec
5361 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5362 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005363 llvm::raw_string_ostream OS(S);
5364 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005365 TemplateArgs.data(),
5366 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005367 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005368 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005369 } else {
5370 S += '?';
5371 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005372 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005373 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005374 if (!RDecl->isUnion()) {
5375 getObjCEncodingForStructureImpl(RDecl, S, FD);
5376 } else {
5377 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5378 FieldEnd = RDecl->field_end();
5379 Field != FieldEnd; ++Field) {
5380 if (FD) {
5381 S += '"';
5382 S += Field->getNameAsString();
5383 S += '"';
5384 }
Mike Stump11289f42009-09-09 15:08:12 +00005385
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005386 // Special case bit-fields.
5387 if (Field->isBitField()) {
5388 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005389 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005390 } else {
5391 QualType qt = Field->getType();
5392 getLegacyIntegralTypeEncoding(qt);
5393 getObjCEncodingForTypeImpl(qt, S, false, true,
5394 FD, /*OutermostType*/false,
5395 /*EncodingProperty*/false,
5396 /*StructField*/true);
5397 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005398 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005399 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005400 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005401 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005402 return;
5403 }
Mike Stump11289f42009-09-09 15:08:12 +00005404
John McCall393a78d2012-12-20 02:45:14 +00005405 case Type::BlockPointer: {
5406 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005407 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005408 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005409 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005410
5411 S += '<';
5412 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005413 getObjCEncodingForTypeImpl(
5414 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5415 FD, false /* OutermostType */, EncodingProperty,
5416 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005417 // Block self
5418 S += "@?";
5419 // Block parameters
5420 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005421 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5422 E = FPT->param_type_end();
5423 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005424 getObjCEncodingForTypeImpl(*I, S,
5425 ExpandPointedToStructures,
5426 ExpandStructures,
5427 FD,
5428 false /* OutermostType */,
5429 EncodingProperty,
5430 false /* StructField */,
5431 EncodeBlockParameters,
5432 EncodeClassNames);
5433 }
5434 }
5435 S += '>';
5436 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005437 return;
5438 }
Mike Stump11289f42009-09-09 15:08:12 +00005439
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005440 case Type::ObjCObject: {
5441 // hack to match legacy encoding of *id and *Class
5442 QualType Ty = getObjCObjectPointerType(CT);
5443 if (Ty->isObjCIdType()) {
5444 S += "{objc_object=}";
5445 return;
5446 }
5447 else if (Ty->isObjCClassType()) {
5448 S += "{objc_class=}";
5449 return;
5450 }
5451 }
5452
John McCall393a78d2012-12-20 02:45:14 +00005453 case Type::ObjCInterface: {
5454 // Ignore protocol qualifiers when mangling at this level.
5455 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005456
John McCall393a78d2012-12-20 02:45:14 +00005457 // The assumption seems to be that this assert will succeed
5458 // because nested levels will have filtered out 'id' and 'Class'.
5459 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005460 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005461 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005462 S += '{';
5463 const IdentifierInfo *II = OI->getIdentifier();
5464 S += II->getName();
5465 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005466 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005467 DeepCollectObjCIvars(OI, true, Ivars);
5468 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005469 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005470 if (Field->isBitField())
5471 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005472 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005473 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5474 false, false, false, false, false,
5475 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005476 }
5477 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005478 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005479 }
Mike Stump11289f42009-09-09 15:08:12 +00005480
John McCall393a78d2012-12-20 02:45:14 +00005481 case Type::ObjCObjectPointer: {
5482 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005483 if (OPT->isObjCIdType()) {
5484 S += '@';
5485 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005486 }
Mike Stump11289f42009-09-09 15:08:12 +00005487
Steve Narofff0c86112009-10-28 22:03:49 +00005488 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5489 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5490 // Since this is a binary compatibility issue, need to consult with runtime
5491 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005492 S += '#';
5493 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005494 }
Mike Stump11289f42009-09-09 15:08:12 +00005495
Chris Lattnere7cabb92009-07-13 00:10:46 +00005496 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005497 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005498 ExpandPointedToStructures,
5499 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005500 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005501 // Note that we do extended encoding of protocol qualifer list
5502 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005503 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005504 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5505 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005506 S += '<';
5507 S += (*I)->getNameAsString();
5508 S += '>';
5509 }
5510 S += '"';
5511 }
5512 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005513 }
Mike Stump11289f42009-09-09 15:08:12 +00005514
Chris Lattnere7cabb92009-07-13 00:10:46 +00005515 QualType PointeeTy = OPT->getPointeeType();
5516 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005517 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5518 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005519 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005520 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005521 // {...};
5522 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005523 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005524 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005525 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5526 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5527 DeepCollectObjCIvars(OI, true, Ivars);
5528 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5529 if (cast<FieldDecl>(Ivars[i]) == FD) {
5530 S += '{';
5531 S += OI->getIdentifier()->getName();
5532 S += '}';
5533 return;
5534 }
5535 }
5536 }
Mike Stump11289f42009-09-09 15:08:12 +00005537 getObjCEncodingForTypeImpl(PointeeTy, S,
5538 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005539 NULL,
5540 false, false, false, false, false,
5541 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005542 return;
5543 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005544
5545 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005546 if (OPT->getInterfaceDecl() &&
5547 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005548 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005549 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005550 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5551 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005552 S += '<';
5553 S += (*I)->getNameAsString();
5554 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005555 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005556 S += '"';
5557 }
5558 return;
5559 }
Mike Stump11289f42009-09-09 15:08:12 +00005560
John McCalla9e6e8d2010-05-17 23:56:34 +00005561 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005562 // FIXME: we shoul do better than that. 'M' is available.
5563 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005564 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005565
John McCall393a78d2012-12-20 02:45:14 +00005566 case Type::Vector:
5567 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005568 // This matches gcc's encoding, even though technically it is
5569 // insufficient.
5570 // FIXME. We should do a better job than gcc.
5571 return;
John McCall393a78d2012-12-20 02:45:14 +00005572
Richard Smith27d807c2013-04-30 13:56:41 +00005573 case Type::Auto:
5574 // We could see an undeduced auto type here during error recovery.
5575 // Just ignore it.
5576 return;
5577
John McCall393a78d2012-12-20 02:45:14 +00005578#define ABSTRACT_TYPE(KIND, BASE)
5579#define TYPE(KIND, BASE)
5580#define DEPENDENT_TYPE(KIND, BASE) \
5581 case Type::KIND:
5582#define NON_CANONICAL_TYPE(KIND, BASE) \
5583 case Type::KIND:
5584#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5585 case Type::KIND:
5586#include "clang/AST/TypeNodes.def"
5587 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005588 }
John McCall393a78d2012-12-20 02:45:14 +00005589 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005590}
5591
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005592void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5593 std::string &S,
5594 const FieldDecl *FD,
5595 bool includeVBases) const {
5596 assert(RDecl && "Expected non-null RecordDecl");
5597 assert(!RDecl->isUnion() && "Should not be called for unions");
5598 if (!RDecl->getDefinition())
5599 return;
5600
5601 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5602 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5603 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5604
5605 if (CXXRec) {
5606 for (CXXRecordDecl::base_class_iterator
5607 BI = CXXRec->bases_begin(),
5608 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5609 if (!BI->isVirtual()) {
5610 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005611 if (base->isEmpty())
5612 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005613 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005614 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5615 std::make_pair(offs, base));
5616 }
5617 }
5618 }
5619
5620 unsigned i = 0;
5621 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5622 FieldEnd = RDecl->field_end();
5623 Field != FieldEnd; ++Field, ++i) {
5624 uint64_t offs = layout.getFieldOffset(i);
5625 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005626 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005627 }
5628
5629 if (CXXRec && includeVBases) {
5630 for (CXXRecordDecl::base_class_iterator
5631 BI = CXXRec->vbases_begin(),
5632 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5633 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005634 if (base->isEmpty())
5635 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005636 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005637 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5638 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005639 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5640 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005641 }
5642 }
5643
5644 CharUnits size;
5645 if (CXXRec) {
5646 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5647 } else {
5648 size = layout.getSize();
5649 }
5650
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005651#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005652 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005653#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005654 std::multimap<uint64_t, NamedDecl *>::iterator
5655 CurLayObj = FieldOrBaseOffsets.begin();
5656
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005657 if (CXXRec && CXXRec->isDynamicClass() &&
5658 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005659 if (FD) {
5660 S += "\"_vptr$";
5661 std::string recname = CXXRec->getNameAsString();
5662 if (recname.empty()) recname = "?";
5663 S += recname;
5664 S += '"';
5665 }
5666 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005667#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005668 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005669#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005670 }
5671
5672 if (!RDecl->hasFlexibleArrayMember()) {
5673 // Mark the end of the structure.
5674 uint64_t offs = toBits(size);
5675 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5676 std::make_pair(offs, (NamedDecl*)0));
5677 }
5678
5679 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005680#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005681 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005682 if (CurOffs < CurLayObj->first) {
5683 uint64_t padding = CurLayObj->first - CurOffs;
5684 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5685 // packing/alignment of members is different that normal, in which case
5686 // the encoding will be out-of-sync with the real layout.
5687 // If the runtime switches to just consider the size of types without
5688 // taking into account alignment, we could make padding explicit in the
5689 // encoding (e.g. using arrays of chars). The encoding strings would be
5690 // longer then though.
5691 CurOffs += padding;
5692 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005693#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005694
5695 NamedDecl *dcl = CurLayObj->second;
5696 if (dcl == 0)
5697 break; // reached end of structure.
5698
5699 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5700 // We expand the bases without their virtual bases since those are going
5701 // in the initial structure. Note that this differs from gcc which
5702 // expands virtual bases each time one is encountered in the hierarchy,
5703 // making the encoding type bigger than it really is.
5704 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005705 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005706#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005707 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005708#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005709 } else {
5710 FieldDecl *field = cast<FieldDecl>(dcl);
5711 if (FD) {
5712 S += '"';
5713 S += field->getNameAsString();
5714 S += '"';
5715 }
5716
5717 if (field->isBitField()) {
5718 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005719#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005720 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005721#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005722 } else {
5723 QualType qt = field->getType();
5724 getLegacyIntegralTypeEncoding(qt);
5725 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5726 /*OutermostType*/false,
5727 /*EncodingProperty*/false,
5728 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005729#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005730 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005731#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005732 }
5733 }
5734 }
5735}
5736
Mike Stump11289f42009-09-09 15:08:12 +00005737void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005738 std::string& S) const {
5739 if (QT & Decl::OBJC_TQ_In)
5740 S += 'n';
5741 if (QT & Decl::OBJC_TQ_Inout)
5742 S += 'N';
5743 if (QT & Decl::OBJC_TQ_Out)
5744 S += 'o';
5745 if (QT & Decl::OBJC_TQ_Bycopy)
5746 S += 'O';
5747 if (QT & Decl::OBJC_TQ_Byref)
5748 S += 'R';
5749 if (QT & Decl::OBJC_TQ_Oneway)
5750 S += 'V';
5751}
5752
Douglas Gregor3ea72692011-08-12 05:46:01 +00005753TypedefDecl *ASTContext::getObjCIdDecl() const {
5754 if (!ObjCIdDecl) {
5755 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5756 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005757 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005758 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005759 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005760}
5761
Douglas Gregor52e02802011-08-12 06:17:30 +00005762TypedefDecl *ASTContext::getObjCSelDecl() const {
5763 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005764 QualType T = getPointerType(ObjCBuiltinSelTy);
5765 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005766 }
5767 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005768}
5769
Douglas Gregor0a586182011-08-12 05:59:41 +00005770TypedefDecl *ASTContext::getObjCClassDecl() const {
5771 if (!ObjCClassDecl) {
5772 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5773 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005774 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005775 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005776 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005777}
5778
Douglas Gregord53ae832012-01-17 18:09:05 +00005779ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5780 if (!ObjCProtocolClassDecl) {
5781 ObjCProtocolClassDecl
5782 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5783 SourceLocation(),
5784 &Idents.get("Protocol"),
5785 /*PrevDecl=*/0,
5786 SourceLocation(), true);
5787 }
5788
5789 return ObjCProtocolClassDecl;
5790}
5791
Meador Inge5d3fb222012-06-16 03:34:49 +00005792//===----------------------------------------------------------------------===//
5793// __builtin_va_list Construction Functions
5794//===----------------------------------------------------------------------===//
5795
5796static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5797 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005798 QualType T = Context->getPointerType(Context->CharTy);
5799 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005800}
5801
5802static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5803 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005804 QualType T = Context->getPointerType(Context->VoidTy);
5805 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005806}
5807
Tim Northover9bb857a2013-01-31 12:13:10 +00005808static TypedefDecl *
5809CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005810 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005811 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005812 if (Context->getLangOpts().CPlusPlus) {
5813 // namespace std { struct __va_list {
5814 NamespaceDecl *NS;
5815 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5816 Context->getTranslationUnitDecl(),
5817 /*Inline*/false, SourceLocation(),
5818 SourceLocation(), &Context->Idents.get("std"),
5819 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005820 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005821 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005822 }
5823
5824 VaListTagDecl->startDefinition();
5825
5826 const size_t NumFields = 5;
5827 QualType FieldTypes[NumFields];
5828 const char *FieldNames[NumFields];
5829
5830 // void *__stack;
5831 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5832 FieldNames[0] = "__stack";
5833
5834 // void *__gr_top;
5835 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5836 FieldNames[1] = "__gr_top";
5837
5838 // void *__vr_top;
5839 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5840 FieldNames[2] = "__vr_top";
5841
5842 // int __gr_offs;
5843 FieldTypes[3] = Context->IntTy;
5844 FieldNames[3] = "__gr_offs";
5845
5846 // int __vr_offs;
5847 FieldTypes[4] = Context->IntTy;
5848 FieldNames[4] = "__vr_offs";
5849
5850 // Create fields
5851 for (unsigned i = 0; i < NumFields; ++i) {
5852 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5853 VaListTagDecl,
5854 SourceLocation(),
5855 SourceLocation(),
5856 &Context->Idents.get(FieldNames[i]),
5857 FieldTypes[i], /*TInfo=*/0,
5858 /*BitWidth=*/0,
5859 /*Mutable=*/false,
5860 ICIS_NoInit);
5861 Field->setAccess(AS_public);
5862 VaListTagDecl->addDecl(Field);
5863 }
5864 VaListTagDecl->completeDefinition();
5865 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5866 Context->VaListTagTy = VaListTagType;
5867
5868 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005869 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005870}
5871
Meador Inge5d3fb222012-06-16 03:34:49 +00005872static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5873 // typedef struct __va_list_tag {
5874 RecordDecl *VaListTagDecl;
5875
Alp Toker2dea15b2013-12-17 01:22:38 +00005876 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005877 VaListTagDecl->startDefinition();
5878
5879 const size_t NumFields = 5;
5880 QualType FieldTypes[NumFields];
5881 const char *FieldNames[NumFields];
5882
5883 // unsigned char gpr;
5884 FieldTypes[0] = Context->UnsignedCharTy;
5885 FieldNames[0] = "gpr";
5886
5887 // unsigned char fpr;
5888 FieldTypes[1] = Context->UnsignedCharTy;
5889 FieldNames[1] = "fpr";
5890
5891 // unsigned short reserved;
5892 FieldTypes[2] = Context->UnsignedShortTy;
5893 FieldNames[2] = "reserved";
5894
5895 // void* overflow_arg_area;
5896 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5897 FieldNames[3] = "overflow_arg_area";
5898
5899 // void* reg_save_area;
5900 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5901 FieldNames[4] = "reg_save_area";
5902
5903 // Create fields
5904 for (unsigned i = 0; i < NumFields; ++i) {
5905 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5906 SourceLocation(),
5907 SourceLocation(),
5908 &Context->Idents.get(FieldNames[i]),
5909 FieldTypes[i], /*TInfo=*/0,
5910 /*BitWidth=*/0,
5911 /*Mutable=*/false,
5912 ICIS_NoInit);
5913 Field->setAccess(AS_public);
5914 VaListTagDecl->addDecl(Field);
5915 }
5916 VaListTagDecl->completeDefinition();
5917 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005918 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005919
5920 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005921 TypedefDecl *VaListTagTypedefDecl =
5922 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5923
Meador Inge5d3fb222012-06-16 03:34:49 +00005924 QualType VaListTagTypedefType =
5925 Context->getTypedefType(VaListTagTypedefDecl);
5926
5927 // typedef __va_list_tag __builtin_va_list[1];
5928 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5929 QualType VaListTagArrayType
5930 = Context->getConstantArrayType(VaListTagTypedefType,
5931 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005932 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005933}
5934
5935static TypedefDecl *
5936CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5937 // typedef struct __va_list_tag {
5938 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005939 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005940 VaListTagDecl->startDefinition();
5941
5942 const size_t NumFields = 4;
5943 QualType FieldTypes[NumFields];
5944 const char *FieldNames[NumFields];
5945
5946 // unsigned gp_offset;
5947 FieldTypes[0] = Context->UnsignedIntTy;
5948 FieldNames[0] = "gp_offset";
5949
5950 // unsigned fp_offset;
5951 FieldTypes[1] = Context->UnsignedIntTy;
5952 FieldNames[1] = "fp_offset";
5953
5954 // void* overflow_arg_area;
5955 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5956 FieldNames[2] = "overflow_arg_area";
5957
5958 // void* reg_save_area;
5959 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5960 FieldNames[3] = "reg_save_area";
5961
5962 // Create fields
5963 for (unsigned i = 0; i < NumFields; ++i) {
5964 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5965 VaListTagDecl,
5966 SourceLocation(),
5967 SourceLocation(),
5968 &Context->Idents.get(FieldNames[i]),
5969 FieldTypes[i], /*TInfo=*/0,
5970 /*BitWidth=*/0,
5971 /*Mutable=*/false,
5972 ICIS_NoInit);
5973 Field->setAccess(AS_public);
5974 VaListTagDecl->addDecl(Field);
5975 }
5976 VaListTagDecl->completeDefinition();
5977 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005978 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005979
5980 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005981 TypedefDecl *VaListTagTypedefDecl =
5982 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5983
Meador Inge5d3fb222012-06-16 03:34:49 +00005984 QualType VaListTagTypedefType =
5985 Context->getTypedefType(VaListTagTypedefDecl);
5986
5987 // typedef __va_list_tag __builtin_va_list[1];
5988 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5989 QualType VaListTagArrayType
5990 = Context->getConstantArrayType(VaListTagTypedefType,
5991 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005992 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005993}
5994
5995static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5996 // typedef int __builtin_va_list[4];
5997 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5998 QualType IntArrayType
5999 = Context->getConstantArrayType(Context->IntTy,
6000 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006001 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006002}
6003
Logan Chien57086ce2012-10-10 06:56:20 +00006004static TypedefDecl *
6005CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006006 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006007 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006008 if (Context->getLangOpts().CPlusPlus) {
6009 // namespace std { struct __va_list {
6010 NamespaceDecl *NS;
6011 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6012 Context->getTranslationUnitDecl(),
6013 /*Inline*/false, SourceLocation(),
6014 SourceLocation(), &Context->Idents.get("std"),
6015 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006016 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006017 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006018 }
6019
6020 VaListDecl->startDefinition();
6021
6022 // void * __ap;
6023 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6024 VaListDecl,
6025 SourceLocation(),
6026 SourceLocation(),
6027 &Context->Idents.get("__ap"),
6028 Context->getPointerType(Context->VoidTy),
6029 /*TInfo=*/0,
6030 /*BitWidth=*/0,
6031 /*Mutable=*/false,
6032 ICIS_NoInit);
6033 Field->setAccess(AS_public);
6034 VaListDecl->addDecl(Field);
6035
6036 // };
6037 VaListDecl->completeDefinition();
6038
6039 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006040 QualType T = Context->getRecordType(VaListDecl);
6041 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006042}
6043
Ulrich Weigand47445072013-05-06 16:26:41 +00006044static TypedefDecl *
6045CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6046 // typedef struct __va_list_tag {
6047 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006048 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006049 VaListTagDecl->startDefinition();
6050
6051 const size_t NumFields = 4;
6052 QualType FieldTypes[NumFields];
6053 const char *FieldNames[NumFields];
6054
6055 // long __gpr;
6056 FieldTypes[0] = Context->LongTy;
6057 FieldNames[0] = "__gpr";
6058
6059 // long __fpr;
6060 FieldTypes[1] = Context->LongTy;
6061 FieldNames[1] = "__fpr";
6062
6063 // void *__overflow_arg_area;
6064 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6065 FieldNames[2] = "__overflow_arg_area";
6066
6067 // void *__reg_save_area;
6068 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6069 FieldNames[3] = "__reg_save_area";
6070
6071 // Create fields
6072 for (unsigned i = 0; i < NumFields; ++i) {
6073 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6074 VaListTagDecl,
6075 SourceLocation(),
6076 SourceLocation(),
6077 &Context->Idents.get(FieldNames[i]),
6078 FieldTypes[i], /*TInfo=*/0,
6079 /*BitWidth=*/0,
6080 /*Mutable=*/false,
6081 ICIS_NoInit);
6082 Field->setAccess(AS_public);
6083 VaListTagDecl->addDecl(Field);
6084 }
6085 VaListTagDecl->completeDefinition();
6086 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6087 Context->VaListTagTy = VaListTagType;
6088
6089 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006090 TypedefDecl *VaListTagTypedefDecl =
6091 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006092 QualType VaListTagTypedefType =
6093 Context->getTypedefType(VaListTagTypedefDecl);
6094
6095 // typedef __va_list_tag __builtin_va_list[1];
6096 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6097 QualType VaListTagArrayType
6098 = Context->getConstantArrayType(VaListTagTypedefType,
6099 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006100
Alp Toker56b5cc92013-12-15 10:36:26 +00006101 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006102}
6103
Meador Inge5d3fb222012-06-16 03:34:49 +00006104static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6105 TargetInfo::BuiltinVaListKind Kind) {
6106 switch (Kind) {
6107 case TargetInfo::CharPtrBuiltinVaList:
6108 return CreateCharPtrBuiltinVaListDecl(Context);
6109 case TargetInfo::VoidPtrBuiltinVaList:
6110 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006111 case TargetInfo::AArch64ABIBuiltinVaList:
6112 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006113 case TargetInfo::PowerABIBuiltinVaList:
6114 return CreatePowerABIBuiltinVaListDecl(Context);
6115 case TargetInfo::X86_64ABIBuiltinVaList:
6116 return CreateX86_64ABIBuiltinVaListDecl(Context);
6117 case TargetInfo::PNaClABIBuiltinVaList:
6118 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006119 case TargetInfo::AAPCSABIBuiltinVaList:
6120 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006121 case TargetInfo::SystemZBuiltinVaList:
6122 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006123 }
6124
6125 llvm_unreachable("Unhandled __builtin_va_list type kind");
6126}
6127
6128TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006129 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006130 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006131 assert(BuiltinVaListDecl->isImplicit());
6132 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006133
6134 return BuiltinVaListDecl;
6135}
6136
Meador Ingecfb60902012-07-01 15:57:25 +00006137QualType ASTContext::getVaListTagType() const {
6138 // Force the creation of VaListTagTy by building the __builtin_va_list
6139 // declaration.
6140 if (VaListTagTy.isNull())
6141 (void) getBuiltinVaListDecl();
6142
6143 return VaListTagTy;
6144}
6145
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006146void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006147 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006148 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006149
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006150 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006151}
6152
John McCalld28ae272009-12-02 08:04:21 +00006153/// \brief Retrieve the template name that corresponds to a non-empty
6154/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006155TemplateName
6156ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6157 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006158 unsigned size = End - Begin;
6159 assert(size > 1 && "set is not overloaded!");
6160
6161 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6162 size * sizeof(FunctionTemplateDecl*));
6163 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6164
6165 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006166 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006167 NamedDecl *D = *I;
6168 assert(isa<FunctionTemplateDecl>(D) ||
6169 (isa<UsingShadowDecl>(D) &&
6170 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6171 *Storage++ = D;
6172 }
6173
6174 return TemplateName(OT);
6175}
6176
Douglas Gregordc572a32009-03-30 22:58:21 +00006177/// \brief Retrieve the template name that represents a qualified
6178/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006179TemplateName
6180ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6181 bool TemplateKeyword,
6182 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006183 assert(NNS && "Missing nested-name-specifier in qualified template name");
6184
Douglas Gregorc42075a2010-02-04 18:10:26 +00006185 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006186 llvm::FoldingSetNodeID ID;
6187 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6188
6189 void *InsertPos = 0;
6190 QualifiedTemplateName *QTN =
6191 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6192 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006193 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6194 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006195 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6196 }
6197
6198 return TemplateName(QTN);
6199}
6200
6201/// \brief Retrieve the template name that represents a dependent
6202/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006203TemplateName
6204ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6205 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006206 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006207 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006208
6209 llvm::FoldingSetNodeID ID;
6210 DependentTemplateName::Profile(ID, NNS, Name);
6211
6212 void *InsertPos = 0;
6213 DependentTemplateName *QTN =
6214 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6215
6216 if (QTN)
6217 return TemplateName(QTN);
6218
6219 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6220 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006221 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6222 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006223 } else {
6224 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006225 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6226 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006227 DependentTemplateName *CheckQTN =
6228 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6229 assert(!CheckQTN && "Dependent type name canonicalization broken");
6230 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006231 }
6232
6233 DependentTemplateNames.InsertNode(QTN, InsertPos);
6234 return TemplateName(QTN);
6235}
6236
Douglas Gregor71395fa2009-11-04 00:56:37 +00006237/// \brief Retrieve the template name that represents a dependent
6238/// template name such as \c MetaFun::template operator+.
6239TemplateName
6240ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006241 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006242 assert((!NNS || NNS->isDependent()) &&
6243 "Nested name specifier must be dependent");
6244
6245 llvm::FoldingSetNodeID ID;
6246 DependentTemplateName::Profile(ID, NNS, Operator);
6247
6248 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006249 DependentTemplateName *QTN
6250 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006251
6252 if (QTN)
6253 return TemplateName(QTN);
6254
6255 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6256 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006257 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6258 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006259 } else {
6260 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006261 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6262 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006263
6264 DependentTemplateName *CheckQTN
6265 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6266 assert(!CheckQTN && "Dependent template name canonicalization broken");
6267 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006268 }
6269
6270 DependentTemplateNames.InsertNode(QTN, InsertPos);
6271 return TemplateName(QTN);
6272}
6273
Douglas Gregor5590be02011-01-15 06:45:20 +00006274TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006275ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6276 TemplateName replacement) const {
6277 llvm::FoldingSetNodeID ID;
6278 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6279
6280 void *insertPos = 0;
6281 SubstTemplateTemplateParmStorage *subst
6282 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6283
6284 if (!subst) {
6285 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6286 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6287 }
6288
6289 return TemplateName(subst);
6290}
6291
6292TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006293ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6294 const TemplateArgument &ArgPack) const {
6295 ASTContext &Self = const_cast<ASTContext &>(*this);
6296 llvm::FoldingSetNodeID ID;
6297 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6298
6299 void *InsertPos = 0;
6300 SubstTemplateTemplateParmPackStorage *Subst
6301 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6302
6303 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006304 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006305 ArgPack.pack_size(),
6306 ArgPack.pack_begin());
6307 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6308 }
6309
6310 return TemplateName(Subst);
6311}
6312
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006313/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006314/// TargetInfo, produce the corresponding type. The unsigned @p Type
6315/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006316CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006317 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006318 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006319 case TargetInfo::SignedChar: return SignedCharTy;
6320 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006321 case TargetInfo::SignedShort: return ShortTy;
6322 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6323 case TargetInfo::SignedInt: return IntTy;
6324 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6325 case TargetInfo::SignedLong: return LongTy;
6326 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6327 case TargetInfo::SignedLongLong: return LongLongTy;
6328 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6329 }
6330
David Blaikie83d382b2011-09-23 05:06:16 +00006331 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006332}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006333
6334//===----------------------------------------------------------------------===//
6335// Type Predicates.
6336//===----------------------------------------------------------------------===//
6337
Fariborz Jahanian96207692009-02-18 21:49:28 +00006338/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6339/// garbage collection attribute.
6340///
John McCall553d45a2011-01-12 00:34:59 +00006341Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006342 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006343 return Qualifiers::GCNone;
6344
David Blaikiebbafb8a2012-03-11 07:00:24 +00006345 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006346 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6347
6348 // Default behaviour under objective-C's gc is for ObjC pointers
6349 // (or pointers to them) be treated as though they were declared
6350 // as __strong.
6351 if (GCAttrs == Qualifiers::GCNone) {
6352 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6353 return Qualifiers::Strong;
6354 else if (Ty->isPointerType())
6355 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6356 } else {
6357 // It's not valid to set GC attributes on anything that isn't a
6358 // pointer.
6359#ifndef NDEBUG
6360 QualType CT = Ty->getCanonicalTypeInternal();
6361 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6362 CT = AT->getElementType();
6363 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6364#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006365 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006366 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006367}
6368
Chris Lattner49af6a42008-04-07 06:51:04 +00006369//===----------------------------------------------------------------------===//
6370// Type Compatibility Testing
6371//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006372
Mike Stump11289f42009-09-09 15:08:12 +00006373/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006374/// compatible.
6375static bool areCompatVectorTypes(const VectorType *LHS,
6376 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006377 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006378 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006379 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006380}
6381
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006382bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6383 QualType SecondVec) {
6384 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6385 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6386
6387 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6388 return true;
6389
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006390 // Treat Neon vector types and most AltiVec vector types as if they are the
6391 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006392 const VectorType *First = FirstVec->getAs<VectorType>();
6393 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006394 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006395 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006396 First->getVectorKind() != VectorType::AltiVecPixel &&
6397 First->getVectorKind() != VectorType::AltiVecBool &&
6398 Second->getVectorKind() != VectorType::AltiVecPixel &&
6399 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006400 return true;
6401
6402 return false;
6403}
6404
Steve Naroff8e6aee52009-07-23 01:01:38 +00006405//===----------------------------------------------------------------------===//
6406// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6407//===----------------------------------------------------------------------===//
6408
6409/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6410/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006411bool
6412ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6413 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006414 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006415 return true;
6416 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6417 E = rProto->protocol_end(); PI != E; ++PI)
6418 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6419 return true;
6420 return false;
6421}
6422
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006423/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6424/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006425bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6426 QualType rhs) {
6427 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6428 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6429 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6430
6431 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6432 E = lhsQID->qual_end(); I != E; ++I) {
6433 bool match = false;
6434 ObjCProtocolDecl *lhsProto = *I;
6435 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6436 E = rhsOPT->qual_end(); J != E; ++J) {
6437 ObjCProtocolDecl *rhsProto = *J;
6438 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6439 match = true;
6440 break;
6441 }
6442 }
6443 if (!match)
6444 return false;
6445 }
6446 return true;
6447}
6448
Steve Naroff8e6aee52009-07-23 01:01:38 +00006449/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6450/// ObjCQualifiedIDType.
6451bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6452 bool compare) {
6453 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006454 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006455 lhs->isObjCIdType() || lhs->isObjCClassType())
6456 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006457 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006458 rhs->isObjCIdType() || rhs->isObjCClassType())
6459 return true;
6460
6461 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006462 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006463
Steve Naroff8e6aee52009-07-23 01:01:38 +00006464 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006465
Steve Naroff8e6aee52009-07-23 01:01:38 +00006466 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006467 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006468 // make sure we check the class hierarchy.
6469 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6470 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6471 E = lhsQID->qual_end(); I != E; ++I) {
6472 // when comparing an id<P> on lhs with a static type on rhs,
6473 // see if static class implements all of id's protocols, directly or
6474 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006475 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006476 return false;
6477 }
6478 }
6479 // If there are no qualifiers and no interface, we have an 'id'.
6480 return true;
6481 }
Mike Stump11289f42009-09-09 15:08:12 +00006482 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006483 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6484 E = lhsQID->qual_end(); I != E; ++I) {
6485 ObjCProtocolDecl *lhsProto = *I;
6486 bool match = false;
6487
6488 // when comparing an id<P> on lhs with a static type on rhs,
6489 // see if static class implements all of id's protocols, directly or
6490 // through its super class and categories.
6491 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6492 E = rhsOPT->qual_end(); J != E; ++J) {
6493 ObjCProtocolDecl *rhsProto = *J;
6494 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6495 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6496 match = true;
6497 break;
6498 }
6499 }
Mike Stump11289f42009-09-09 15:08:12 +00006500 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006501 // make sure we check the class hierarchy.
6502 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6503 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6504 E = lhsQID->qual_end(); I != E; ++I) {
6505 // when comparing an id<P> on lhs with a static type on rhs,
6506 // see if static class implements all of id's protocols, directly or
6507 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006508 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006509 match = true;
6510 break;
6511 }
6512 }
6513 }
6514 if (!match)
6515 return false;
6516 }
Mike Stump11289f42009-09-09 15:08:12 +00006517
Steve Naroff8e6aee52009-07-23 01:01:38 +00006518 return true;
6519 }
Mike Stump11289f42009-09-09 15:08:12 +00006520
Steve Naroff8e6aee52009-07-23 01:01:38 +00006521 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6522 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6523
Mike Stump11289f42009-09-09 15:08:12 +00006524 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006525 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006526 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006527 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6528 E = lhsOPT->qual_end(); I != E; ++I) {
6529 ObjCProtocolDecl *lhsProto = *I;
6530 bool match = false;
6531
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006532 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006533 // see if static class implements all of id's protocols, directly or
6534 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006535 // First, lhs protocols in the qualifier list must be found, direct
6536 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006537 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6538 E = rhsQID->qual_end(); J != E; ++J) {
6539 ObjCProtocolDecl *rhsProto = *J;
6540 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6541 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6542 match = true;
6543 break;
6544 }
6545 }
6546 if (!match)
6547 return false;
6548 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006549
6550 // Static class's protocols, or its super class or category protocols
6551 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6552 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6553 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6554 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6555 // This is rather dubious but matches gcc's behavior. If lhs has
6556 // no type qualifier and its class has no static protocol(s)
6557 // assume that it is mismatch.
6558 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6559 return false;
6560 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6561 LHSInheritedProtocols.begin(),
6562 E = LHSInheritedProtocols.end(); I != E; ++I) {
6563 bool match = false;
6564 ObjCProtocolDecl *lhsProto = (*I);
6565 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6566 E = rhsQID->qual_end(); J != E; ++J) {
6567 ObjCProtocolDecl *rhsProto = *J;
6568 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6569 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6570 match = true;
6571 break;
6572 }
6573 }
6574 if (!match)
6575 return false;
6576 }
6577 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006578 return true;
6579 }
6580 return false;
6581}
6582
Eli Friedman47f77112008-08-22 00:56:42 +00006583/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006584/// compatible for assignment from RHS to LHS. This handles validation of any
6585/// protocol qualifiers on the LHS or RHS.
6586///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006587bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6588 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006589 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6590 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6591
Steve Naroff1329fa02009-07-15 18:40:39 +00006592 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006593 if (LHS->isObjCUnqualifiedIdOrClass() ||
6594 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006595 return true;
6596
John McCall8b07ec22010-05-15 11:32:37 +00006597 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006598 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6599 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006600 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006601
6602 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6603 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6604 QualType(RHSOPT,0));
6605
John McCall8b07ec22010-05-15 11:32:37 +00006606 // If we have 2 user-defined types, fall into that path.
6607 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006608 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006609
Steve Naroff8e6aee52009-07-23 01:01:38 +00006610 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006611}
6612
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006613/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006614/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006615/// arguments in block literals. When passed as arguments, passing 'A*' where
6616/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6617/// not OK. For the return type, the opposite is not OK.
6618bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6619 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006620 const ObjCObjectPointerType *RHSOPT,
6621 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006622 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006623 return true;
6624
6625 if (LHSOPT->isObjCBuiltinType()) {
6626 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6627 }
6628
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006629 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006630 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6631 QualType(RHSOPT,0),
6632 false);
6633
6634 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6635 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6636 if (LHS && RHS) { // We have 2 user-defined types.
6637 if (LHS != RHS) {
6638 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006639 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006640 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006641 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006642 }
6643 else
6644 return true;
6645 }
6646 return false;
6647}
6648
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006649/// getIntersectionOfProtocols - This routine finds the intersection of set
6650/// of protocols inherited from two distinct objective-c pointer objects.
6651/// It is used to build composite qualifier list of the composite type of
6652/// the conditional expression involving two objective-c pointer objects.
6653static
6654void getIntersectionOfProtocols(ASTContext &Context,
6655 const ObjCObjectPointerType *LHSOPT,
6656 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006657 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006658
John McCall8b07ec22010-05-15 11:32:37 +00006659 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6660 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6661 assert(LHS->getInterface() && "LHS must have an interface base");
6662 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006663
6664 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6665 unsigned LHSNumProtocols = LHS->getNumProtocols();
6666 if (LHSNumProtocols > 0)
6667 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6668 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006669 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006670 Context.CollectInheritedProtocols(LHS->getInterface(),
6671 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006672 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6673 LHSInheritedProtocols.end());
6674 }
6675
6676 unsigned RHSNumProtocols = RHS->getNumProtocols();
6677 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006678 ObjCProtocolDecl **RHSProtocols =
6679 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006680 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6681 if (InheritedProtocolSet.count(RHSProtocols[i]))
6682 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006683 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006684 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006685 Context.CollectInheritedProtocols(RHS->getInterface(),
6686 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006687 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6688 RHSInheritedProtocols.begin(),
6689 E = RHSInheritedProtocols.end(); I != E; ++I)
6690 if (InheritedProtocolSet.count((*I)))
6691 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006692 }
6693}
6694
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006695/// areCommonBaseCompatible - Returns common base class of the two classes if
6696/// one found. Note that this is O'2 algorithm. But it will be called as the
6697/// last type comparison in a ?-exp of ObjC pointer types before a
6698/// warning is issued. So, its invokation is extremely rare.
6699QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006700 const ObjCObjectPointerType *Lptr,
6701 const ObjCObjectPointerType *Rptr) {
6702 const ObjCObjectType *LHS = Lptr->getObjectType();
6703 const ObjCObjectType *RHS = Rptr->getObjectType();
6704 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6705 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006706 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006707 return QualType();
6708
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006709 do {
John McCall8b07ec22010-05-15 11:32:37 +00006710 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006711 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006712 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006713 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6714
6715 QualType Result = QualType(LHS, 0);
6716 if (!Protocols.empty())
6717 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6718 Result = getObjCObjectPointerType(Result);
6719 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006720 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006721 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006722
6723 return QualType();
6724}
6725
John McCall8b07ec22010-05-15 11:32:37 +00006726bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6727 const ObjCObjectType *RHS) {
6728 assert(LHS->getInterface() && "LHS is not an interface type");
6729 assert(RHS->getInterface() && "RHS is not an interface type");
6730
Chris Lattner49af6a42008-04-07 06:51:04 +00006731 // Verify that the base decls are compatible: the RHS must be a subclass of
6732 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006733 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006734 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006735
Chris Lattner49af6a42008-04-07 06:51:04 +00006736 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6737 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006738 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006739 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006740
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006741 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6742 // more detailed analysis is required.
6743 if (RHS->getNumProtocols() == 0) {
6744 // OK, if LHS is a superclass of RHS *and*
6745 // this superclass is assignment compatible with LHS.
6746 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006747 bool IsSuperClass =
6748 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6749 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006750 // OK if conversion of LHS to SuperClass results in narrowing of types
6751 // ; i.e., SuperClass may implement at least one of the protocols
6752 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6753 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6754 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006755 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006756 // If super class has no protocols, it is not a match.
6757 if (SuperClassInheritedProtocols.empty())
6758 return false;
6759
6760 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6761 LHSPE = LHS->qual_end();
6762 LHSPI != LHSPE; LHSPI++) {
6763 bool SuperImplementsProtocol = false;
6764 ObjCProtocolDecl *LHSProto = (*LHSPI);
6765
6766 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6767 SuperClassInheritedProtocols.begin(),
6768 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6769 ObjCProtocolDecl *SuperClassProto = (*I);
6770 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6771 SuperImplementsProtocol = true;
6772 break;
6773 }
6774 }
6775 if (!SuperImplementsProtocol)
6776 return false;
6777 }
6778 return true;
6779 }
6780 return false;
6781 }
Mike Stump11289f42009-09-09 15:08:12 +00006782
John McCall8b07ec22010-05-15 11:32:37 +00006783 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6784 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006785 LHSPI != LHSPE; LHSPI++) {
6786 bool RHSImplementsProtocol = false;
6787
6788 // If the RHS doesn't implement the protocol on the left, the types
6789 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006790 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6791 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006792 RHSPI != RHSPE; RHSPI++) {
6793 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006794 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006795 break;
6796 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006797 }
6798 // FIXME: For better diagnostics, consider passing back the protocol name.
6799 if (!RHSImplementsProtocol)
6800 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006801 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006802 // The RHS implements all protocols listed on the LHS.
6803 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006804}
6805
Steve Naroffb7605152009-02-12 17:52:19 +00006806bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6807 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006808 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6809 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006810
Steve Naroff7cae42b2009-07-10 23:34:53 +00006811 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006812 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006813
6814 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6815 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006816}
6817
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006818bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6819 return canAssignObjCInterfaces(
6820 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6821 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6822}
6823
Mike Stump11289f42009-09-09 15:08:12 +00006824/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006825/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006826/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006827/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006828bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6829 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006830 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006831 return hasSameType(LHS, RHS);
6832
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006833 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006834}
6835
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006836bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006837 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006838}
6839
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006840bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6841 return !mergeTypes(LHS, RHS, true).isNull();
6842}
6843
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006844/// mergeTransparentUnionType - if T is a transparent union type and a member
6845/// of T is compatible with SubType, return the merged type, else return
6846/// QualType()
6847QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6848 bool OfBlockPointer,
6849 bool Unqualified) {
6850 if (const RecordType *UT = T->getAsUnionType()) {
6851 RecordDecl *UD = UT->getDecl();
6852 if (UD->hasAttr<TransparentUnionAttr>()) {
6853 for (RecordDecl::field_iterator it = UD->field_begin(),
6854 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006855 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006856 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6857 if (!MT.isNull())
6858 return MT;
6859 }
6860 }
6861 }
6862
6863 return QualType();
6864}
6865
Alp Toker9cacbab2014-01-20 20:26:09 +00006866/// mergeFunctionParameterTypes - merge two types which appear as function
6867/// parameter types
6868QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6869 bool OfBlockPointer,
6870 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006871 // GNU extension: two types are compatible if they appear as a function
6872 // argument, one of the types is a transparent union type and the other
6873 // type is compatible with a union member
6874 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6875 Unqualified);
6876 if (!lmerge.isNull())
6877 return lmerge;
6878
6879 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6880 Unqualified);
6881 if (!rmerge.isNull())
6882 return rmerge;
6883
6884 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6885}
6886
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006887QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006888 bool OfBlockPointer,
6889 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006890 const FunctionType *lbase = lhs->getAs<FunctionType>();
6891 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006892 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6893 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006894 bool allLTypes = true;
6895 bool allRTypes = true;
6896
6897 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006898 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006899 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006900 QualType RHS = rbase->getReturnType();
6901 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006902 bool UnqualifiedResult = Unqualified;
6903 if (!UnqualifiedResult)
6904 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006905 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006906 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006907 else
Alp Toker314cc812014-01-25 16:55:45 +00006908 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006909 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006910 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006911
6912 if (Unqualified)
6913 retType = retType.getUnqualifiedType();
6914
Alp Toker314cc812014-01-25 16:55:45 +00006915 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6916 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006917 if (Unqualified) {
6918 LRetType = LRetType.getUnqualifiedType();
6919 RRetType = RRetType.getUnqualifiedType();
6920 }
6921
6922 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006923 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006924 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006925 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006926
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006927 // FIXME: double check this
6928 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6929 // rbase->getRegParmAttr() != 0 &&
6930 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006931 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6932 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006933
Douglas Gregor8c940862010-01-18 17:14:39 +00006934 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006935 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006936 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006937
John McCall8c6b56f2010-12-15 01:06:38 +00006938 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006939 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6940 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006941 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6942 return QualType();
6943
John McCall31168b02011-06-15 23:02:42 +00006944 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6945 return QualType();
6946
John McCall8c6b56f2010-12-15 01:06:38 +00006947 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6948 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006949
Rafael Espindola8778c282012-11-29 16:09:03 +00006950 if (lbaseInfo.getNoReturn() != NoReturn)
6951 allLTypes = false;
6952 if (rbaseInfo.getNoReturn() != NoReturn)
6953 allRTypes = false;
6954
John McCall31168b02011-06-15 23:02:42 +00006955 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006956
Eli Friedman47f77112008-08-22 00:56:42 +00006957 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006958 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6959 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006960 // Compatible functions must have the same number of parameters
6961 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006962 return QualType();
6963
6964 // Variadic and non-variadic functions aren't compatible
6965 if (lproto->isVariadic() != rproto->isVariadic())
6966 return QualType();
6967
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006968 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6969 return QualType();
6970
Fariborz Jahanian97676972011-09-28 21:52:05 +00006971 if (LangOpts.ObjCAutoRefCount &&
6972 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6973 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006974
6975 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006976 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006977 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6978 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6979 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6980 QualType paramType = mergeFunctionParameterTypes(
6981 lParamType, rParamType, OfBlockPointer, Unqualified);
6982 if (paramType.isNull())
6983 return QualType();
6984
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006985 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006986 paramType = paramType.getUnqualifiedType();
6987
6988 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006989 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006990 lParamType = lParamType.getUnqualifiedType();
6991 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006992 }
Alp Toker601b22c2014-01-21 23:35:24 +00006993
6994 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006995 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006996 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006997 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006998 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006999
Eli Friedman47f77112008-08-22 00:56:42 +00007000 if (allLTypes) return lhs;
7001 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007002
7003 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7004 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007005 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007006 }
7007
7008 if (lproto) allRTypes = false;
7009 if (rproto) allLTypes = false;
7010
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007011 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007012 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007013 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007014 if (proto->isVariadic()) return QualType();
7015 // Check that the types are compatible with the types that
7016 // would result from default argument promotions (C99 6.7.5.3p15).
7017 // The only types actually affected are promotable integer
7018 // types and floats, which would be passed as a different
7019 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007020 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7021 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007022
Eli Friedman448ce402012-08-30 00:44:15 +00007023 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007024 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007025 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7026 paramTy = Enum->getDecl()->getIntegerType();
7027 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007028 return QualType();
7029 }
Alp Toker601b22c2014-01-21 23:35:24 +00007030
7031 if (paramTy->isPromotableIntegerType() ||
7032 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007033 return QualType();
7034 }
7035
7036 if (allLTypes) return lhs;
7037 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007038
7039 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7040 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007041 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007042 }
7043
7044 if (allLTypes) return lhs;
7045 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007046 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007047}
7048
John McCall433c2e62013-03-21 00:10:07 +00007049/// Given that we have an enum type and a non-enum type, try to merge them.
7050static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7051 QualType other, bool isBlockReturnType) {
7052 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7053 // a signed integer type, or an unsigned integer type.
7054 // Compatibility is based on the underlying type, not the promotion
7055 // type.
7056 QualType underlyingType = ET->getDecl()->getIntegerType();
7057 if (underlyingType.isNull()) return QualType();
7058 if (Context.hasSameType(underlyingType, other))
7059 return other;
7060
7061 // In block return types, we're more permissive and accept any
7062 // integral type of the same size.
7063 if (isBlockReturnType && other->isIntegerType() &&
7064 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7065 return other;
7066
7067 return QualType();
7068}
7069
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007070QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007071 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007072 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007073 // C++ [expr]: If an expression initially has the type "reference to T", the
7074 // type is adjusted to "T" prior to any further analysis, the expression
7075 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007076 // expression is an lvalue unless the reference is an rvalue reference and
7077 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007078 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7079 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007080
7081 if (Unqualified) {
7082 LHS = LHS.getUnqualifiedType();
7083 RHS = RHS.getUnqualifiedType();
7084 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007085
Eli Friedman47f77112008-08-22 00:56:42 +00007086 QualType LHSCan = getCanonicalType(LHS),
7087 RHSCan = getCanonicalType(RHS);
7088
7089 // If two types are identical, they are compatible.
7090 if (LHSCan == RHSCan)
7091 return LHS;
7092
John McCall8ccfcb52009-09-24 19:53:00 +00007093 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007094 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7095 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007096 if (LQuals != RQuals) {
7097 // If any of these qualifiers are different, we have a type
7098 // mismatch.
7099 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007100 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7101 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007102 return QualType();
7103
7104 // Exactly one GC qualifier difference is allowed: __strong is
7105 // okay if the other type has no GC qualifier but is an Objective
7106 // C object pointer (i.e. implicitly strong by default). We fix
7107 // this by pretending that the unqualified type was actually
7108 // qualified __strong.
7109 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7110 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7111 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7112
7113 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7114 return QualType();
7115
7116 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7117 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7118 }
7119 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7120 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7121 }
Eli Friedman47f77112008-08-22 00:56:42 +00007122 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007123 }
7124
7125 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007126
Eli Friedmandcca6332009-06-01 01:22:52 +00007127 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7128 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007129
Chris Lattnerfd652912008-01-14 05:45:46 +00007130 // We want to consider the two function types to be the same for these
7131 // comparisons, just force one to the other.
7132 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7133 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007134
7135 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007136 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7137 LHSClass = Type::ConstantArray;
7138 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7139 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007140
John McCall8b07ec22010-05-15 11:32:37 +00007141 // ObjCInterfaces are just specialized ObjCObjects.
7142 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7143 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7144
Nate Begemance4d7fc2008-04-18 23:10:10 +00007145 // Canonicalize ExtVector -> Vector.
7146 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7147 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007148
Chris Lattner95554662008-04-07 05:43:21 +00007149 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007150 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007151 // Note that we only have special rules for turning block enum
7152 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007153 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007154 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007155 }
John McCall9dd450b2009-09-21 23:43:11 +00007156 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007157 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007158 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007159 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007160 if (OfBlockPointer && !BlockReturnType) {
7161 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7162 return LHS;
7163 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7164 return RHS;
7165 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007166
Eli Friedman47f77112008-08-22 00:56:42 +00007167 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007168 }
Eli Friedman47f77112008-08-22 00:56:42 +00007169
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007170 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007171 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007172#define TYPE(Class, Base)
7173#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007174#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007175#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7176#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7177#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007178 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007179
Richard Smith27d807c2013-04-30 13:56:41 +00007180 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007181 case Type::LValueReference:
7182 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007183 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007184 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007185
John McCall8b07ec22010-05-15 11:32:37 +00007186 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007187 case Type::IncompleteArray:
7188 case Type::VariableArray:
7189 case Type::FunctionProto:
7190 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007191 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007192
Chris Lattnerfd652912008-01-14 05:45:46 +00007193 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007194 {
7195 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007196 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7197 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007198 if (Unqualified) {
7199 LHSPointee = LHSPointee.getUnqualifiedType();
7200 RHSPointee = RHSPointee.getUnqualifiedType();
7201 }
7202 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7203 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007204 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007205 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007206 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007207 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007208 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007209 return getPointerType(ResultType);
7210 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007211 case Type::BlockPointer:
7212 {
7213 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007214 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7215 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007216 if (Unqualified) {
7217 LHSPointee = LHSPointee.getUnqualifiedType();
7218 RHSPointee = RHSPointee.getUnqualifiedType();
7219 }
7220 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7221 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007222 if (ResultType.isNull()) return QualType();
7223 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7224 return LHS;
7225 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7226 return RHS;
7227 return getBlockPointerType(ResultType);
7228 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007229 case Type::Atomic:
7230 {
7231 // Merge two pointer types, while trying to preserve typedef info
7232 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7233 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7234 if (Unqualified) {
7235 LHSValue = LHSValue.getUnqualifiedType();
7236 RHSValue = RHSValue.getUnqualifiedType();
7237 }
7238 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7239 Unqualified);
7240 if (ResultType.isNull()) return QualType();
7241 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7242 return LHS;
7243 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7244 return RHS;
7245 return getAtomicType(ResultType);
7246 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007247 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007248 {
7249 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7250 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7251 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7252 return QualType();
7253
7254 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7255 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007256 if (Unqualified) {
7257 LHSElem = LHSElem.getUnqualifiedType();
7258 RHSElem = RHSElem.getUnqualifiedType();
7259 }
7260
7261 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007262 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007263 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7264 return LHS;
7265 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7266 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007267 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7268 ArrayType::ArraySizeModifier(), 0);
7269 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7270 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007271 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7272 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007273 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7274 return LHS;
7275 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7276 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007277 if (LVAT) {
7278 // FIXME: This isn't correct! But tricky to implement because
7279 // the array's size has to be the size of LHS, but the type
7280 // has to be different.
7281 return LHS;
7282 }
7283 if (RVAT) {
7284 // FIXME: This isn't correct! But tricky to implement because
7285 // the array's size has to be the size of RHS, but the type
7286 // has to be different.
7287 return RHS;
7288 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007289 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7290 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007291 return getIncompleteArrayType(ResultType,
7292 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007293 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007294 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007295 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007296 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007297 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007298 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007299 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007300 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007301 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007302 case Type::Complex:
7303 // Distinct complex types are incompatible.
7304 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007305 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007306 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007307 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7308 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007309 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007310 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007311 case Type::ObjCObject: {
7312 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007313 // FIXME: This should be type compatibility, e.g. whether
7314 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007315 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7316 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7317 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007318 return LHS;
7319
Eli Friedman47f77112008-08-22 00:56:42 +00007320 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007321 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007322 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007323 if (OfBlockPointer) {
7324 if (canAssignObjCInterfacesInBlockPointer(
7325 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007326 RHS->getAs<ObjCObjectPointerType>(),
7327 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007328 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007329 return QualType();
7330 }
John McCall9dd450b2009-09-21 23:43:11 +00007331 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7332 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007333 return LHS;
7334
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007335 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007336 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007337 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007338
David Blaikie8a40f702012-01-17 06:56:22 +00007339 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007340}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007341
Fariborz Jahanian97676972011-09-28 21:52:05 +00007342bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7343 const FunctionProtoType *FromFunctionType,
7344 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007345 if (FromFunctionType->hasAnyConsumedParams() !=
7346 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007347 return false;
7348 FunctionProtoType::ExtProtoInfo FromEPI =
7349 FromFunctionType->getExtProtoInfo();
7350 FunctionProtoType::ExtProtoInfo ToEPI =
7351 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007352 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007353 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7354 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007355 return false;
7356 }
7357 return true;
7358}
7359
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007360/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7361/// 'RHS' attributes and returns the merged version; including for function
7362/// return types.
7363QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7364 QualType LHSCan = getCanonicalType(LHS),
7365 RHSCan = getCanonicalType(RHS);
7366 // If two types are identical, they are compatible.
7367 if (LHSCan == RHSCan)
7368 return LHS;
7369 if (RHSCan->isFunctionType()) {
7370 if (!LHSCan->isFunctionType())
7371 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007372 QualType OldReturnType =
7373 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007374 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007375 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007376 QualType ResReturnType =
7377 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7378 if (ResReturnType.isNull())
7379 return QualType();
7380 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7381 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7382 // In either case, use OldReturnType to build the new function type.
7383 const FunctionType *F = LHS->getAs<FunctionType>();
7384 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007385 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7386 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007387 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007388 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007389 return ResultType;
7390 }
7391 }
7392 return QualType();
7393 }
7394
7395 // If the qualifiers are different, the types can still be merged.
7396 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7397 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7398 if (LQuals != RQuals) {
7399 // If any of these qualifiers are different, we have a type mismatch.
7400 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7401 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7402 return QualType();
7403
7404 // Exactly one GC qualifier difference is allowed: __strong is
7405 // okay if the other type has no GC qualifier but is an Objective
7406 // C object pointer (i.e. implicitly strong by default). We fix
7407 // this by pretending that the unqualified type was actually
7408 // qualified __strong.
7409 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7410 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7411 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7412
7413 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7414 return QualType();
7415
7416 if (GC_L == Qualifiers::Strong)
7417 return LHS;
7418 if (GC_R == Qualifiers::Strong)
7419 return RHS;
7420 return QualType();
7421 }
7422
7423 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7424 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7425 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7426 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7427 if (ResQT == LHSBaseQT)
7428 return LHS;
7429 if (ResQT == RHSBaseQT)
7430 return RHS;
7431 }
7432 return QualType();
7433}
7434
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007435//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007436// Integer Predicates
7437//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007438
Jay Foad39c79802011-01-12 09:06:06 +00007439unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007440 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007441 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007442 if (T->isBooleanType())
7443 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007444 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007445 return (unsigned)getTypeSize(T);
7446}
7447
Abramo Bagnara13640492012-09-09 10:21:24 +00007448QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007449 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007450
7451 // Turn <4 x signed int> -> <4 x unsigned int>
7452 if (const VectorType *VTy = T->getAs<VectorType>())
7453 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007454 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007455
7456 // For enums, we return the unsigned version of the base type.
7457 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007458 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007459
7460 const BuiltinType *BTy = T->getAs<BuiltinType>();
7461 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007462 switch (BTy->getKind()) {
7463 case BuiltinType::Char_S:
7464 case BuiltinType::SChar:
7465 return UnsignedCharTy;
7466 case BuiltinType::Short:
7467 return UnsignedShortTy;
7468 case BuiltinType::Int:
7469 return UnsignedIntTy;
7470 case BuiltinType::Long:
7471 return UnsignedLongTy;
7472 case BuiltinType::LongLong:
7473 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007474 case BuiltinType::Int128:
7475 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007476 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007477 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007478 }
7479}
7480
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007481ASTMutationListener::~ASTMutationListener() { }
7482
Richard Smith1fa5d642013-05-11 05:45:24 +00007483void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7484 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007485
7486//===----------------------------------------------------------------------===//
7487// Builtin Type Computation
7488//===----------------------------------------------------------------------===//
7489
7490/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007491/// pointer over the consumed characters. This returns the resultant type. If
7492/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7493/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7494/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007495///
7496/// RequiresICE is filled in on return to indicate whether the value is required
7497/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007498static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007499 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007500 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007501 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007502 // Modifiers.
7503 int HowLong = 0;
7504 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007505 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007506
Chris Lattnerdc226c22010-10-01 22:42:38 +00007507 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007508 bool Done = false;
7509 while (!Done) {
7510 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007511 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007512 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007513 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007514 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007515 case 'S':
7516 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7517 assert(!Signed && "Can't use 'S' modifier multiple times!");
7518 Signed = true;
7519 break;
7520 case 'U':
7521 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7522 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7523 Unsigned = true;
7524 break;
7525 case 'L':
7526 assert(HowLong <= 2 && "Can't have LLLL modifier");
7527 ++HowLong;
7528 break;
7529 }
7530 }
7531
7532 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007533
Chris Lattnerecd79c62009-06-14 00:45:47 +00007534 // Read the base type.
7535 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007536 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007537 case 'v':
7538 assert(HowLong == 0 && !Signed && !Unsigned &&
7539 "Bad modifiers used with 'v'!");
7540 Type = Context.VoidTy;
7541 break;
Jack Carter24bef982013-08-15 15:16:57 +00007542 case 'h':
7543 assert(HowLong == 0 && !Signed && !Unsigned &&
7544 "Bad modifiers used with 'f'!");
7545 Type = Context.HalfTy;
7546 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007547 case 'f':
7548 assert(HowLong == 0 && !Signed && !Unsigned &&
7549 "Bad modifiers used with 'f'!");
7550 Type = Context.FloatTy;
7551 break;
7552 case 'd':
7553 assert(HowLong < 2 && !Signed && !Unsigned &&
7554 "Bad modifiers used with 'd'!");
7555 if (HowLong)
7556 Type = Context.LongDoubleTy;
7557 else
7558 Type = Context.DoubleTy;
7559 break;
7560 case 's':
7561 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7562 if (Unsigned)
7563 Type = Context.UnsignedShortTy;
7564 else
7565 Type = Context.ShortTy;
7566 break;
7567 case 'i':
7568 if (HowLong == 3)
7569 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7570 else if (HowLong == 2)
7571 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7572 else if (HowLong == 1)
7573 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7574 else
7575 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7576 break;
7577 case 'c':
7578 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7579 if (Signed)
7580 Type = Context.SignedCharTy;
7581 else if (Unsigned)
7582 Type = Context.UnsignedCharTy;
7583 else
7584 Type = Context.CharTy;
7585 break;
7586 case 'b': // boolean
7587 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7588 Type = Context.BoolTy;
7589 break;
7590 case 'z': // size_t.
7591 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7592 Type = Context.getSizeType();
7593 break;
7594 case 'F':
7595 Type = Context.getCFConstantStringType();
7596 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007597 case 'G':
7598 Type = Context.getObjCIdType();
7599 break;
7600 case 'H':
7601 Type = Context.getObjCSelType();
7602 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007603 case 'M':
7604 Type = Context.getObjCSuperType();
7605 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007606 case 'a':
7607 Type = Context.getBuiltinVaListType();
7608 assert(!Type.isNull() && "builtin va list type not initialized!");
7609 break;
7610 case 'A':
7611 // This is a "reference" to a va_list; however, what exactly
7612 // this means depends on how va_list is defined. There are two
7613 // different kinds of va_list: ones passed by value, and ones
7614 // passed by reference. An example of a by-value va_list is
7615 // x86, where va_list is a char*. An example of by-ref va_list
7616 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7617 // we want this argument to be a char*&; for x86-64, we want
7618 // it to be a __va_list_tag*.
7619 Type = Context.getBuiltinVaListType();
7620 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007621 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007622 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007623 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007624 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007625 break;
7626 case 'V': {
7627 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007628 unsigned NumElements = strtoul(Str, &End, 10);
7629 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007630 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007631
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007632 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7633 RequiresICE, false);
7634 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007635
7636 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007637 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007638 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007639 break;
7640 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007641 case 'E': {
7642 char *End;
7643
7644 unsigned NumElements = strtoul(Str, &End, 10);
7645 assert(End != Str && "Missing vector size");
7646
7647 Str = End;
7648
7649 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7650 false);
7651 Type = Context.getExtVectorType(ElementType, NumElements);
7652 break;
7653 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007654 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007655 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7656 false);
7657 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007658 Type = Context.getComplexType(ElementType);
7659 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007660 }
7661 case 'Y' : {
7662 Type = Context.getPointerDiffType();
7663 break;
7664 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007665 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007666 Type = Context.getFILEType();
7667 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007668 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007669 return QualType();
7670 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007671 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007672 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007673 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007674 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007675 else
7676 Type = Context.getjmp_bufType();
7677
Mike Stump2adb4da2009-07-28 23:47:15 +00007678 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007679 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007680 return QualType();
7681 }
7682 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007683 case 'K':
7684 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7685 Type = Context.getucontext_tType();
7686
7687 if (Type.isNull()) {
7688 Error = ASTContext::GE_Missing_ucontext;
7689 return QualType();
7690 }
7691 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007692 case 'p':
7693 Type = Context.getProcessIDType();
7694 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007695 }
Mike Stump11289f42009-09-09 15:08:12 +00007696
Chris Lattnerdc226c22010-10-01 22:42:38 +00007697 // If there are modifiers and if we're allowed to parse them, go for it.
7698 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007699 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007700 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007701 default: Done = true; --Str; break;
7702 case '*':
7703 case '&': {
7704 // Both pointers and references can have their pointee types
7705 // qualified with an address space.
7706 char *End;
7707 unsigned AddrSpace = strtoul(Str, &End, 10);
7708 if (End != Str && AddrSpace != 0) {
7709 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7710 Str = End;
7711 }
7712 if (c == '*')
7713 Type = Context.getPointerType(Type);
7714 else
7715 Type = Context.getLValueReferenceType(Type);
7716 break;
7717 }
7718 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7719 case 'C':
7720 Type = Type.withConst();
7721 break;
7722 case 'D':
7723 Type = Context.getVolatileType(Type);
7724 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007725 case 'R':
7726 Type = Type.withRestrict();
7727 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007728 }
7729 }
Chris Lattner84733392010-10-01 07:13:18 +00007730
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007731 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007732 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007733
Chris Lattnerecd79c62009-06-14 00:45:47 +00007734 return Type;
7735}
7736
7737/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007738QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007739 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007740 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007741 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007742
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007743 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007744
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007745 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007746 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007747 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7748 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007749 if (Error != GE_None)
7750 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007751
7752 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7753
Chris Lattnerecd79c62009-06-14 00:45:47 +00007754 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007755 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007756 if (Error != GE_None)
7757 return QualType();
7758
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007759 // If this argument is required to be an IntegerConstantExpression and the
7760 // caller cares, fill in the bitmask we return.
7761 if (RequiresICE && IntegerConstantArgs)
7762 *IntegerConstantArgs |= 1 << ArgTypes.size();
7763
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764 // Do array -> pointer decay. The builtin should use the decayed type.
7765 if (Ty->isArrayType())
7766 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007767
Chris Lattnerecd79c62009-06-14 00:45:47 +00007768 ArgTypes.push_back(Ty);
7769 }
7770
7771 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7772 "'.' should only occur at end of builtin type list!");
7773
Reid Kleckner78af0702013-08-27 23:08:25 +00007774 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007775 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7776
7777 bool Variadic = (TypeStr[0] == '.');
7778
7779 // We really shouldn't be making a no-proto type here, especially in C++.
7780 if (ArgTypes.empty() && Variadic)
7781 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007782
John McCalldb40c7f2010-12-14 08:05:40 +00007783 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007784 EPI.ExtInfo = EI;
7785 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007786
Jordan Rose5c382722013-03-08 21:51:21 +00007787 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007788}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007789
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007790GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007791 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007792 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007793
Rafael Espindola3ae00052013-05-13 00:12:11 +00007794 GVALinkage External = GVA_StrongExternal;
7795 switch (FD->getTemplateSpecializationKind()) {
7796 case TSK_Undeclared:
7797 case TSK_ExplicitSpecialization:
7798 External = GVA_StrongExternal;
7799 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007800
Rafael Espindola3ae00052013-05-13 00:12:11 +00007801 case TSK_ExplicitInstantiationDefinition:
7802 return GVA_ExplicitTemplateInstantiation;
7803
7804 case TSK_ExplicitInstantiationDeclaration:
7805 case TSK_ImplicitInstantiation:
7806 External = GVA_TemplateInstantiation;
7807 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007808 }
7809
7810 if (!FD->isInlined())
7811 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007812
Alp Tokerbfa39342014-01-14 12:51:41 +00007813 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007814 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007815 // GNU or C99 inline semantics. Determine whether this symbol should be
7816 // externally visible.
7817 if (FD->isInlineDefinitionExternallyVisible())
7818 return External;
7819
7820 // C99 inline semantics, where the symbol is not externally visible.
7821 return GVA_C99Inline;
7822 }
7823
7824 // C++0x [temp.explicit]p9:
7825 // [ Note: The intent is that an inline function that is the subject of
7826 // an explicit instantiation declaration will still be implicitly
7827 // instantiated when used so that the body can be considered for
7828 // inlining, but that no out-of-line copy of the inline function would be
7829 // generated in the translation unit. -- end note ]
7830 if (FD->getTemplateSpecializationKind()
7831 == TSK_ExplicitInstantiationDeclaration)
7832 return GVA_C99Inline;
7833
7834 return GVA_CXXInline;
7835}
7836
7837GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007838 if (!VD->isExternallyVisible())
7839 return GVA_Internal;
7840
Richard Smith8809a0c2013-09-27 20:14:12 +00007841 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007842 case TSK_Undeclared:
7843 case TSK_ExplicitSpecialization:
7844 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007845
Rafael Espindola3ae00052013-05-13 00:12:11 +00007846 case TSK_ExplicitInstantiationDeclaration:
7847 llvm_unreachable("Variable should not be instantiated");
7848 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007849
Rafael Espindola3ae00052013-05-13 00:12:11 +00007850 case TSK_ExplicitInstantiationDefinition:
7851 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007852
Rafael Espindola3ae00052013-05-13 00:12:11 +00007853 case TSK_ImplicitInstantiation:
7854 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007855 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007856
7857 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007858}
7859
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007860bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007861 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7862 if (!VD->isFileVarDecl())
7863 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007864 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7865 // We never need to emit an uninstantiated function template.
7866 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7867 return false;
7868 } else
7869 return false;
7870
7871 // If this is a member of a class template, we do not need to emit it.
7872 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007873 return false;
7874
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007875 // Weak references don't produce any output by themselves.
7876 if (D->hasAttr<WeakRefAttr>())
7877 return false;
7878
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007879 // Aliases and used decls are required.
7880 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7881 return true;
7882
7883 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7884 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007885 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007886 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007887
7888 // Constructors and destructors are required.
7889 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7890 return true;
7891
John McCall6bd2a892013-01-25 22:31:03 +00007892 // The key function for a class is required. This rule only comes
7893 // into play when inline functions can be key functions, though.
7894 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7895 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7896 const CXXRecordDecl *RD = MD->getParent();
7897 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7898 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7899 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7900 return true;
7901 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007902 }
7903 }
7904
7905 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7906
7907 // static, static inline, always_inline, and extern inline functions can
7908 // always be deferred. Normal inline functions can be deferred in C99/C++.
7909 // Implicit template instantiations can also be deferred in C++.
7910 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007911 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007912 return false;
7913 return true;
7914 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007915
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007916 const VarDecl *VD = cast<VarDecl>(D);
7917 assert(VD->isFileVarDecl() && "Expected file scoped var");
7918
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007919 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7920 return false;
7921
Richard Smitha0e5e542012-11-12 21:38:00 +00007922 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007923 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007924 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7925 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007926
Richard Smitha0e5e542012-11-12 21:38:00 +00007927 // Variables that have destruction with side-effects are required.
7928 if (VD->getType().isDestructedType())
7929 return true;
7930
7931 // Variables that have initialization with side-effects are required.
7932 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7933 return true;
7934
7935 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007936}
Charles Davis53c59df2010-08-16 03:33:14 +00007937
Reid Kleckner78af0702013-08-27 23:08:25 +00007938CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7939 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007940 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007941 if (IsCXXMethod)
7942 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007943
Reid Kleckner78af0702013-08-27 23:08:25 +00007944 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007945}
7946
Jay Foad39c79802011-01-12 09:06:06 +00007947bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007948 // Pass through to the C++ ABI object
7949 return ABI->isNearlyEmpty(RD);
7950}
7951
Reid Kleckner96f8f932014-02-05 17:27:08 +00007952VTableContextBase *ASTContext::getVTableContext() {
7953 if (!VTContext.get()) {
7954 if (Target->getCXXABI().isMicrosoft())
7955 VTContext.reset(new MicrosoftVTableContext(*this));
7956 else
7957 VTContext.reset(new ItaniumVTableContext(*this));
7958 }
7959 return VTContext.get();
7960}
7961
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007962MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007963 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007964 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007965 case TargetCXXABI::GenericItanium:
7966 case TargetCXXABI::GenericARM:
7967 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007968 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007969 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007970 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007971 }
David Blaikie83d382b2011-09-23 05:06:16 +00007972 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007973}
7974
Charles Davis53c59df2010-08-16 03:33:14 +00007975CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007976
7977size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007978 return ASTRecordLayouts.getMemorySize() +
7979 llvm::capacity_in_bytes(ObjCLayouts) +
7980 llvm::capacity_in_bytes(KeyFunctions) +
7981 llvm::capacity_in_bytes(ObjCImpls) +
7982 llvm::capacity_in_bytes(BlockVarCopyInits) +
7983 llvm::capacity_in_bytes(DeclAttrs) +
7984 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7985 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7986 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7987 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7988 llvm::capacity_in_bytes(OverriddenMethods) +
7989 llvm::capacity_in_bytes(Types) +
7990 llvm::capacity_in_bytes(VariableArrayTypes) +
7991 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007992}
Ted Kremenek540017e2011-10-06 05:00:56 +00007993
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007994/// getIntTypeForBitwidth -
7995/// sets integer QualTy according to specified details:
7996/// bitwidth, signed/unsigned.
7997/// Returns empty type if there is no appropriate target types.
7998QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7999 unsigned Signed) const {
8000 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8001 CanQualType QualTy = getFromTargetType(Ty);
8002 if (!QualTy && DestWidth == 128)
8003 return Signed ? Int128Ty : UnsignedInt128Ty;
8004 return QualTy;
8005}
8006
8007/// getRealTypeForBitwidth -
8008/// sets floating point QualTy according to specified bitwidth.
8009/// Returns empty type if there is no appropriate target types.
8010QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8011 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8012 switch (Ty) {
8013 case TargetInfo::Float:
8014 return FloatTy;
8015 case TargetInfo::Double:
8016 return DoubleTy;
8017 case TargetInfo::LongDouble:
8018 return LongDoubleTy;
8019 case TargetInfo::NoFloat:
8020 return QualType();
8021 }
8022
8023 llvm_unreachable("Unhandled TargetInfo::RealType value");
8024}
8025
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008026void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8027 if (Number > 1)
8028 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008029}
8030
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008031unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8032 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8033 MangleNumbers.find(ND);
8034 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008035}
8036
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008037MangleNumberingContext &
8038ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008039 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8040 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8041 if (!MCtx)
8042 MCtx = createMangleNumberingContext();
8043 return *MCtx;
8044}
8045
8046MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8047 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008048}
8049
Ted Kremenek540017e2011-10-06 05:00:56 +00008050void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8051 ParamIndices[D] = index;
8052}
8053
8054unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8055 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8056 assert(I != ParamIndices.end() &&
8057 "ParmIndices lacks entry set by ParmVarDecl");
8058 return I->second;
8059}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008060
Richard Smithe6c01442013-06-05 00:46:14 +00008061APValue *
8062ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8063 bool MayCreate) {
8064 assert(E && E->getStorageDuration() == SD_Static &&
8065 "don't need to cache the computed value for this temporary");
8066 if (MayCreate)
8067 return &MaterializedTemporaryValues[E];
8068
8069 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8070 MaterializedTemporaryValues.find(E);
8071 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8072}
8073
Fariborz Jahanian615de762013-05-28 17:37:39 +00008074bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8075 const llvm::Triple &T = getTargetInfo().getTriple();
8076 if (!T.isOSDarwin())
8077 return false;
8078
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008079 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8080 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8081 return false;
8082
Fariborz Jahanian615de762013-05-28 17:37:39 +00008083 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8084 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8085 uint64_t Size = sizeChars.getQuantity();
8086 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8087 unsigned Align = alignChars.getQuantity();
8088 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8089 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8090}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008091
8092namespace {
8093
8094 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8095 /// parents as defined by the \c RecursiveASTVisitor.
8096 ///
8097 /// Note that the relationship described here is purely in terms of AST
8098 /// traversal - there are other relationships (for example declaration context)
8099 /// in the AST that are better modeled by special matchers.
8100 ///
8101 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8102 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8103
8104 public:
8105 /// \brief Builds and returns the translation unit's parent map.
8106 ///
8107 /// The caller takes ownership of the returned \c ParentMap.
8108 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8109 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8110 Visitor.TraverseDecl(&TU);
8111 return Visitor.Parents;
8112 }
8113
8114 private:
8115 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8116
8117 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8118 }
8119
8120 bool shouldVisitTemplateInstantiations() const {
8121 return true;
8122 }
8123 bool shouldVisitImplicitCode() const {
8124 return true;
8125 }
8126 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8127 // are not triggered during data recursion.
8128 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8129 return false;
8130 }
8131
8132 template <typename T>
8133 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8134 if (Node == NULL)
8135 return true;
8136 if (ParentStack.size() > 0)
8137 // FIXME: Currently we add the same parent multiple times, for example
8138 // when we visit all subexpressions of template instantiations; this is
8139 // suboptimal, bug benign: the only way to visit those is with
8140 // hasAncestor / hasParent, and those do not create new matches.
8141 // The plan is to enable DynTypedNode to be storable in a map or hash
8142 // map. The main problem there is to implement hash functions /
8143 // comparison operators for all types that DynTypedNode supports that
8144 // do not have pointer identity.
8145 (*Parents)[Node].push_back(ParentStack.back());
8146 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8147 bool Result = (this ->* traverse) (Node);
8148 ParentStack.pop_back();
8149 return Result;
8150 }
8151
8152 bool TraverseDecl(Decl *DeclNode) {
8153 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8154 }
8155
8156 bool TraverseStmt(Stmt *StmtNode) {
8157 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8158 }
8159
8160 ASTContext::ParentMap *Parents;
8161 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8162
8163 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8164 };
8165
8166} // end namespace
8167
8168ASTContext::ParentVector
8169ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8170 assert(Node.getMemoizationData() &&
8171 "Invariant broken: only nodes that support memoization may be "
8172 "used in the parent map.");
8173 if (!AllParents) {
8174 // We always need to run over the whole translation unit, as
8175 // hasAncestor can escape any subtree.
8176 AllParents.reset(
8177 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8178 }
8179 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8180 if (I == AllParents->end()) {
8181 return ParentVector();
8182 }
8183 return I->second;
8184}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008185
8186bool
8187ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8188 const ObjCMethodDecl *MethodImpl) {
8189 // No point trying to match an unavailable/deprecated mothod.
8190 if (MethodDecl->hasAttr<UnavailableAttr>()
8191 || MethodDecl->hasAttr<DeprecatedAttr>())
8192 return false;
8193 if (MethodDecl->getObjCDeclQualifier() !=
8194 MethodImpl->getObjCDeclQualifier())
8195 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008196 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008197 return false;
8198
8199 if (MethodDecl->param_size() != MethodImpl->param_size())
8200 return false;
8201
8202 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8203 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8204 EF = MethodDecl->param_end();
8205 IM != EM && IF != EF; ++IM, ++IF) {
8206 const ParmVarDecl *DeclVar = (*IF);
8207 const ParmVarDecl *ImplVar = (*IM);
8208 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8209 return false;
8210 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8211 return false;
8212 }
8213 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8214
8215}