blob: d94fa4ba36fe18e190a59ee356889d0c55aaf0d4 [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;
Aaron Ballman86c93902014-03-06 23:45:36 +0000335 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000336 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000337 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000338 if (Pos != RedeclComments.end()) {
339 const RawCommentAndCacheFlags &Raw = Pos->second;
340 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
341 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000342 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 break;
344 }
345 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000346 RC = getRawCommentForDeclNoCache(I);
347 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 RawCommentAndCacheFlags Raw;
349 if (RC) {
350 Raw.setRaw(RC);
351 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
352 } else
353 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 Raw.setOriginalDecl(I);
355 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 if (RC)
357 break;
358 }
359 }
360
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000361 // If we found a comment, it should be a documentation comment.
362 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000364 if (OriginalDecl)
365 *OriginalDecl = OriginalDeclForRC;
366
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 // Update cache for every declaration in the redeclaration chain.
368 RawCommentAndCacheFlags Raw;
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000371 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000372
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 for (auto I : D->redecls()) {
374 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
376 R = Raw;
377 }
378
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000379 return RC;
380}
381
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000382static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
383 SmallVectorImpl<const NamedDecl *> &Redeclared) {
384 const DeclContext *DC = ObjCMethod->getDeclContext();
385 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
386 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
387 if (!ID)
388 return;
389 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000390 for (ObjCInterfaceDecl::known_extensions_iterator
391 Ext = ID->known_extensions_begin(),
392 ExtEnd = ID->known_extensions_end();
393 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000394 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000395 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000396 ObjCMethod->isInstanceMethod()))
397 Redeclared.push_back(RedeclaredMethod);
398 }
399 }
400}
401
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000402comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
403 const Decl *D) const {
404 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
405 ThisDeclInfo->CommentDecl = D;
406 ThisDeclInfo->IsFilled = false;
407 ThisDeclInfo->fill();
408 ThisDeclInfo->CommentDecl = FC->getDecl();
409 comments::FullComment *CFC =
410 new (*this) comments::FullComment(FC->getBlocks(),
411 ThisDeclInfo);
412 return CFC;
413
414}
415
Richard Smithb39b9d52013-05-21 05:24:00 +0000416comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
417 const RawComment *RC = getRawCommentForDeclNoCache(D);
418 return RC ? RC->parse(*this, 0, D) : 0;
419}
420
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000421comments::FullComment *ASTContext::getCommentForDecl(
422 const Decl *D,
423 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000424 if (D->isInvalidDecl())
425 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000426 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000427
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000428 const Decl *Canonical = D->getCanonicalDecl();
429 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
430 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000431
432 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000434 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000435 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000436 return CFC;
437 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000438 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439 }
440
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000441 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000442
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000443 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444 if (!RC) {
445 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000446 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000447 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000448 if (OMD && OMD->isPropertyAccessor())
449 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
450 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000452 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000453 addRedeclaredMethods(OMD, Overridden);
454 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000455 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
456 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
457 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000459 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000460 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000461 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000462 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000463 if (const TagType *TT = QT->getAs<TagType>())
464 if (const Decl *TD = TT->getDecl())
465 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000467 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000468 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
469 while (IC->getSuperClass()) {
470 IC = IC->getSuperClass();
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 }
475 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
476 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
477 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
478 return cloneFullComment(FC, D);
479 }
480 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
481 if (!(RD = RD->getDefinition()))
482 return NULL;
483 // Check non-virtual bases.
484 for (CXXRecordDecl::base_class_const_iterator I =
485 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000486 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 continue;
488 QualType Ty = I->getType();
489 if (Ty.isNull())
490 continue;
491 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
492 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
493 continue;
494
495 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
496 return cloneFullComment(FC, D);
497 }
498 }
499 // Check virtual bases.
500 for (CXXRecordDecl::base_class_const_iterator I =
501 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000502 if (I->getAccessSpecifier() != AS_public)
503 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 QualType Ty = I->getType();
505 if (Ty.isNull())
506 continue;
507 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
508 if (!(VirtualBase= VirtualBase->getDefinition()))
509 continue;
510 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
511 return cloneFullComment(FC, D);
512 }
513 }
514 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000515 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000516 }
517
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000518 // If the RawComment was attached to other redeclaration of this Decl, we
519 // should parse the comment in context of that other Decl. This is important
520 // because comments can contain references to parameter names which can be
521 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000522 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000523 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000524
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000525 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000526 ParsedComments[Canonical] = FC;
527 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000528}
529
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000530void
531ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
532 TemplateTemplateParmDecl *Parm) {
533 ID.AddInteger(Parm->getDepth());
534 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000535 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000536
537 TemplateParameterList *Params = Parm->getTemplateParameters();
538 ID.AddInteger(Params->size());
539 for (TemplateParameterList::const_iterator P = Params->begin(),
540 PEnd = Params->end();
541 P != PEnd; ++P) {
542 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
543 ID.AddInteger(0);
544 ID.AddBoolean(TTP->isParameterPack());
545 continue;
546 }
547
548 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
549 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000550 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000551 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000552 if (NTTP->isExpandedParameterPack()) {
553 ID.AddBoolean(true);
554 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000555 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
556 QualType T = NTTP->getExpansionType(I);
557 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
558 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000559 } else
560 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000561 continue;
562 }
563
564 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
565 ID.AddInteger(2);
566 Profile(ID, TTP);
567 }
568}
569
570TemplateTemplateParmDecl *
571ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000572 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000573 // Check if we already have a canonical template template parameter.
574 llvm::FoldingSetNodeID ID;
575 CanonicalTemplateTemplateParm::Profile(ID, TTP);
576 void *InsertPos = 0;
577 CanonicalTemplateTemplateParm *Canonical
578 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
579 if (Canonical)
580 return Canonical->getParam();
581
582 // Build a canonical template parameter list.
583 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000584 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000585 CanonParams.reserve(Params->size());
586 for (TemplateParameterList::const_iterator P = Params->begin(),
587 PEnd = Params->end();
588 P != PEnd; ++P) {
589 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
590 CanonParams.push_back(
591 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000592 SourceLocation(),
593 SourceLocation(),
594 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000595 TTP->getIndex(), 0, false,
596 TTP->isParameterPack()));
597 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000598 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
599 QualType T = getCanonicalType(NTTP->getType());
600 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
601 NonTypeTemplateParmDecl *Param;
602 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000603 SmallVector<QualType, 2> ExpandedTypes;
604 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000605 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
606 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
607 ExpandedTInfos.push_back(
608 getTrivialTypeSourceInfo(ExpandedTypes.back()));
609 }
610
611 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000612 SourceLocation(),
613 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 NTTP->getDepth(),
615 NTTP->getPosition(), 0,
616 T,
617 TInfo,
618 ExpandedTypes.data(),
619 ExpandedTypes.size(),
620 ExpandedTInfos.data());
621 } else {
622 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000623 SourceLocation(),
624 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000625 NTTP->getDepth(),
626 NTTP->getPosition(), 0,
627 T,
628 NTTP->isParameterPack(),
629 TInfo);
630 }
631 CanonParams.push_back(Param);
632
633 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000634 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
635 cast<TemplateTemplateParmDecl>(*P)));
636 }
637
638 TemplateTemplateParmDecl *CanonTTP
639 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
640 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000641 TTP->getPosition(),
642 TTP->isParameterPack(),
643 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 TemplateParameterList::Create(*this, SourceLocation(),
645 SourceLocation(),
646 CanonParams.data(),
647 CanonParams.size(),
648 SourceLocation()));
649
650 // Get the new insert position for the node we care about.
651 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
652 assert(Canonical == 0 && "Shouldn't be in the map!");
653 (void)Canonical;
654
655 // Create the canonical template template parameter entry.
656 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
657 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
658 return CanonTTP;
659}
660
Charles Davis53c59df2010-08-16 03:33:14 +0000661CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000662 if (!LangOpts.CPlusPlus) return 0;
663
John McCall359b8852013-01-25 22:30:49 +0000664 switch (T.getCXXABI().getKind()) {
665 case TargetCXXABI::GenericARM:
666 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000667 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000668 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000669 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000670 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000671 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000672 return CreateMicrosoftCXXABI(*this);
673 }
David Blaikie8a40f702012-01-17 06:56:22 +0000674 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000675}
676
Douglas Gregore8bbc122011-09-02 00:18:52 +0000677static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000678 const LangOptions &LOpts) {
679 if (LOpts.FakeAddressSpaceMap) {
680 // The fake address space map must have a distinct entry for each
681 // language-specific address space.
682 static const unsigned FakeAddrSpaceMap[] = {
683 1, // opencl_global
684 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000685 3, // opencl_constant
686 4, // cuda_device
687 5, // cuda_constant
688 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000689 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000690 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000691 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000692 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000693 }
694}
695
David Tweed31d09b02013-09-13 12:04:22 +0000696static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
697 const LangOptions &LangOpts) {
698 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000699 case LangOptions::ASMM_Target:
700 return TI.useAddressSpaceMapMangling();
701 case LangOptions::ASMM_On:
702 return true;
703 case LangOptions::ASMM_Off:
704 return false;
705 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000706 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000707}
708
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000709ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000711 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000712 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 unsigned size_reserve,
714 bool DelayInitialization)
715 : FunctionProtoTypes(this_()),
716 TemplateSpecializationTypes(this_()),
717 DependentTemplateSpecializationTypes(this_()),
718 SubstTemplateTemplateParmPacks(this_()),
719 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000720 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000721 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000722 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000723 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000724 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000725 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000726 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
727 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
728 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000729 NullTypeSourceInfo(QualType()),
730 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000731 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000732 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000733 Idents(idents), Selectors(sels),
734 BuiltinInfo(builtins),
735 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000736 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000737 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000738 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000739 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000740{
Mike Stump11289f42009-09-09 15:08:12 +0000741 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000742 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000743
744 if (!DelayInitialization) {
745 assert(t && "No target supplied for ASTContext initialization");
746 InitBuiltinTypes(*t);
747 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000748}
749
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000750ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000751 // Release the DenseMaps associated with DeclContext objects.
752 // FIXME: Is this the ideal solution?
753 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000754
Manuel Klimeka7328992013-06-03 13:51:33 +0000755 // Call all of the deallocation functions on all of their targets.
756 for (DeallocationMap::const_iterator I = Deallocations.begin(),
757 E = Deallocations.end(); I != E; ++I)
758 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
759 (I->first)((I->second)[J]);
760
Ted Kremenek076baeb2010-06-08 23:00:58 +0000761 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000762 // because they can contain DenseMaps.
763 for (llvm::DenseMap<const ObjCContainerDecl*,
764 const ASTRecordLayout*>::iterator
765 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
766 // Increment in loop to prevent using deallocated memory.
767 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
768 R->Destroy(*this);
769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
771 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
772 // Increment in loop to prevent using deallocated memory.
773 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
774 R->Destroy(*this);
775 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000776
777 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
778 AEnd = DeclAttrs.end();
779 A != AEnd; ++A)
780 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000781
Reid Kleckner588c9372014-02-19 23:44:52 +0000782 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000783}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000784
Douglas Gregor1a809332010-05-23 18:26:36 +0000785void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000786 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000787}
788
Mike Stump11289f42009-09-09 15:08:12 +0000789void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000790ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
791 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000792}
793
Chris Lattner4eb445d2007-01-26 01:27:23 +0000794void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000795 llvm::errs() << "\n*** AST Context Stats:\n";
796 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000797
Douglas Gregora30d0462009-05-26 14:40:08 +0000798 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000799#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000800#define ABSTRACT_TYPE(Name, Parent)
801#include "clang/AST/TypeNodes.def"
802 0 // Extra
803 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000804
Chris Lattner4eb445d2007-01-26 01:27:23 +0000805 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
806 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000807 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000808 }
809
Douglas Gregora30d0462009-05-26 14:40:08 +0000810 unsigned Idx = 0;
811 unsigned TotalBytes = 0;
812#define TYPE(Name, Parent) \
813 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000814 llvm::errs() << " " << counts[Idx] << " " << #Name \
815 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000816 TotalBytes += counts[Idx] * sizeof(Name##Type); \
817 ++Idx;
818#define ABSTRACT_TYPE(Name, Parent)
819#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chandler Carruth3c147a72011-07-04 05:32:14 +0000821 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
822
Douglas Gregor7454c562010-07-02 20:37:36 +0000823 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000824 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
825 << NumImplicitDefaultConstructors
826 << " implicit default constructors created\n";
827 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
828 << NumImplicitCopyConstructors
829 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000830 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000831 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
832 << NumImplicitMoveConstructors
833 << " implicit move constructors created\n";
834 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
835 << NumImplicitCopyAssignmentOperators
836 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000837 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000838 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
839 << NumImplicitMoveAssignmentOperators
840 << " implicit move assignment operators created\n";
841 llvm::errs() << NumImplicitDestructorsDeclared << "/"
842 << NumImplicitDestructors
843 << " implicit destructors created\n";
844
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000845 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000847 ExternalSource->PrintStats();
848 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000849
Douglas Gregor5b11d492010-07-25 17:53:33 +0000850 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000851}
852
Alp Toker2dea15b2013-12-17 01:22:38 +0000853RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
854 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000855 SourceLocation Loc;
856 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000857 if (getLangOpts().CPlusPlus)
858 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
859 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000860 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000861 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
862 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000863 NewDecl->setImplicit();
864 return NewDecl;
865}
866
867TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
868 StringRef Name) const {
869 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
870 TypedefDecl *NewDecl = TypedefDecl::Create(
871 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
872 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
873 NewDecl->setImplicit();
874 return NewDecl;
875}
876
Douglas Gregor801c99d2011-08-12 06:49:56 +0000877TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000878 if (!Int128Decl)
879 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000880 return Int128Decl;
881}
882
883TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000884 if (!UInt128Decl)
885 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000886 return UInt128Decl;
887}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000888
Nico Webere1687c52013-06-20 21:44:55 +0000889TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000890 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000891 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000892 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000893
Nico Webere1687c52013-06-20 21:44:55 +0000894 return Float128StubDecl;
895}
896
John McCall48f2d582009-10-23 23:03:21 +0000897void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000898 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000899 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000900 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000901}
902
Douglas Gregore8bbc122011-09-02 00:18:52 +0000903void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
904 assert((!this->Target || this->Target == &Target) &&
905 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000906 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908 this->Target = &Target;
909
910 ABI.reset(createCXXABI(Target));
911 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000912 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000913
Chris Lattner970e54e2006-11-12 00:37:36 +0000914 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000915 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000916
Chris Lattner970e54e2006-11-12 00:37:36 +0000917 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000918 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000919 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000920 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000921 InitBuiltinType(CharTy, BuiltinType::Char_S);
922 else
923 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000924 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000925 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
926 InitBuiltinType(ShortTy, BuiltinType::Short);
927 InitBuiltinType(IntTy, BuiltinType::Int);
928 InitBuiltinType(LongTy, BuiltinType::Long);
929 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000930
Chris Lattner970e54e2006-11-12 00:37:36 +0000931 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000932 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
933 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
934 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
935 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
936 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner970e54e2006-11-12 00:37:36 +0000938 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000939 InitBuiltinType(FloatTy, BuiltinType::Float);
940 InitBuiltinType(DoubleTy, BuiltinType::Double);
941 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000942
Chris Lattnerf122cef2009-04-30 02:43:43 +0000943 // GNU extension, 128-bit integers.
944 InitBuiltinType(Int128Ty, BuiltinType::Int128);
945 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
946
Hans Wennborg0d81e012013-05-10 10:08:40 +0000947 // C++ 3.9.1p5
948 if (TargetInfo::isTypeSigned(Target.getWCharType()))
949 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
950 else // -fshort-wchar makes wchar_t be unsigned.
951 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
952 if (LangOpts.CPlusPlus && LangOpts.WChar)
953 WideCharTy = WCharTy;
954 else {
955 // C99 (or C++ using -fno-wchar).
956 WideCharTy = getFromTargetType(Target.getWCharType());
957 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000958
James Molloy36365542012-05-04 10:55:22 +0000959 WIntTy = getFromTargetType(Target.getWIntType());
960
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000961 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
962 InitBuiltinType(Char16Ty, BuiltinType::Char16);
963 else // C99
964 Char16Ty = getFromTargetType(Target.getChar16Type());
965
966 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
967 InitBuiltinType(Char32Ty, BuiltinType::Char32);
968 else // C99
969 Char32Ty = getFromTargetType(Target.getChar32Type());
970
Douglas Gregor4619e432008-12-05 23:32:09 +0000971 // Placeholder type for type-dependent expressions whose type is
972 // completely unknown. No code should ever check a type against
973 // DependentTy and users should never see it; however, it is here to
974 // help diagnose failures to properly check for type-dependent
975 // expressions.
976 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977
John McCall36e7fe32010-10-12 00:20:44 +0000978 // Placeholder type for functions.
979 InitBuiltinType(OverloadTy, BuiltinType::Overload);
980
John McCall0009fcc2011-04-26 20:42:42 +0000981 // Placeholder type for bound members.
982 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
983
John McCall526ab472011-10-25 17:37:35 +0000984 // Placeholder type for pseudo-objects.
985 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
986
John McCall31996342011-04-07 08:22:57 +0000987 // "any" type; useful for debugger-like clients.
988 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
989
John McCall8a6b59a2011-10-17 18:09:15 +0000990 // Placeholder type for unbridged ARC casts.
991 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
992
Eli Friedman34866c72012-08-31 00:14:07 +0000993 // Placeholder type for builtin functions.
994 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
995
Chris Lattner970e54e2006-11-12 00:37:36 +0000996 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000997 FloatComplexTy = getComplexType(FloatTy);
998 DoubleComplexTy = getComplexType(DoubleTy);
999 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001000
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001001 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001002 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1003 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001004 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001005
1006 if (LangOpts.OpenCL) {
1007 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1008 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1009 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1010 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1011 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1012 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001013
Guy Benyei61054192013-02-07 10:55:47 +00001014 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001015 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001016 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001017
1018 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001019 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1020 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001021
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001022 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001023
1024 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001025
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001026 // void * type
1027 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001028
1029 // nullptr type (C++0x 2.14.7)
1030 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001031
1032 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1033 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001034
1035 // Builtin type used to help define __builtin_va_list.
1036 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001037}
1038
David Blaikie9c902b52011-09-25 23:23:43 +00001039DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001040 return SourceMgr.getDiagnostics();
1041}
1042
Douglas Gregor561eceb2010-08-30 16:49:28 +00001043AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1044 AttrVec *&Result = DeclAttrs[D];
1045 if (!Result) {
1046 void *Mem = Allocate(sizeof(AttrVec));
1047 Result = new (Mem) AttrVec;
1048 }
1049
1050 return *Result;
1051}
1052
1053/// \brief Erase the attributes corresponding to the given declaration.
1054void ASTContext::eraseDeclAttrs(const Decl *D) {
1055 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1056 if (Pos != DeclAttrs.end()) {
1057 Pos->second->~AttrVec();
1058 DeclAttrs.erase(Pos);
1059 }
1060}
1061
Larisse Voufo39a1e502013-08-06 01:03:05 +00001062// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001063MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001064ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001065 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001066 return getTemplateOrSpecializationInfo(Var)
1067 .dyn_cast<MemberSpecializationInfo *>();
1068}
1069
1070ASTContext::TemplateOrSpecializationInfo
1071ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1072 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1073 TemplateOrInstantiation.find(Var);
1074 if (Pos == TemplateOrInstantiation.end())
1075 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001076
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001077 return Pos->second;
1078}
1079
Mike Stump11289f42009-09-09 15:08:12 +00001080void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001081ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001082 TemplateSpecializationKind TSK,
1083 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001084 assert(Inst->isStaticDataMember() && "Not a static data member");
1085 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001086 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1087 Tmpl, TSK, PointOfInstantiation));
1088}
1089
1090void
1091ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1092 TemplateOrSpecializationInfo TSI) {
1093 assert(!TemplateOrInstantiation[Inst] &&
1094 "Already noted what the variable was instantiated from");
1095 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001096}
1097
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001098FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1099 const FunctionDecl *FD){
1100 assert(FD && "Specialization is 0");
1101 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001102 = ClassScopeSpecializationPattern.find(FD);
1103 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001104 return 0;
1105
1106 return Pos->second;
1107}
1108
1109void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1110 FunctionDecl *Pattern) {
1111 assert(FD && "Specialization is 0");
1112 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001113 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001114}
1115
John McCalle61f2ba2009-11-18 02:36:19 +00001116NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001117ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001118 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001119 = InstantiatedFromUsingDecl.find(UUD);
1120 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001121 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001122
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001123 return Pos->second;
1124}
1125
1126void
John McCallb96ec562009-12-04 22:46:56 +00001127ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1128 assert((isa<UsingDecl>(Pattern) ||
1129 isa<UnresolvedUsingValueDecl>(Pattern) ||
1130 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1131 "pattern decl is not a using decl");
1132 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1133 InstantiatedFromUsingDecl[Inst] = Pattern;
1134}
1135
1136UsingShadowDecl *
1137ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1138 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1139 = InstantiatedFromUsingShadowDecl.find(Inst);
1140 if (Pos == InstantiatedFromUsingShadowDecl.end())
1141 return 0;
1142
1143 return Pos->second;
1144}
1145
1146void
1147ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1148 UsingShadowDecl *Pattern) {
1149 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1150 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001151}
1152
Anders Carlsson5da84842009-09-01 04:26:58 +00001153FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1154 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1155 = InstantiatedFromUnnamedFieldDecl.find(Field);
1156 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1157 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001158
Anders Carlsson5da84842009-09-01 04:26:58 +00001159 return Pos->second;
1160}
1161
1162void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1163 FieldDecl *Tmpl) {
1164 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1165 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1166 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1167 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001168
Anders Carlsson5da84842009-09-01 04:26:58 +00001169 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1170}
1171
Douglas Gregor832940b2010-03-02 23:58:15 +00001172ASTContext::overridden_cxx_method_iterator
1173ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1174 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001175 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001176 if (Pos == OverriddenMethods.end())
1177 return 0;
1178
1179 return Pos->second.begin();
1180}
1181
1182ASTContext::overridden_cxx_method_iterator
1183ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1184 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001185 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001186 if (Pos == OverriddenMethods.end())
1187 return 0;
1188
1189 return Pos->second.end();
1190}
1191
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001192unsigned
1193ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1194 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001195 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001196 if (Pos == OverriddenMethods.end())
1197 return 0;
1198
1199 return Pos->second.size();
1200}
1201
Douglas Gregor832940b2010-03-02 23:58:15 +00001202void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1203 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001204 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001205 OverriddenMethods[Method].push_back(Overridden);
1206}
1207
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001208void ASTContext::getOverriddenMethods(
1209 const NamedDecl *D,
1210 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001211 assert(D);
1212
1213 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001214 Overridden.append(overridden_methods_begin(CXXMethod),
1215 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001216 return;
1217 }
1218
1219 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1220 if (!Method)
1221 return;
1222
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001223 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1224 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001225 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001226}
1227
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001228void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1229 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1230 assert(!Import->isFromASTFile() && "Non-local import declaration");
1231 if (!FirstLocalImport) {
1232 FirstLocalImport = Import;
1233 LastLocalImport = Import;
1234 return;
1235 }
1236
1237 LastLocalImport->NextLocalImport = Import;
1238 LastLocalImport = Import;
1239}
1240
Chris Lattner53cfe802007-07-18 17:52:12 +00001241//===----------------------------------------------------------------------===//
1242// Type Sizing and Analysis
1243//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001244
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001245/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1246/// scalar floating point type.
1247const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001248 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001249 assert(BT && "Not a floating point type!");
1250 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001251 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001252 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001253 case BuiltinType::Float: return Target->getFloatFormat();
1254 case BuiltinType::Double: return Target->getDoubleFormat();
1255 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001256 }
1257}
1258
Rafael Espindola71eccb32013-08-08 19:53:46 +00001259CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001260 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001261
John McCall94268702010-10-08 18:24:19 +00001262 bool UseAlignAttrOnly = false;
1263 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1264 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001265
John McCall94268702010-10-08 18:24:19 +00001266 // __attribute__((aligned)) can increase or decrease alignment
1267 // *except* on a struct or struct member, where it only increases
1268 // alignment unless 'packed' is also specified.
1269 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001270 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001271 // ignore that possibility; Sema should diagnose it.
1272 if (isa<FieldDecl>(D)) {
1273 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1274 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1275 } else {
1276 UseAlignAttrOnly = true;
1277 }
1278 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001279 else if (isa<FieldDecl>(D))
1280 UseAlignAttrOnly =
1281 D->hasAttr<PackedAttr>() ||
1282 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001283
John McCall4e819612011-01-20 07:57:12 +00001284 // If we're using the align attribute only, just ignore everything
1285 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001286 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001287 // do nothing
1288
John McCall94268702010-10-08 18:24:19 +00001289 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001290 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001291 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001292 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001293 T = RT->getPointeeType();
1294 else
1295 T = getPointerType(RT->getPointeeType());
1296 }
1297 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001298 // Adjust alignments of declarations with array type by the
1299 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001300 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001301 unsigned MinWidth = Target->getLargeArrayMinWidth();
1302 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001303 if (isa<VariableArrayType>(arrayType))
1304 Align = std::max(Align, Target->getLargeArrayAlign());
1305 else if (isa<ConstantArrayType>(arrayType) &&
1306 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1307 Align = std::max(Align, Target->getLargeArrayAlign());
1308 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001309
John McCall33ddac02011-01-19 10:06:00 +00001310 // Walk through any array types while we're at it.
1311 T = getBaseElementType(arrayType);
1312 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001313 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001314 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1315 if (VD->hasGlobalStorage())
1316 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1317 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001318 }
John McCall4e819612011-01-20 07:57:12 +00001319
1320 // Fields can be subject to extra alignment constraints, like if
1321 // the field is packed, the struct is packed, or the struct has a
1322 // a max-field-alignment constraint (#pragma pack). So calculate
1323 // the actual alignment of the field within the struct, and then
1324 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001325 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1326 const RecordDecl *Parent = Field->getParent();
1327 // We can only produce a sensible answer if the record is valid.
1328 if (!Parent->isInvalidDecl()) {
1329 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001330
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001331 // Start with the record's overall alignment.
1332 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001333
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001334 // Use the GCD of that and the offset within the record.
1335 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1336 if (Offset > 0) {
1337 // Alignment is always a power of 2, so the GCD will be a power of 2,
1338 // which means we get to do this crazy thing instead of Euclid's.
1339 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1340 if (LowBitOfOffset < FieldAlign)
1341 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1342 }
1343
1344 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001345 }
Charles Davis3fc51072010-02-23 04:52:00 +00001346 }
Chris Lattner68061312009-01-24 21:53:27 +00001347 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001348
Ken Dyckcc56c542011-01-15 18:38:59 +00001349 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001350}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001351
John McCallf1249922012-08-21 04:10:00 +00001352// getTypeInfoDataSizeInChars - Return the size of a type, in
1353// chars. If the type is a record, its data size is returned. This is
1354// the size of the memcpy that's performed when assigning this type
1355// using a trivial copy/move assignment operator.
1356std::pair<CharUnits, CharUnits>
1357ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1358 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1359
1360 // In C++, objects can sometimes be allocated into the tail padding
1361 // of a base-class subobject. We decide whether that's possible
1362 // during class layout, so here we can just trust the layout results.
1363 if (getLangOpts().CPlusPlus) {
1364 if (const RecordType *RT = T->getAs<RecordType>()) {
1365 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1366 sizeAndAlign.first = layout.getDataSize();
1367 }
1368 }
1369
1370 return sizeAndAlign;
1371}
1372
Richard Trieu04d2d942013-05-14 21:59:17 +00001373/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1374/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1375std::pair<CharUnits, CharUnits>
1376static getConstantArrayInfoInChars(const ASTContext &Context,
1377 const ConstantArrayType *CAT) {
1378 std::pair<CharUnits, CharUnits> EltInfo =
1379 Context.getTypeInfoInChars(CAT->getElementType());
1380 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001381 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1382 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001383 "Overflow in array type char size evaluation");
1384 uint64_t Width = EltInfo.first.getQuantity() * Size;
1385 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001386 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1387 Context.getTargetInfo().getPointerWidth(0) == 64)
1388 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001389 return std::make_pair(CharUnits::fromQuantity(Width),
1390 CharUnits::fromQuantity(Align));
1391}
1392
John McCall87fe5d52010-05-20 01:18:31 +00001393std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001394ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001395 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1396 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001397 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001398 return std::make_pair(toCharUnitsFromBits(Info.first),
1399 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001400}
1401
1402std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001403ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001404 return getTypeInfoInChars(T.getTypePtr());
1405}
1406
Daniel Dunbarc6475872012-03-09 04:12:54 +00001407std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1408 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1409 if (it != MemoizedTypeInfo.end())
1410 return it->second;
1411
1412 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1413 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1414 return Info;
1415}
1416
1417/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1418/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001419///
1420/// FIXME: Pointers into different addr spaces could have different sizes and
1421/// alignment requirements: getPointerInfo should take an AddrSpace, this
1422/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001423std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001424ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001425 uint64_t Width=0;
1426 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001427 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001428#define TYPE(Class, Base)
1429#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001430#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001431#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001432#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1433 case Type::Class: \
1434 assert(!T->isDependentType() && "should not see dependent types here"); \
1435 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001436#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001437 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001438
Chris Lattner355332d2007-07-13 22:27:08 +00001439 case Type::FunctionNoProto:
1440 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001441 // GCC extension: alignof(function) = 32 bits
1442 Width = 0;
1443 Align = 32;
1444 break;
1445
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001446 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001447 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001448 Width = 0;
1449 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1450 break;
1451
Steve Naroff5c131802007-08-30 01:06:46 +00001452 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001453 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001454
Chris Lattner37e05872008-03-05 18:54:05 +00001455 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001456 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001457 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1458 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001459 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001460 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001461 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1462 getTargetInfo().getPointerWidth(0) == 64)
1463 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001464 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001465 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001466 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001467 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001468 const VectorType *VT = cast<VectorType>(T);
1469 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1470 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001471 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001472 // If the alignment is not a power of 2, round up to the next power of 2.
1473 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001474 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001475 Align = llvm::NextPowerOf2(Align);
1476 Width = llvm::RoundUpToAlignment(Width, Align);
1477 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001478 // Adjust the alignment based on the target max.
1479 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1480 if (TargetVectorAlign && TargetVectorAlign < Align)
1481 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001482 break;
1483 }
Chris Lattner647fb222007-07-18 18:26:58 +00001484
Chris Lattner7570e9c2008-03-08 08:52:55 +00001485 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001486 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001487 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001488 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001489 // GCC extension: alignof(void) = 8 bits.
1490 Width = 0;
1491 Align = 8;
1492 break;
1493
Chris Lattner6a4f7452007-12-19 19:23:28 +00001494 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001495 Width = Target->getBoolWidth();
1496 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001497 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001498 case BuiltinType::Char_S:
1499 case BuiltinType::Char_U:
1500 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001501 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001502 Width = Target->getCharWidth();
1503 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001504 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001505 case BuiltinType::WChar_S:
1506 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001507 Width = Target->getWCharWidth();
1508 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001509 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001510 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001511 Width = Target->getChar16Width();
1512 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001513 break;
1514 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001515 Width = Target->getChar32Width();
1516 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001517 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001518 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001519 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001520 Width = Target->getShortWidth();
1521 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001522 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001523 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001524 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 Width = Target->getIntWidth();
1526 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001528 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 Width = Target->getLongWidth();
1531 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001533 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001534 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001535 Width = Target->getLongLongWidth();
1536 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001537 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001538 case BuiltinType::Int128:
1539 case BuiltinType::UInt128:
1540 Width = 128;
1541 Align = 128; // int128_t is 128-bit aligned on all targets.
1542 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001543 case BuiltinType::Half:
1544 Width = Target->getHalfWidth();
1545 Align = Target->getHalfAlign();
1546 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001547 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001548 Width = Target->getFloatWidth();
1549 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001550 break;
1551 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getDoubleWidth();
1553 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
1555 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 Width = Target->getLongDoubleWidth();
1557 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001559 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001560 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1561 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001562 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001563 case BuiltinType::ObjCId:
1564 case BuiltinType::ObjCClass:
1565 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001566 Width = Target->getPointerWidth(0);
1567 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001568 break;
Guy Benyei61054192013-02-07 10:55:47 +00001569 case BuiltinType::OCLSampler:
1570 // Samplers are modeled as integers.
1571 Width = Target->getIntWidth();
1572 Align = Target->getIntAlign();
1573 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001574 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001575 case BuiltinType::OCLImage1d:
1576 case BuiltinType::OCLImage1dArray:
1577 case BuiltinType::OCLImage1dBuffer:
1578 case BuiltinType::OCLImage2d:
1579 case BuiltinType::OCLImage2dArray:
1580 case BuiltinType::OCLImage3d:
1581 // Currently these types are pointers to opaque types.
1582 Width = Target->getPointerWidth(0);
1583 Align = Target->getPointerAlign(0);
1584 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001585 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001586 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001587 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001588 Width = Target->getPointerWidth(0);
1589 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001590 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001591 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001592 unsigned AS = getTargetAddressSpace(
1593 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001594 Width = Target->getPointerWidth(AS);
1595 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001596 break;
1597 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001598 case Type::LValueReference:
1599 case Type::RValueReference: {
1600 // alignof and sizeof should never enter this code path here, so we go
1601 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001602 unsigned AS = getTargetAddressSpace(
1603 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001604 Width = Target->getPointerWidth(AS);
1605 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001606 break;
1607 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001608 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001609 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getPointerWidth(AS);
1611 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001612 break;
1613 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001614 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001615 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001616 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001617 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001618 }
Chris Lattner647fb222007-07-18 18:26:58 +00001619 case Type::Complex: {
1620 // Complex types have the same alignment as their elements, but twice the
1621 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001622 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001623 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001624 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001625 Align = EltInfo.second;
1626 break;
1627 }
John McCall8b07ec22010-05-15 11:32:37 +00001628 case Type::ObjCObject:
1629 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001630 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001631 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001632 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001633 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001634 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001635 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001636 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001637 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001638 break;
1639 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001640 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001641 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001642 const TagType *TT = cast<TagType>(T);
1643
1644 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001645 Width = 8;
1646 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001647 break;
1648 }
Mike Stump11289f42009-09-09 15:08:12 +00001649
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001650 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001651 return getTypeInfo(ET->getDecl()->getIntegerType());
1652
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001653 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001654 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001655 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001656 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001657 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001658 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001659
Chris Lattner63d2b362009-10-22 05:17:15 +00001660 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001661 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1662 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001663
Richard Smith30482bc2011-02-20 03:19:35 +00001664 case Type::Auto: {
1665 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001666 assert(!A->getDeducedType().isNull() &&
1667 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001668 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001669 }
1670
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001671 case Type::Paren:
1672 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1673
Douglas Gregoref462e62009-04-30 17:32:17 +00001674 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001675 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001676 std::pair<uint64_t, unsigned> Info
1677 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001678 // If the typedef has an aligned attribute on it, it overrides any computed
1679 // alignment we have. This violates the GCC documentation (which says that
1680 // attribute(aligned) can only round up) but matches its implementation.
1681 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1682 Align = AttrAlign;
1683 else
1684 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001685 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001686 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001687 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001688
Abramo Bagnara6150c882010-05-11 21:36:43 +00001689 case Type::Elaborated:
1690 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001691
John McCall81904512011-01-06 01:58:22 +00001692 case Type::Attributed:
1693 return getTypeInfo(
1694 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1695
Eli Friedman0dfb8892011-10-06 23:00:33 +00001696 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001697 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001698 std::pair<uint64_t, unsigned> Info
1699 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1700 Width = Info.first;
1701 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001702
1703 // If the size of the type doesn't exceed the platform's max
1704 // atomic promotion width, make the size and alignment more
1705 // favorable to atomic operations:
1706 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1707 // Round the size up to a power of 2.
1708 if (!llvm::isPowerOf2_64(Width))
1709 Width = llvm::NextPowerOf2(Width);
1710
1711 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001712 Align = static_cast<unsigned>(Width);
1713 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001714 }
1715
Douglas Gregoref462e62009-04-30 17:32:17 +00001716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001718 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001719 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001720}
1721
Ken Dyckcc56c542011-01-15 18:38:59 +00001722/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1723CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1724 return CharUnits::fromQuantity(BitSize / getCharWidth());
1725}
1726
Ken Dyckb0fcc592011-02-11 01:54:29 +00001727/// toBits - Convert a size in characters to a size in characters.
1728int64_t ASTContext::toBits(CharUnits CharSize) const {
1729 return CharSize.getQuantity() * getCharWidth();
1730}
1731
Ken Dyck8c89d592009-12-22 14:23:30 +00001732/// getTypeSizeInChars - Return the size of the specified type, in characters.
1733/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001734CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001735 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001736}
Jay Foad39c79802011-01-12 09:06:06 +00001737CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001738 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001739}
1740
Ken Dycka6046ab2010-01-26 17:25:18 +00001741/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001742/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001743CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001744 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001745}
Jay Foad39c79802011-01-12 09:06:06 +00001746CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001747 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001748}
1749
Chris Lattnera3402cd2009-01-27 18:08:34 +00001750/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1751/// type for the current target in bits. This can be different than the ABI
1752/// alignment in cases where it is beneficial for performance to overalign
1753/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001754unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001755 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001756
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001757 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1758 return ABIAlign; // Never overalign on XCore.
1759
David Majnemer8b6bd572014-02-24 23:34:17 +00001760 const TypedefType *TT = T->getAs<TypedefType>();
1761
Eli Friedman7ab09572009-05-25 21:27:19 +00001762 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001763 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001764 T = CT->getElementType().getTypePtr();
1765 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001766 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1767 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001768 // Don't increase the alignment if an alignment attribute was specified on a
1769 // typedef declaration.
1770 if (!TT || !TT->getDecl()->getMaxAlignment())
1771 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001772
Chris Lattnera3402cd2009-01-27 18:08:34 +00001773 return ABIAlign;
1774}
1775
Ulrich Weigandfa806422013-05-06 16:23:57 +00001776/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1777/// to a global variable of the specified type.
1778unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1779 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1780}
1781
1782/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1783/// should be given to a global variable of the specified type.
1784CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1785 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1786}
1787
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001788/// DeepCollectObjCIvars -
1789/// This routine first collects all declared, but not synthesized, ivars in
1790/// super class and then collects all ivars, including those synthesized for
1791/// current class. This routine is used for implementation of current class
1792/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001793///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001794void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1795 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001796 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001797 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1798 DeepCollectObjCIvars(SuperClass, false, Ivars);
1799 if (!leafClass) {
1800 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1801 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001802 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001803 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001804 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001805 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001806 Iv= Iv->getNextIvar())
1807 Ivars.push_back(Iv);
1808 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001809}
1810
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001811/// CollectInheritedProtocols - Collect all protocols in current class and
1812/// those inherited by it.
1813void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001814 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001815 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001816 // We can use protocol_iterator here instead of
1817 // all_referenced_protocol_iterator since we are walking all categories.
1818 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1819 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001821 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001822 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001823 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001824 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001825 CollectInheritedProtocols(*P, Protocols);
1826 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001827 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001828
1829 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001830 for (ObjCInterfaceDecl::visible_categories_iterator
1831 Cat = OI->visible_categories_begin(),
1832 CatEnd = OI->visible_categories_end();
1833 Cat != CatEnd; ++Cat) {
1834 CollectInheritedProtocols(*Cat, Protocols);
1835 }
1836
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001837 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1838 while (SD) {
1839 CollectInheritedProtocols(SD, Protocols);
1840 SD = SD->getSuperClass();
1841 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001842 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001843 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001844 PE = OC->protocol_end(); P != PE; ++P) {
1845 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001846 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001847 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1848 PE = Proto->protocol_end(); P != PE; ++P)
1849 CollectInheritedProtocols(*P, Protocols);
1850 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001851 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001852 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1853 PE = OP->protocol_end(); P != PE; ++P) {
1854 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001855 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001856 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1857 PE = Proto->protocol_end(); P != PE; ++P)
1858 CollectInheritedProtocols(*P, Protocols);
1859 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001860 }
1861}
1862
Jay Foad39c79802011-01-12 09:06:06 +00001863unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001864 unsigned count = 0;
1865 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001866 for (ObjCInterfaceDecl::known_extensions_iterator
1867 Ext = OI->known_extensions_begin(),
1868 ExtEnd = OI->known_extensions_end();
1869 Ext != ExtEnd; ++Ext) {
1870 count += Ext->ivar_size();
1871 }
1872
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001873 // Count ivar defined in this class's implementation. This
1874 // includes synthesized ivars.
1875 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001876 count += ImplDecl->ivar_size();
1877
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001878 return count;
1879}
1880
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001881bool ASTContext::isSentinelNullExpr(const Expr *E) {
1882 if (!E)
1883 return false;
1884
1885 // nullptr_t is always treated as null.
1886 if (E->getType()->isNullPtrType()) return true;
1887
1888 if (E->getType()->isAnyPointerType() &&
1889 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1890 Expr::NPC_ValueDependentIsNull))
1891 return true;
1892
1893 // Unfortunately, __null has type 'int'.
1894 if (isa<GNUNullExpr>(E)) return true;
1895
1896 return false;
1897}
1898
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001899/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1900ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1901 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1902 I = ObjCImpls.find(D);
1903 if (I != ObjCImpls.end())
1904 return cast<ObjCImplementationDecl>(I->second);
1905 return 0;
1906}
1907/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1908ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1909 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1910 I = ObjCImpls.find(D);
1911 if (I != ObjCImpls.end())
1912 return cast<ObjCCategoryImplDecl>(I->second);
1913 return 0;
1914}
1915
1916/// \brief Set the implementation of ObjCInterfaceDecl.
1917void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1918 ObjCImplementationDecl *ImplD) {
1919 assert(IFaceD && ImplD && "Passed null params");
1920 ObjCImpls[IFaceD] = ImplD;
1921}
1922/// \brief Set the implementation of ObjCCategoryDecl.
1923void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1924 ObjCCategoryImplDecl *ImplD) {
1925 assert(CatD && ImplD && "Passed null params");
1926 ObjCImpls[CatD] = ImplD;
1927}
1928
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001929const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1930 const NamedDecl *ND) const {
1931 if (const ObjCInterfaceDecl *ID =
1932 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001933 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001934 if (const ObjCCategoryDecl *CD =
1935 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001936 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001937 if (const ObjCImplDecl *IMD =
1938 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001939 return IMD->getClassInterface();
1940
1941 return 0;
1942}
1943
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001944/// \brief Get the copy initialization expression of VarDecl,or NULL if
1945/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001946Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001947 assert(VD && "Passed null params");
1948 assert(VD->hasAttr<BlocksAttr>() &&
1949 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001950 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001951 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001952 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1953}
1954
1955/// \brief Set the copy inialization expression of a block var decl.
1956void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1957 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001958 assert(VD->hasAttr<BlocksAttr>() &&
1959 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001960 BlockVarCopyInits[VD] = Init;
1961}
1962
John McCallbcd03502009-12-07 02:54:59 +00001963TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001964 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001965 if (!DataSize)
1966 DataSize = TypeLoc::getFullDataSizeForType(T);
1967 else
1968 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001969 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001970
John McCallbcd03502009-12-07 02:54:59 +00001971 TypeSourceInfo *TInfo =
1972 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1973 new (TInfo) TypeSourceInfo(T);
1974 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001975}
1976
John McCallbcd03502009-12-07 02:54:59 +00001977TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001978 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001979 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001980 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001981 return DI;
1982}
1983
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001984const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001985ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001986 return getObjCLayout(D, 0);
1987}
1988
1989const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001990ASTContext::getASTObjCImplementationLayout(
1991 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001992 return getObjCLayout(D->getClassInterface(), D);
1993}
1994
Chris Lattner983a8bb2007-07-13 22:13:22 +00001995//===----------------------------------------------------------------------===//
1996// Type creation/memoization methods
1997//===----------------------------------------------------------------------===//
1998
Jay Foad39c79802011-01-12 09:06:06 +00001999QualType
John McCall33ddac02011-01-19 10:06:00 +00002000ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2001 unsigned fastQuals = quals.getFastQualifiers();
2002 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002003
2004 // Check if we've already instantiated this type.
2005 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002006 ExtQuals::Profile(ID, baseType, quals);
2007 void *insertPos = 0;
2008 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2009 assert(eq->getQualifiers() == quals);
2010 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002011 }
2012
John McCall33ddac02011-01-19 10:06:00 +00002013 // If the base type is not canonical, make the appropriate canonical type.
2014 QualType canon;
2015 if (!baseType->isCanonicalUnqualified()) {
2016 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002017 canonSplit.Quals.addConsistentQualifiers(quals);
2018 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002019
2020 // Re-find the insert position.
2021 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2022 }
2023
2024 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2025 ExtQualNodes.InsertNode(eq, insertPos);
2026 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002027}
2028
Jay Foad39c79802011-01-12 09:06:06 +00002029QualType
2030ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002031 QualType CanT = getCanonicalType(T);
2032 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002033 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002034
John McCall8ccfcb52009-09-24 19:53:00 +00002035 // If we are composing extended qualifiers together, merge together
2036 // into one ExtQuals node.
2037 QualifierCollector Quals;
2038 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002039
John McCall8ccfcb52009-09-24 19:53:00 +00002040 // If this type already has an address space specified, it cannot get
2041 // another one.
2042 assert(!Quals.hasAddressSpace() &&
2043 "Type cannot be in multiple addr spaces!");
2044 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002045
John McCall8ccfcb52009-09-24 19:53:00 +00002046 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002047}
2048
Chris Lattnerd60183d2009-02-18 22:53:11 +00002049QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002050 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002051 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002052 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002053 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002054
John McCall53fa7142010-12-24 02:08:15 +00002055 if (const PointerType *ptr = T->getAs<PointerType>()) {
2056 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002057 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002058 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2059 return getPointerType(ResultType);
2060 }
2061 }
Mike Stump11289f42009-09-09 15:08:12 +00002062
John McCall8ccfcb52009-09-24 19:53:00 +00002063 // If we are composing extended qualifiers together, merge together
2064 // into one ExtQuals node.
2065 QualifierCollector Quals;
2066 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002067
John McCall8ccfcb52009-09-24 19:53:00 +00002068 // If this type already has an ObjCGC specified, it cannot get
2069 // another one.
2070 assert(!Quals.hasObjCGCAttr() &&
2071 "Type cannot have multiple ObjCGCs!");
2072 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002073
John McCall8ccfcb52009-09-24 19:53:00 +00002074 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002075}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002076
John McCall4f5019e2010-12-19 02:44:49 +00002077const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2078 FunctionType::ExtInfo Info) {
2079 if (T->getExtInfo() == Info)
2080 return T;
2081
2082 QualType Result;
2083 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002084 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002085 } else {
2086 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2087 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2088 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002089 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002090 }
2091
2092 return cast<FunctionType>(Result.getTypePtr());
2093}
2094
Richard Smith2a7d4812013-05-04 07:00:32 +00002095void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2096 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002097 FD = FD->getMostRecentDecl();
2098 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002099 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2100 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002101 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002102 if (FunctionDecl *Next = FD->getPreviousDecl())
2103 FD = Next;
2104 else
2105 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002106 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002107 if (ASTMutationListener *L = getASTMutationListener())
2108 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002109}
2110
Chris Lattnerc6395932007-06-22 20:56:16 +00002111/// getComplexType - Return the uniqued reference to the type for a complex
2112/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002113QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002114 // Unique pointers, to guarantee there is only one pointer of a particular
2115 // structure.
2116 llvm::FoldingSetNodeID ID;
2117 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattnerc6395932007-06-22 20:56:16 +00002119 void *InsertPos = 0;
2120 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2121 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002122
Chris Lattnerc6395932007-06-22 20:56:16 +00002123 // If the pointee type isn't canonical, this won't be a canonical type either,
2124 // so fill in the canonical type field.
2125 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002126 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002127 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattnerc6395932007-06-22 20:56:16 +00002129 // Get the new insert position for the node we care about.
2130 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002131 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002132 }
John McCall90d1c2d2009-09-24 23:30:46 +00002133 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002134 Types.push_back(New);
2135 ComplexTypes.InsertNode(New, InsertPos);
2136 return QualType(New, 0);
2137}
2138
Chris Lattner970e54e2006-11-12 00:37:36 +00002139/// getPointerType - Return the uniqued reference to the type for a pointer to
2140/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002141QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002142 // Unique pointers, to guarantee there is only one pointer of a particular
2143 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002144 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002145 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner67521df2007-01-27 01:29:36 +00002147 void *InsertPos = 0;
2148 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002149 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattner7ccecb92006-11-12 08:50:50 +00002151 // If the pointee type isn't canonical, this won't be a canonical type either,
2152 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002153 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002154 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002155 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002156
Bob Wilsonc8541f22013-03-15 17:12:43 +00002157 // Get the new insert position for the node we care about.
2158 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2159 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2160 }
John McCall90d1c2d2009-09-24 23:30:46 +00002161 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002162 Types.push_back(New);
2163 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002164 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002165}
2166
Reid Kleckner0503a872013-12-05 01:23:43 +00002167QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2168 llvm::FoldingSetNodeID ID;
2169 AdjustedType::Profile(ID, Orig, New);
2170 void *InsertPos = 0;
2171 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2172 if (AT)
2173 return QualType(AT, 0);
2174
2175 QualType Canonical = getCanonicalType(New);
2176
2177 // Get the new insert position for the node we care about.
2178 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2179 assert(AT == 0 && "Shouldn't be in the map!");
2180
2181 AT = new (*this, TypeAlignment)
2182 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2183 Types.push_back(AT);
2184 AdjustedTypes.InsertNode(AT, InsertPos);
2185 return QualType(AT, 0);
2186}
2187
Reid Kleckner8a365022013-06-24 17:51:48 +00002188QualType ASTContext::getDecayedType(QualType T) const {
2189 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2190
Reid Kleckner8a365022013-06-24 17:51:48 +00002191 QualType Decayed;
2192
2193 // C99 6.7.5.3p7:
2194 // A declaration of a parameter as "array of type" shall be
2195 // adjusted to "qualified pointer to type", where the type
2196 // qualifiers (if any) are those specified within the [ and ] of
2197 // the array type derivation.
2198 if (T->isArrayType())
2199 Decayed = getArrayDecayedType(T);
2200
2201 // C99 6.7.5.3p8:
2202 // A declaration of a parameter as "function returning type"
2203 // shall be adjusted to "pointer to function returning type", as
2204 // in 6.3.2.1.
2205 if (T->isFunctionType())
2206 Decayed = getPointerType(T);
2207
Reid Kleckner0503a872013-12-05 01:23:43 +00002208 llvm::FoldingSetNodeID ID;
2209 AdjustedType::Profile(ID, T, Decayed);
2210 void *InsertPos = 0;
2211 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2212 if (AT)
2213 return QualType(AT, 0);
2214
Reid Kleckner8a365022013-06-24 17:51:48 +00002215 QualType Canonical = getCanonicalType(Decayed);
2216
2217 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002218 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2219 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002220
Reid Kleckner0503a872013-12-05 01:23:43 +00002221 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2222 Types.push_back(AT);
2223 AdjustedTypes.InsertNode(AT, InsertPos);
2224 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002225}
2226
Mike Stump11289f42009-09-09 15:08:12 +00002227/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002228/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002229QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002230 assert(T->isFunctionType() && "block of function types only");
2231 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002232 // structure.
2233 llvm::FoldingSetNodeID ID;
2234 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002235
Steve Naroffec33ed92008-08-27 16:04:49 +00002236 void *InsertPos = 0;
2237 if (BlockPointerType *PT =
2238 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2239 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002240
2241 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002242 // type either so fill in the canonical type field.
2243 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002244 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002245 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002246
Steve Naroffec33ed92008-08-27 16:04:49 +00002247 // Get the new insert position for the node we care about.
2248 BlockPointerType *NewIP =
2249 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002250 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002251 }
John McCall90d1c2d2009-09-24 23:30:46 +00002252 BlockPointerType *New
2253 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002254 Types.push_back(New);
2255 BlockPointerTypes.InsertNode(New, InsertPos);
2256 return QualType(New, 0);
2257}
2258
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002259/// getLValueReferenceType - Return the uniqued reference to the type for an
2260/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002261QualType
2262ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002263 assert(getCanonicalType(T) != OverloadTy &&
2264 "Unresolved overloaded function type");
2265
Bill Wendling3708c182007-05-27 10:15:43 +00002266 // Unique pointers, to guarantee there is only one pointer of a particular
2267 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002268 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002269 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002270
2271 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002272 if (LValueReferenceType *RT =
2273 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002274 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002275
John McCallfc93cf92009-10-22 22:37:11 +00002276 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2277
Bill Wendling3708c182007-05-27 10:15:43 +00002278 // If the referencee type isn't canonical, this won't be a canonical type
2279 // either, so fill in the canonical type field.
2280 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002281 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2282 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2283 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002284
Bill Wendling3708c182007-05-27 10:15:43 +00002285 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002286 LValueReferenceType *NewIP =
2287 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002288 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002289 }
2290
John McCall90d1c2d2009-09-24 23:30:46 +00002291 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002292 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2293 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002294 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002295 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002296
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002297 return QualType(New, 0);
2298}
2299
2300/// getRValueReferenceType - Return the uniqued reference to the type for an
2301/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002302QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002303 // Unique pointers, to guarantee there is only one pointer of a particular
2304 // structure.
2305 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002306 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002307
2308 void *InsertPos = 0;
2309 if (RValueReferenceType *RT =
2310 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2311 return QualType(RT, 0);
2312
John McCallfc93cf92009-10-22 22:37:11 +00002313 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2314
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002315 // If the referencee type isn't canonical, this won't be a canonical type
2316 // either, so fill in the canonical type field.
2317 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002318 if (InnerRef || !T.isCanonical()) {
2319 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2320 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002321
2322 // Get the new insert position for the node we care about.
2323 RValueReferenceType *NewIP =
2324 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002325 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002326 }
2327
John McCall90d1c2d2009-09-24 23:30:46 +00002328 RValueReferenceType *New
2329 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002330 Types.push_back(New);
2331 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002332 return QualType(New, 0);
2333}
2334
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002335/// getMemberPointerType - Return the uniqued reference to the type for a
2336/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002337QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002338 // Unique pointers, to guarantee there is only one pointer of a particular
2339 // structure.
2340 llvm::FoldingSetNodeID ID;
2341 MemberPointerType::Profile(ID, T, Cls);
2342
2343 void *InsertPos = 0;
2344 if (MemberPointerType *PT =
2345 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2346 return QualType(PT, 0);
2347
2348 // If the pointee or class type isn't canonical, this won't be a canonical
2349 // type either, so fill in the canonical type field.
2350 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002351 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002352 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2353
2354 // Get the new insert position for the node we care about.
2355 MemberPointerType *NewIP =
2356 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002357 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002358 }
John McCall90d1c2d2009-09-24 23:30:46 +00002359 MemberPointerType *New
2360 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002361 Types.push_back(New);
2362 MemberPointerTypes.InsertNode(New, InsertPos);
2363 return QualType(New, 0);
2364}
2365
Mike Stump11289f42009-09-09 15:08:12 +00002366/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002367/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002368QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002369 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002370 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002371 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002372 assert((EltTy->isDependentType() ||
2373 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002374 "Constant array of VLAs is illegal!");
2375
Chris Lattnere2df3f92009-05-13 04:12:56 +00002376 // Convert the array size into a canonical width matching the pointer size for
2377 // the target.
2378 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002379 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002380 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002381
Chris Lattner23b7eb62007-06-15 23:05:46 +00002382 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002383 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner36f8e652007-01-27 08:31:04 +00002385 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002386 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002387 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002388 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002389
John McCall33ddac02011-01-19 10:06:00 +00002390 // If the element type isn't canonical or has qualifiers, this won't
2391 // be a canonical type either, so fill in the canonical type field.
2392 QualType Canon;
2393 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2394 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002395 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002396 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002397 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002398
Chris Lattner36f8e652007-01-27 08:31:04 +00002399 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002400 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002401 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002402 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
John McCall90d1c2d2009-09-24 23:30:46 +00002405 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002406 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002407 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002408 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002409 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002410}
2411
John McCall06549462011-01-18 08:40:38 +00002412/// getVariableArrayDecayedType - Turns the given type, which may be
2413/// variably-modified, into the corresponding type with all the known
2414/// sizes replaced with [*].
2415QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2416 // Vastly most common case.
2417 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002418
John McCall06549462011-01-18 08:40:38 +00002419 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002420
John McCall06549462011-01-18 08:40:38 +00002421 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002422 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002423 switch (ty->getTypeClass()) {
2424#define TYPE(Class, Base)
2425#define ABSTRACT_TYPE(Class, Base)
2426#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2427#include "clang/AST/TypeNodes.def"
2428 llvm_unreachable("didn't desugar past all non-canonical types?");
2429
2430 // These types should never be variably-modified.
2431 case Type::Builtin:
2432 case Type::Complex:
2433 case Type::Vector:
2434 case Type::ExtVector:
2435 case Type::DependentSizedExtVector:
2436 case Type::ObjCObject:
2437 case Type::ObjCInterface:
2438 case Type::ObjCObjectPointer:
2439 case Type::Record:
2440 case Type::Enum:
2441 case Type::UnresolvedUsing:
2442 case Type::TypeOfExpr:
2443 case Type::TypeOf:
2444 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002445 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002446 case Type::DependentName:
2447 case Type::InjectedClassName:
2448 case Type::TemplateSpecialization:
2449 case Type::DependentTemplateSpecialization:
2450 case Type::TemplateTypeParm:
2451 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002452 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002453 case Type::PackExpansion:
2454 llvm_unreachable("type should never be variably-modified");
2455
2456 // These types can be variably-modified but should never need to
2457 // further decay.
2458 case Type::FunctionNoProto:
2459 case Type::FunctionProto:
2460 case Type::BlockPointer:
2461 case Type::MemberPointer:
2462 return type;
2463
2464 // These types can be variably-modified. All these modifications
2465 // preserve structure except as noted by comments.
2466 // TODO: if we ever care about optimizing VLAs, there are no-op
2467 // optimizations available here.
2468 case Type::Pointer:
2469 result = getPointerType(getVariableArrayDecayedType(
2470 cast<PointerType>(ty)->getPointeeType()));
2471 break;
2472
2473 case Type::LValueReference: {
2474 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2475 result = getLValueReferenceType(
2476 getVariableArrayDecayedType(lv->getPointeeType()),
2477 lv->isSpelledAsLValue());
2478 break;
2479 }
2480
2481 case Type::RValueReference: {
2482 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2483 result = getRValueReferenceType(
2484 getVariableArrayDecayedType(lv->getPointeeType()));
2485 break;
2486 }
2487
Eli Friedman0dfb8892011-10-06 23:00:33 +00002488 case Type::Atomic: {
2489 const AtomicType *at = cast<AtomicType>(ty);
2490 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2491 break;
2492 }
2493
John McCall06549462011-01-18 08:40:38 +00002494 case Type::ConstantArray: {
2495 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2496 result = getConstantArrayType(
2497 getVariableArrayDecayedType(cat->getElementType()),
2498 cat->getSize(),
2499 cat->getSizeModifier(),
2500 cat->getIndexTypeCVRQualifiers());
2501 break;
2502 }
2503
2504 case Type::DependentSizedArray: {
2505 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2506 result = getDependentSizedArrayType(
2507 getVariableArrayDecayedType(dat->getElementType()),
2508 dat->getSizeExpr(),
2509 dat->getSizeModifier(),
2510 dat->getIndexTypeCVRQualifiers(),
2511 dat->getBracketsRange());
2512 break;
2513 }
2514
2515 // Turn incomplete types into [*] types.
2516 case Type::IncompleteArray: {
2517 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2518 result = getVariableArrayType(
2519 getVariableArrayDecayedType(iat->getElementType()),
2520 /*size*/ 0,
2521 ArrayType::Normal,
2522 iat->getIndexTypeCVRQualifiers(),
2523 SourceRange());
2524 break;
2525 }
2526
2527 // Turn VLA types into [*] types.
2528 case Type::VariableArray: {
2529 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2530 result = getVariableArrayType(
2531 getVariableArrayDecayedType(vat->getElementType()),
2532 /*size*/ 0,
2533 ArrayType::Star,
2534 vat->getIndexTypeCVRQualifiers(),
2535 vat->getBracketsRange());
2536 break;
2537 }
2538 }
2539
2540 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002541 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002542}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002543
Steve Naroffcadebd02007-08-30 18:14:25 +00002544/// getVariableArrayType - Returns a non-unique reference to the type for a
2545/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002546QualType ASTContext::getVariableArrayType(QualType EltTy,
2547 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002548 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002549 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002550 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002551 // Since we don't unique expressions, it isn't possible to unique VLA's
2552 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002553 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002554
John McCall33ddac02011-01-19 10:06:00 +00002555 // Be sure to pull qualifiers off the element type.
2556 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2557 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002558 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002559 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002560 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002561 }
2562
John McCall90d1c2d2009-09-24 23:30:46 +00002563 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002564 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002565
2566 VariableArrayTypes.push_back(New);
2567 Types.push_back(New);
2568 return QualType(New, 0);
2569}
2570
Douglas Gregor4619e432008-12-05 23:32:09 +00002571/// getDependentSizedArrayType - Returns a non-unique reference to
2572/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002573/// type.
John McCall33ddac02011-01-19 10:06:00 +00002574QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2575 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002576 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002577 unsigned elementTypeQuals,
2578 SourceRange brackets) const {
2579 assert((!numElements || numElements->isTypeDependent() ||
2580 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002581 "Size must be type- or value-dependent!");
2582
John McCall33ddac02011-01-19 10:06:00 +00002583 // Dependently-sized array types that do not have a specified number
2584 // of elements will have their sizes deduced from a dependent
2585 // initializer. We do no canonicalization here at all, which is okay
2586 // because they can't be used in most locations.
2587 if (!numElements) {
2588 DependentSizedArrayType *newType
2589 = new (*this, TypeAlignment)
2590 DependentSizedArrayType(*this, elementType, QualType(),
2591 numElements, ASM, elementTypeQuals,
2592 brackets);
2593 Types.push_back(newType);
2594 return QualType(newType, 0);
2595 }
2596
2597 // Otherwise, we actually build a new type every time, but we
2598 // also build a canonical type.
2599
2600 SplitQualType canonElementType = getCanonicalType(elementType).split();
2601
2602 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002603 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002604 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002605 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002606 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002607
John McCall33ddac02011-01-19 10:06:00 +00002608 // Look for an existing type with these properties.
2609 DependentSizedArrayType *canonTy =
2610 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002611
John McCall33ddac02011-01-19 10:06:00 +00002612 // If we don't have one, build one.
2613 if (!canonTy) {
2614 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002615 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002616 QualType(), numElements, ASM, elementTypeQuals,
2617 brackets);
2618 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2619 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002620 }
2621
John McCall33ddac02011-01-19 10:06:00 +00002622 // Apply qualifiers from the element type to the array.
2623 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002624 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002625
John McCall33ddac02011-01-19 10:06:00 +00002626 // If we didn't need extra canonicalization for the element type,
2627 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002628 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002629 return canon;
2630
2631 // Otherwise, we need to build a type which follows the spelling
2632 // of the element type.
2633 DependentSizedArrayType *sugaredType
2634 = new (*this, TypeAlignment)
2635 DependentSizedArrayType(*this, elementType, canon, numElements,
2636 ASM, elementTypeQuals, brackets);
2637 Types.push_back(sugaredType);
2638 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002639}
2640
John McCall33ddac02011-01-19 10:06:00 +00002641QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002642 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002643 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002644 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002645 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002646
John McCall33ddac02011-01-19 10:06:00 +00002647 void *insertPos = 0;
2648 if (IncompleteArrayType *iat =
2649 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2650 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002651
2652 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002653 // either, so fill in the canonical type field. We also have to pull
2654 // qualifiers off the element type.
2655 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002656
John McCall33ddac02011-01-19 10:06:00 +00002657 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2658 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002659 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002660 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002661 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002662
2663 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002664 IncompleteArrayType *existing =
2665 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2666 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002667 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002668
John McCall33ddac02011-01-19 10:06:00 +00002669 IncompleteArrayType *newType = new (*this, TypeAlignment)
2670 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002671
John McCall33ddac02011-01-19 10:06:00 +00002672 IncompleteArrayTypes.InsertNode(newType, insertPos);
2673 Types.push_back(newType);
2674 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002675}
2676
Steve Naroff91fcddb2007-07-18 18:00:27 +00002677/// getVectorType - Return the unique reference to a vector type of
2678/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002679QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002680 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002681 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002682
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002683 // Check if we've already instantiated a vector of this type.
2684 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002685 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002686
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002687 void *InsertPos = 0;
2688 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2689 return QualType(VTP, 0);
2690
2691 // If the element type isn't canonical, this won't be a canonical type either,
2692 // so fill in the canonical type field.
2693 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002694 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002695 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002696
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002697 // Get the new insert position for the node we care about.
2698 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002699 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002700 }
John McCall90d1c2d2009-09-24 23:30:46 +00002701 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002702 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002703 VectorTypes.InsertNode(New, InsertPos);
2704 Types.push_back(New);
2705 return QualType(New, 0);
2706}
2707
Nate Begemance4d7fc2008-04-18 23:10:10 +00002708/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002709/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002710QualType
2711ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002712 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002713
Steve Naroff91fcddb2007-07-18 18:00:27 +00002714 // Check if we've already instantiated a vector of this type.
2715 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002716 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002717 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002718 void *InsertPos = 0;
2719 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2720 return QualType(VTP, 0);
2721
2722 // If the element type isn't canonical, this won't be a canonical type either,
2723 // so fill in the canonical type field.
2724 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002725 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002726 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002727
Steve Naroff91fcddb2007-07-18 18:00:27 +00002728 // Get the new insert position for the node we care about.
2729 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002730 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002731 }
John McCall90d1c2d2009-09-24 23:30:46 +00002732 ExtVectorType *New = new (*this, TypeAlignment)
2733 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002734 VectorTypes.InsertNode(New, InsertPos);
2735 Types.push_back(New);
2736 return QualType(New, 0);
2737}
2738
Jay Foad39c79802011-01-12 09:06:06 +00002739QualType
2740ASTContext::getDependentSizedExtVectorType(QualType vecType,
2741 Expr *SizeExpr,
2742 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002743 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002744 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002745 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002746
Douglas Gregor352169a2009-07-31 03:54:25 +00002747 void *InsertPos = 0;
2748 DependentSizedExtVectorType *Canon
2749 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2750 DependentSizedExtVectorType *New;
2751 if (Canon) {
2752 // We already have a canonical version of this array type; use it as
2753 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002754 New = new (*this, TypeAlignment)
2755 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2756 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002757 } else {
2758 QualType CanonVecTy = getCanonicalType(vecType);
2759 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002760 New = new (*this, TypeAlignment)
2761 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2762 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002763
2764 DependentSizedExtVectorType *CanonCheck
2765 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2766 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2767 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002768 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2769 } else {
2770 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2771 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002772 New = new (*this, TypeAlignment)
2773 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002774 }
2775 }
Mike Stump11289f42009-09-09 15:08:12 +00002776
Douglas Gregor758a8692009-06-17 21:51:59 +00002777 Types.push_back(New);
2778 return QualType(New, 0);
2779}
2780
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002781/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002782///
Jay Foad39c79802011-01-12 09:06:06 +00002783QualType
2784ASTContext::getFunctionNoProtoType(QualType ResultTy,
2785 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002786 const CallingConv CallConv = Info.getCC();
2787
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002788 // Unique functions, to guarantee there is only one function of a particular
2789 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002790 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002791 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002792
Chris Lattner47955de2007-01-27 08:37:20 +00002793 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002794 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002795 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002796 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002797
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002798 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002799 if (!ResultTy.isCanonical()) {
2800 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002801
Chris Lattner47955de2007-01-27 08:37:20 +00002802 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002803 FunctionNoProtoType *NewIP =
2804 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002805 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
Roman Divacky65b88cd2011-03-01 17:40:53 +00002808 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002809 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002810 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002811 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002812 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002813 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002814}
2815
Douglas Gregorcd780372013-01-17 23:36:45 +00002816/// \brief Determine whether \p T is canonical as the result type of a function.
2817static bool isCanonicalResultType(QualType T) {
2818 return T.isCanonical() &&
2819 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2820 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2821}
2822
Jay Foad39c79802011-01-12 09:06:06 +00002823QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002824ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002825 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002826 size_t NumArgs = ArgArray.size();
2827
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002828 // Unique functions, to guarantee there is only one function of a particular
2829 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002830 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002831 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2832 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002833
2834 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002835 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002836 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002837 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002838
2839 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002840 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002841 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002842 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002843 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002844 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002845 isCanonical = false;
2846
2847 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002848 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002849 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002850 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002851 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002852 CanonicalArgs.reserve(NumArgs);
2853 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002854 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002855
John McCalldb40c7f2010-12-14 08:05:40 +00002856 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002857 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002858 CanonicalEPI.ExceptionSpecType = EST_None;
2859 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002860
Douglas Gregorcd780372013-01-17 23:36:45 +00002861 // Result types do not have ARC lifetime qualifiers.
2862 QualType CanResultTy = getCanonicalType(ResultTy);
2863 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2864 Qualifiers Qs = CanResultTy.getQualifiers();
2865 Qs.removeObjCLifetime();
2866 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2867 }
2868
Jordan Rose5c382722013-03-08 21:51:21 +00002869 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002870
Chris Lattnerfd4de792007-01-27 01:15:32 +00002871 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002872 FunctionProtoType *NewIP =
2873 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002874 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002875 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002876
John McCall31168b02011-06-15 23:02:42 +00002877 // FunctionProtoType objects are allocated with extra bytes after
2878 // them for three variable size arrays at the end:
2879 // - parameter types
2880 // - exception types
2881 // - consumed-arguments flags
2882 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002883 // expression, or information used to resolve the exception
2884 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002885 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002886 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002887 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002888 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002889 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002890 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002891 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002892 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002893 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2894 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002895 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002896 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002897 Size += NumArgs * sizeof(bool);
2898
John McCalldb40c7f2010-12-14 08:05:40 +00002899 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002900 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002901 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002902 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002903 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002904 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002905}
Chris Lattneref51c202006-11-10 07:17:23 +00002906
John McCalle78aac42010-03-10 03:28:59 +00002907#ifndef NDEBUG
2908static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2909 if (!isa<CXXRecordDecl>(D)) return false;
2910 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2911 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2912 return true;
2913 if (RD->getDescribedClassTemplate() &&
2914 !isa<ClassTemplateSpecializationDecl>(RD))
2915 return true;
2916 return false;
2917}
2918#endif
2919
2920/// getInjectedClassNameType - Return the unique reference to the
2921/// injected class name type for the specified templated declaration.
2922QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002923 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002924 assert(NeedsInjectedClassNameType(Decl));
2925 if (Decl->TypeForDecl) {
2926 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002927 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002928 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2929 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2930 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2931 } else {
John McCall424cec92011-01-19 06:33:43 +00002932 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002933 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002934 Decl->TypeForDecl = newType;
2935 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002936 }
2937 return QualType(Decl->TypeForDecl, 0);
2938}
2939
Douglas Gregor83a586e2008-04-13 21:07:44 +00002940/// getTypeDeclType - Return the unique reference to the type for the
2941/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002942QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002943 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002944 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002945
Richard Smithdda56e42011-04-15 14:24:37 +00002946 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002947 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002948
John McCall96f0b5f2010-03-10 06:48:02 +00002949 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2950 "Template type parameter types are always available.");
2951
John McCall81e38502010-02-16 03:57:14 +00002952 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002953 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002954 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002955 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002956 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002957 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002958 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002959 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002960 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002961 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2962 Decl->TypeForDecl = newType;
2963 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002964 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002965 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002966
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002967 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002968}
2969
Chris Lattner32d920b2007-01-26 02:01:53 +00002970/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002971/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002972QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002973ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2974 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002975 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002976
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002977 if (Canonical.isNull())
2978 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002979 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002980 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002981 Decl->TypeForDecl = newType;
2982 Types.push_back(newType);
2983 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002984}
2985
Jay Foad39c79802011-01-12 09:06:06 +00002986QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002987 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2988
Douglas Gregorec9fd132012-01-14 16:38:05 +00002989 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002990 if (PrevDecl->TypeForDecl)
2991 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2992
John McCall424cec92011-01-19 06:33:43 +00002993 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2994 Decl->TypeForDecl = newType;
2995 Types.push_back(newType);
2996 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002997}
2998
Jay Foad39c79802011-01-12 09:06:06 +00002999QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003000 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3001
Douglas Gregorec9fd132012-01-14 16:38:05 +00003002 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003003 if (PrevDecl->TypeForDecl)
3004 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3005
John McCall424cec92011-01-19 06:33:43 +00003006 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3007 Decl->TypeForDecl = newType;
3008 Types.push_back(newType);
3009 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003010}
3011
John McCall81904512011-01-06 01:58:22 +00003012QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3013 QualType modifiedType,
3014 QualType equivalentType) {
3015 llvm::FoldingSetNodeID id;
3016 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3017
3018 void *insertPos = 0;
3019 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3020 if (type) return QualType(type, 0);
3021
3022 QualType canon = getCanonicalType(equivalentType);
3023 type = new (*this, TypeAlignment)
3024 AttributedType(canon, attrKind, modifiedType, equivalentType);
3025
3026 Types.push_back(type);
3027 AttributedTypes.InsertNode(type, insertPos);
3028
3029 return QualType(type, 0);
3030}
3031
3032
John McCallcebee162009-10-18 09:09:24 +00003033/// \brief Retrieve a substitution-result type.
3034QualType
3035ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003036 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003037 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003038 && "replacement types must always be canonical");
3039
3040 llvm::FoldingSetNodeID ID;
3041 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3042 void *InsertPos = 0;
3043 SubstTemplateTypeParmType *SubstParm
3044 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3045
3046 if (!SubstParm) {
3047 SubstParm = new (*this, TypeAlignment)
3048 SubstTemplateTypeParmType(Parm, Replacement);
3049 Types.push_back(SubstParm);
3050 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3051 }
3052
3053 return QualType(SubstParm, 0);
3054}
3055
Douglas Gregorada4b792011-01-14 02:55:32 +00003056/// \brief Retrieve a
3057QualType ASTContext::getSubstTemplateTypeParmPackType(
3058 const TemplateTypeParmType *Parm,
3059 const TemplateArgument &ArgPack) {
3060#ifndef NDEBUG
3061 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3062 PEnd = ArgPack.pack_end();
3063 P != PEnd; ++P) {
3064 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3065 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3066 }
3067#endif
3068
3069 llvm::FoldingSetNodeID ID;
3070 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3071 void *InsertPos = 0;
3072 if (SubstTemplateTypeParmPackType *SubstParm
3073 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3074 return QualType(SubstParm, 0);
3075
3076 QualType Canon;
3077 if (!Parm->isCanonicalUnqualified()) {
3078 Canon = getCanonicalType(QualType(Parm, 0));
3079 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3080 ArgPack);
3081 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3082 }
3083
3084 SubstTemplateTypeParmPackType *SubstParm
3085 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3086 ArgPack);
3087 Types.push_back(SubstParm);
3088 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3089 return QualType(SubstParm, 0);
3090}
3091
Douglas Gregoreff93e02009-02-05 23:33:38 +00003092/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003093/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003094/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003095QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003096 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003097 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003098 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003099 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003100 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003101 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003102 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3103
3104 if (TypeParm)
3105 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003106
Chandler Carruth08836322011-05-01 00:51:33 +00003107 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003108 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003109 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003110
3111 TemplateTypeParmType *TypeCheck
3112 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3113 assert(!TypeCheck && "Template type parameter canonical type broken");
3114 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003115 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003116 TypeParm = new (*this, TypeAlignment)
3117 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003118
3119 Types.push_back(TypeParm);
3120 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3121
3122 return QualType(TypeParm, 0);
3123}
3124
John McCalle78aac42010-03-10 03:28:59 +00003125TypeSourceInfo *
3126ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3127 SourceLocation NameLoc,
3128 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003129 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003130 assert(!Name.getAsDependentTemplateName() &&
3131 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003132 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003133
3134 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003135 TemplateSpecializationTypeLoc TL =
3136 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003137 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003138 TL.setTemplateNameLoc(NameLoc);
3139 TL.setLAngleLoc(Args.getLAngleLoc());
3140 TL.setRAngleLoc(Args.getRAngleLoc());
3141 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3142 TL.setArgLocInfo(i, Args[i].getLocInfo());
3143 return DI;
3144}
3145
Mike Stump11289f42009-09-09 15:08:12 +00003146QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003147ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003148 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003149 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003150 assert(!Template.getAsDependentTemplateName() &&
3151 "No dependent template names here!");
3152
John McCall6b51f282009-11-23 01:53:49 +00003153 unsigned NumArgs = Args.size();
3154
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003155 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003156 ArgVec.reserve(NumArgs);
3157 for (unsigned i = 0; i != NumArgs; ++i)
3158 ArgVec.push_back(Args[i].getArgument());
3159
John McCall2408e322010-04-27 00:57:59 +00003160 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003161 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003162}
3163
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003164#ifndef NDEBUG
3165static bool hasAnyPackExpansions(const TemplateArgument *Args,
3166 unsigned NumArgs) {
3167 for (unsigned I = 0; I != NumArgs; ++I)
3168 if (Args[I].isPackExpansion())
3169 return true;
3170
3171 return true;
3172}
3173#endif
3174
John McCall0ad16662009-10-29 08:12:44 +00003175QualType
3176ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003177 const TemplateArgument *Args,
3178 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003179 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003180 assert(!Template.getAsDependentTemplateName() &&
3181 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003182 // Look through qualified template names.
3183 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3184 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003185
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003186 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003187 Template.getAsTemplateDecl() &&
3188 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003189 QualType CanonType;
3190 if (!Underlying.isNull())
3191 CanonType = getCanonicalType(Underlying);
3192 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003193 // We can get here with an alias template when the specialization contains
3194 // a pack expansion that does not match up with a parameter pack.
3195 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3196 "Caller must compute aliased type");
3197 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003198 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3199 NumArgs);
3200 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003201
Douglas Gregora8e02e72009-07-28 23:00:59 +00003202 // Allocate the (non-canonical) template specialization type, but don't
3203 // try to unique it: these types typically have location information that
3204 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003205 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3206 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003207 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003208 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003209 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003210 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3211 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003212
Douglas Gregor8bf42052009-02-09 18:46:07 +00003213 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003214 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003215}
3216
Mike Stump11289f42009-09-09 15:08:12 +00003217QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003218ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3219 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003220 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003221 assert(!Template.getAsDependentTemplateName() &&
3222 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003223
Douglas Gregore29139c2011-03-03 17:04:51 +00003224 // Look through qualified template names.
3225 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3226 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003227
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003228 // Build the canonical template specialization type.
3229 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003230 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003231 CanonArgs.reserve(NumArgs);
3232 for (unsigned I = 0; I != NumArgs; ++I)
3233 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3234
3235 // Determine whether this canonical template specialization type already
3236 // exists.
3237 llvm::FoldingSetNodeID ID;
3238 TemplateSpecializationType::Profile(ID, CanonTemplate,
3239 CanonArgs.data(), NumArgs, *this);
3240
3241 void *InsertPos = 0;
3242 TemplateSpecializationType *Spec
3243 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3244
3245 if (!Spec) {
3246 // Allocate a new canonical template specialization type.
3247 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3248 sizeof(TemplateArgument) * NumArgs),
3249 TypeAlignment);
3250 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3251 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003252 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003253 Types.push_back(Spec);
3254 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3255 }
3256
3257 assert(Spec->isDependentType() &&
3258 "Non-dependent template-id type must have a canonical type");
3259 return QualType(Spec, 0);
3260}
3261
3262QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003263ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3264 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003265 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003266 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003267 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003268
3269 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003270 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003271 if (T)
3272 return QualType(T, 0);
3273
Douglas Gregorc42075a2010-02-04 18:10:26 +00003274 QualType Canon = NamedType;
3275 if (!Canon.isCanonical()) {
3276 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003277 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3278 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003279 (void)CheckT;
3280 }
3281
Abramo Bagnara6150c882010-05-11 21:36:43 +00003282 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003283 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003284 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003285 return QualType(T, 0);
3286}
3287
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003288QualType
Jay Foad39c79802011-01-12 09:06:06 +00003289ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003290 llvm::FoldingSetNodeID ID;
3291 ParenType::Profile(ID, InnerType);
3292
3293 void *InsertPos = 0;
3294 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3295 if (T)
3296 return QualType(T, 0);
3297
3298 QualType Canon = InnerType;
3299 if (!Canon.isCanonical()) {
3300 Canon = getCanonicalType(InnerType);
3301 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3302 assert(!CheckT && "Paren canonical type broken");
3303 (void)CheckT;
3304 }
3305
3306 T = new (*this) ParenType(InnerType, Canon);
3307 Types.push_back(T);
3308 ParenTypes.InsertNode(T, InsertPos);
3309 return QualType(T, 0);
3310}
3311
Douglas Gregor02085352010-03-31 20:19:30 +00003312QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3313 NestedNameSpecifier *NNS,
3314 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003315 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003316 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3317
3318 if (Canon.isNull()) {
3319 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003320 ElaboratedTypeKeyword CanonKeyword = Keyword;
3321 if (Keyword == ETK_None)
3322 CanonKeyword = ETK_Typename;
3323
3324 if (CanonNNS != NNS || CanonKeyword != Keyword)
3325 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003326 }
3327
3328 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003329 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003330
3331 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003332 DependentNameType *T
3333 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003334 if (T)
3335 return QualType(T, 0);
3336
Douglas Gregor02085352010-03-31 20:19:30 +00003337 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003338 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003339 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003340 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003341}
3342
Mike Stump11289f42009-09-09 15:08:12 +00003343QualType
John McCallc392f372010-06-11 00:33:02 +00003344ASTContext::getDependentTemplateSpecializationType(
3345 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003346 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003347 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003348 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003349 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003350 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003351 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3352 ArgCopy.push_back(Args[I].getArgument());
3353 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3354 ArgCopy.size(),
3355 ArgCopy.data());
3356}
3357
3358QualType
3359ASTContext::getDependentTemplateSpecializationType(
3360 ElaboratedTypeKeyword Keyword,
3361 NestedNameSpecifier *NNS,
3362 const IdentifierInfo *Name,
3363 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003364 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003365 assert((!NNS || NNS->isDependent()) &&
3366 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003367
Douglas Gregorc42075a2010-02-04 18:10:26 +00003368 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003369 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3370 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003371
3372 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003373 DependentTemplateSpecializationType *T
3374 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003375 if (T)
3376 return QualType(T, 0);
3377
John McCallc392f372010-06-11 00:33:02 +00003378 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003379
John McCallc392f372010-06-11 00:33:02 +00003380 ElaboratedTypeKeyword CanonKeyword = Keyword;
3381 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3382
3383 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003384 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003385 for (unsigned I = 0; I != NumArgs; ++I) {
3386 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3387 if (!CanonArgs[I].structurallyEquals(Args[I]))
3388 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003389 }
3390
John McCallc392f372010-06-11 00:33:02 +00003391 QualType Canon;
3392 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3393 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3394 Name, NumArgs,
3395 CanonArgs.data());
3396
3397 // Find the insert position again.
3398 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3399 }
3400
3401 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3402 sizeof(TemplateArgument) * NumArgs),
3403 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003404 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003405 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003406 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003407 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003408 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003409}
3410
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003411QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003412 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003413 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003414 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003415
3416 assert(Pattern->containsUnexpandedParameterPack() &&
3417 "Pack expansions must expand one or more parameter packs");
3418 void *InsertPos = 0;
3419 PackExpansionType *T
3420 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3421 if (T)
3422 return QualType(T, 0);
3423
3424 QualType Canon;
3425 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003426 Canon = getCanonicalType(Pattern);
3427 // The canonical type might not contain an unexpanded parameter pack, if it
3428 // contains an alias template specialization which ignores one of its
3429 // parameters.
3430 if (Canon->containsUnexpandedParameterPack()) {
3431 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003432
Richard Smith68eea502012-07-16 00:20:35 +00003433 // Find the insert position again, in case we inserted an element into
3434 // PackExpansionTypes and invalidated our insert position.
3435 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3436 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003437 }
3438
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003439 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003440 Types.push_back(T);
3441 PackExpansionTypes.InsertNode(T, InsertPos);
3442 return QualType(T, 0);
3443}
3444
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003445/// CmpProtocolNames - Comparison predicate for sorting protocols
3446/// alphabetically.
3447static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3448 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003449 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003450}
3451
John McCall8b07ec22010-05-15 11:32:37 +00003452static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003453 unsigned NumProtocols) {
3454 if (NumProtocols == 0) return true;
3455
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003456 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3457 return false;
3458
John McCallfc93cf92009-10-22 22:37:11 +00003459 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003460 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3461 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003462 return false;
3463 return true;
3464}
3465
3466static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003467 unsigned &NumProtocols) {
3468 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003469
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003470 // Sort protocols, keyed by name.
3471 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3472
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003473 // Canonicalize.
3474 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3475 Protocols[I] = Protocols[I]->getCanonicalDecl();
3476
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003477 // Remove duplicates.
3478 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3479 NumProtocols = ProtocolsEnd-Protocols;
3480}
3481
John McCall8b07ec22010-05-15 11:32:37 +00003482QualType ASTContext::getObjCObjectType(QualType BaseType,
3483 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003484 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003485 // If the base type is an interface and there aren't any protocols
3486 // to add, then the interface type will do just fine.
3487 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3488 return BaseType;
3489
3490 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003491 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003492 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003493 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003494 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3495 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003496
John McCall8b07ec22010-05-15 11:32:37 +00003497 // Build the canonical type, which has the canonical base type and
3498 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003499 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003500 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3501 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3502 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003503 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003504 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003505 unsigned UniqueCount = NumProtocols;
3506
John McCallfc93cf92009-10-22 22:37:11 +00003507 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003508 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3509 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003510 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003511 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3512 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003513 }
3514
3515 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003516 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3517 }
3518
3519 unsigned Size = sizeof(ObjCObjectTypeImpl);
3520 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3521 void *Mem = Allocate(Size, TypeAlignment);
3522 ObjCObjectTypeImpl *T =
3523 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3524
3525 Types.push_back(T);
3526 ObjCObjectTypes.InsertNode(T, InsertPos);
3527 return QualType(T, 0);
3528}
3529
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003530/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3531/// protocol list adopt all protocols in QT's qualified-id protocol
3532/// list.
3533bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3534 ObjCInterfaceDecl *IC) {
3535 if (!QT->isObjCQualifiedIdType())
3536 return false;
3537
3538 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3539 // If both the right and left sides have qualifiers.
3540 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3541 E = OPT->qual_end(); I != E; ++I) {
3542 ObjCProtocolDecl *Proto = *I;
3543 if (!IC->ClassImplementsProtocol(Proto, false))
3544 return false;
3545 }
3546 return true;
3547 }
3548 return false;
3549}
3550
3551/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3552/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3553/// of protocols.
3554bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3555 ObjCInterfaceDecl *IDecl) {
3556 if (!QT->isObjCQualifiedIdType())
3557 return false;
3558 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3559 if (!OPT)
3560 return false;
3561 if (!IDecl->hasDefinition())
3562 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003563 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3564 CollectInheritedProtocols(IDecl, InheritedProtocols);
3565 if (InheritedProtocols.empty())
3566 return false;
3567
3568 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3569 InheritedProtocols.begin(),
3570 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003571 // If both the right and left sides have qualifiers.
3572 bool Adopts = false;
3573 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3574 E = OPT->qual_end(); I != E; ++I) {
3575 ObjCProtocolDecl *Proto = *I;
3576 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3577 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3578 break;
3579 }
3580 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003581 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003582 }
3583 return true;
3584}
3585
John McCall8b07ec22010-05-15 11:32:37 +00003586/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3587/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003588QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003589 llvm::FoldingSetNodeID ID;
3590 ObjCObjectPointerType::Profile(ID, ObjectT);
3591
3592 void *InsertPos = 0;
3593 if (ObjCObjectPointerType *QT =
3594 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3595 return QualType(QT, 0);
3596
3597 // Find the canonical object type.
3598 QualType Canonical;
3599 if (!ObjectT.isCanonical()) {
3600 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3601
3602 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003603 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3604 }
3605
Douglas Gregorf85bee62010-02-08 22:59:26 +00003606 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003607 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3608 ObjCObjectPointerType *QType =
3609 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003610
Steve Narofffb4330f2009-06-17 22:40:22 +00003611 Types.push_back(QType);
3612 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003613 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003614}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003615
Douglas Gregor1c283312010-08-11 12:19:30 +00003616/// getObjCInterfaceType - Return the unique reference to the type for the
3617/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003618QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3619 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003620 if (Decl->TypeForDecl)
3621 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003622
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003623 if (PrevDecl) {
3624 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3625 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3626 return QualType(PrevDecl->TypeForDecl, 0);
3627 }
3628
Douglas Gregor7671e532011-12-16 16:34:57 +00003629 // Prefer the definition, if there is one.
3630 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3631 Decl = Def;
3632
Douglas Gregor1c283312010-08-11 12:19:30 +00003633 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3634 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3635 Decl->TypeForDecl = T;
3636 Types.push_back(T);
3637 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003638}
3639
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003640/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3641/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003642/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003643/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003644/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003645QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003646 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003647 if (tofExpr->isTypeDependent()) {
3648 llvm::FoldingSetNodeID ID;
3649 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003650
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003651 void *InsertPos = 0;
3652 DependentTypeOfExprType *Canon
3653 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3654 if (Canon) {
3655 // We already have a "canonical" version of an identical, dependent
3656 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003657 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003658 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003659 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003660 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003661 Canon
3662 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003663 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3664 toe = Canon;
3665 }
3666 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003667 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003668 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003669 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003670 Types.push_back(toe);
3671 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003672}
3673
Steve Naroffa773cd52007-08-01 18:02:17 +00003674/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3675/// TypeOfType AST's. The only motivation to unique these nodes would be
3676/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003677/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003678/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003679QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003680 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003681 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003682 Types.push_back(tot);
3683 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003684}
3685
Anders Carlssonad6bd352009-06-24 21:24:56 +00003686
Anders Carlsson81df7b82009-06-24 19:06:50 +00003687/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3688/// DecltypeType AST's. The only motivation to unique these nodes would be
3689/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003690/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003691/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003692QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003693 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003694
3695 // C++0x [temp.type]p2:
3696 // If an expression e involves a template parameter, decltype(e) denotes a
3697 // unique dependent type. Two such decltype-specifiers refer to the same
3698 // type only if their expressions are equivalent (14.5.6.1).
3699 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003700 llvm::FoldingSetNodeID ID;
3701 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003702
Douglas Gregora21f6c32009-07-30 23:36:40 +00003703 void *InsertPos = 0;
3704 DependentDecltypeType *Canon
3705 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3706 if (Canon) {
3707 // We already have a "canonical" version of an equivalent, dependent
3708 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003709 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003710 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003711 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003712 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003713 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003714 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3715 dt = Canon;
3716 }
3717 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003718 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3719 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003720 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003721 Types.push_back(dt);
3722 return QualType(dt, 0);
3723}
3724
Alexis Hunte852b102011-05-24 22:41:36 +00003725/// getUnaryTransformationType - We don't unique these, since the memory
3726/// savings are minimal and these are rare.
3727QualType ASTContext::getUnaryTransformType(QualType BaseType,
3728 QualType UnderlyingType,
3729 UnaryTransformType::UTTKind Kind)
3730 const {
3731 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003732 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3733 Kind,
3734 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003735 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003736 Types.push_back(Ty);
3737 return QualType(Ty, 0);
3738}
3739
Richard Smith2a7d4812013-05-04 07:00:32 +00003740/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3741/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3742/// canonical deduced-but-dependent 'auto' type.
3743QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003744 bool IsDependent) const {
3745 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003746 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003747
Richard Smith2a7d4812013-05-04 07:00:32 +00003748 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003749 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003750 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003751 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003752 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3753 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003754
Richard Smith74aeef52013-04-26 16:15:35 +00003755 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003756 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003757 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003758 Types.push_back(AT);
3759 if (InsertPos)
3760 AutoTypes.InsertNode(AT, InsertPos);
3761 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003762}
3763
Eli Friedman0dfb8892011-10-06 23:00:33 +00003764/// getAtomicType - Return the uniqued reference to the atomic type for
3765/// the given value type.
3766QualType ASTContext::getAtomicType(QualType T) const {
3767 // Unique pointers, to guarantee there is only one pointer of a particular
3768 // structure.
3769 llvm::FoldingSetNodeID ID;
3770 AtomicType::Profile(ID, T);
3771
3772 void *InsertPos = 0;
3773 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3774 return QualType(AT, 0);
3775
3776 // If the atomic value type isn't canonical, this won't be a canonical type
3777 // either, so fill in the canonical type field.
3778 QualType Canonical;
3779 if (!T.isCanonical()) {
3780 Canonical = getAtomicType(getCanonicalType(T));
3781
3782 // Get the new insert position for the node we care about.
3783 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3784 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3785 }
3786 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3787 Types.push_back(New);
3788 AtomicTypes.InsertNode(New, InsertPos);
3789 return QualType(New, 0);
3790}
3791
Richard Smith02e85f32011-04-14 22:09:26 +00003792/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3793QualType ASTContext::getAutoDeductType() const {
3794 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003795 AutoDeductTy = QualType(
3796 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003797 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003798 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003799 return AutoDeductTy;
3800}
3801
3802/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3803QualType ASTContext::getAutoRRefDeductType() const {
3804 if (AutoRRefDeductTy.isNull())
3805 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3806 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3807 return AutoRRefDeductTy;
3808}
3809
Chris Lattnerfb072462007-01-23 05:45:31 +00003810/// getTagDeclType - Return the unique reference to the type for the
3811/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003812QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003813 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003814 // FIXME: What is the design on getTagDeclType when it requires casting
3815 // away const? mutable?
3816 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003817}
3818
Mike Stump11289f42009-09-09 15:08:12 +00003819/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3820/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3821/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003822CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003823 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003824}
Chris Lattnerfb072462007-01-23 05:45:31 +00003825
Hans Wennborg27541db2011-10-27 08:29:09 +00003826/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3827CanQualType ASTContext::getIntMaxType() const {
3828 return getFromTargetType(Target->getIntMaxType());
3829}
3830
3831/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3832CanQualType ASTContext::getUIntMaxType() const {
3833 return getFromTargetType(Target->getUIntMaxType());
3834}
3835
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003836/// getSignedWCharType - Return the type of "signed wchar_t".
3837/// Used when in C++, as a GCC extension.
3838QualType ASTContext::getSignedWCharType() const {
3839 // FIXME: derive from "Target" ?
3840 return WCharTy;
3841}
3842
3843/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3844/// Used when in C++, as a GCC extension.
3845QualType ASTContext::getUnsignedWCharType() const {
3846 // FIXME: derive from "Target" ?
3847 return UnsignedIntTy;
3848}
3849
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003850QualType ASTContext::getIntPtrType() const {
3851 return getFromTargetType(Target->getIntPtrType());
3852}
3853
3854QualType ASTContext::getUIntPtrType() const {
3855 return getCorrespondingUnsignedType(getIntPtrType());
3856}
3857
Hans Wennborg27541db2011-10-27 08:29:09 +00003858/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003859/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3860QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003861 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003862}
3863
Eli Friedman4e91899e2012-11-27 02:58:24 +00003864/// \brief Return the unique type for "pid_t" defined in
3865/// <sys/types.h>. We need this to compute the correct type for vfork().
3866QualType ASTContext::getProcessIDType() const {
3867 return getFromTargetType(Target->getProcessIDType());
3868}
3869
Chris Lattnera21ad802008-04-02 05:18:44 +00003870//===----------------------------------------------------------------------===//
3871// Type Operators
3872//===----------------------------------------------------------------------===//
3873
Jay Foad39c79802011-01-12 09:06:06 +00003874CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003875 // Push qualifiers into arrays, and then discard any remaining
3876 // qualifiers.
3877 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003878 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003879 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003880 QualType Result;
3881 if (isa<ArrayType>(Ty)) {
3882 Result = getArrayDecayedType(QualType(Ty,0));
3883 } else if (isa<FunctionType>(Ty)) {
3884 Result = getPointerType(QualType(Ty, 0));
3885 } else {
3886 Result = QualType(Ty, 0);
3887 }
3888
3889 return CanQualType::CreateUnsafe(Result);
3890}
3891
John McCall6c9dd522011-01-18 07:41:22 +00003892QualType ASTContext::getUnqualifiedArrayType(QualType type,
3893 Qualifiers &quals) {
3894 SplitQualType splitType = type.getSplitUnqualifiedType();
3895
3896 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3897 // the unqualified desugared type and then drops it on the floor.
3898 // We then have to strip that sugar back off with
3899 // getUnqualifiedDesugaredType(), which is silly.
3900 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003901 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003902
3903 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003904 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003905 quals = splitType.Quals;
3906 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003907 }
3908
John McCall6c9dd522011-01-18 07:41:22 +00003909 // Otherwise, recurse on the array's element type.
3910 QualType elementType = AT->getElementType();
3911 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3912
3913 // If that didn't change the element type, AT has no qualifiers, so we
3914 // can just use the results in splitType.
3915 if (elementType == unqualElementType) {
3916 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003917 quals = splitType.Quals;
3918 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003919 }
3920
3921 // Otherwise, add in the qualifiers from the outermost type, then
3922 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003923 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003924
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003925 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003926 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003927 CAT->getSizeModifier(), 0);
3928 }
3929
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003930 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003931 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003932 }
3933
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003934 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003935 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003936 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003937 VAT->getSizeModifier(),
3938 VAT->getIndexTypeCVRQualifiers(),
3939 VAT->getBracketsRange());
3940 }
3941
3942 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003943 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003944 DSAT->getSizeModifier(), 0,
3945 SourceRange());
3946}
3947
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003948/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3949/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3950/// they point to and return true. If T1 and T2 aren't pointer types
3951/// or pointer-to-member types, or if they are not similar at this
3952/// level, returns false and leaves T1 and T2 unchanged. Top-level
3953/// qualifiers on T1 and T2 are ignored. This function will typically
3954/// be called in a loop that successively "unwraps" pointer and
3955/// pointer-to-member types to compare them at each level.
3956bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3957 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3958 *T2PtrType = T2->getAs<PointerType>();
3959 if (T1PtrType && T2PtrType) {
3960 T1 = T1PtrType->getPointeeType();
3961 T2 = T2PtrType->getPointeeType();
3962 return true;
3963 }
3964
3965 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3966 *T2MPType = T2->getAs<MemberPointerType>();
3967 if (T1MPType && T2MPType &&
3968 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3969 QualType(T2MPType->getClass(), 0))) {
3970 T1 = T1MPType->getPointeeType();
3971 T2 = T2MPType->getPointeeType();
3972 return true;
3973 }
3974
David Blaikiebbafb8a2012-03-11 07:00:24 +00003975 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003976 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3977 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3978 if (T1OPType && T2OPType) {
3979 T1 = T1OPType->getPointeeType();
3980 T2 = T2OPType->getPointeeType();
3981 return true;
3982 }
3983 }
3984
3985 // FIXME: Block pointers, too?
3986
3987 return false;
3988}
3989
Jay Foad39c79802011-01-12 09:06:06 +00003990DeclarationNameInfo
3991ASTContext::getNameForTemplate(TemplateName Name,
3992 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003993 switch (Name.getKind()) {
3994 case TemplateName::QualifiedTemplate:
3995 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003996 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003997 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3998 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003999
John McCalld9dfe3a2011-06-30 08:33:18 +00004000 case TemplateName::OverloadedTemplate: {
4001 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4002 // DNInfo work in progress: CHECKME: what about DNLoc?
4003 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4004 }
4005
4006 case TemplateName::DependentTemplate: {
4007 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004008 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004009 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004010 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4011 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004012 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004013 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4014 // DNInfo work in progress: FIXME: source locations?
4015 DeclarationNameLoc DNLoc;
4016 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4017 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4018 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004019 }
4020 }
4021
John McCalld9dfe3a2011-06-30 08:33:18 +00004022 case TemplateName::SubstTemplateTemplateParm: {
4023 SubstTemplateTemplateParmStorage *subst
4024 = Name.getAsSubstTemplateTemplateParm();
4025 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4026 NameLoc);
4027 }
4028
4029 case TemplateName::SubstTemplateTemplateParmPack: {
4030 SubstTemplateTemplateParmPackStorage *subst
4031 = Name.getAsSubstTemplateTemplateParmPack();
4032 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4033 NameLoc);
4034 }
4035 }
4036
4037 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004038}
4039
Jay Foad39c79802011-01-12 09:06:06 +00004040TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004041 switch (Name.getKind()) {
4042 case TemplateName::QualifiedTemplate:
4043 case TemplateName::Template: {
4044 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004045 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004046 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004047 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4048
4049 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004050 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004051 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004052
John McCalld9dfe3a2011-06-30 08:33:18 +00004053 case TemplateName::OverloadedTemplate:
4054 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004055
John McCalld9dfe3a2011-06-30 08:33:18 +00004056 case TemplateName::DependentTemplate: {
4057 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4058 assert(DTN && "Non-dependent template names must refer to template decls.");
4059 return DTN->CanonicalTemplateName;
4060 }
4061
4062 case TemplateName::SubstTemplateTemplateParm: {
4063 SubstTemplateTemplateParmStorage *subst
4064 = Name.getAsSubstTemplateTemplateParm();
4065 return getCanonicalTemplateName(subst->getReplacement());
4066 }
4067
4068 case TemplateName::SubstTemplateTemplateParmPack: {
4069 SubstTemplateTemplateParmPackStorage *subst
4070 = Name.getAsSubstTemplateTemplateParmPack();
4071 TemplateTemplateParmDecl *canonParameter
4072 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4073 TemplateArgument canonArgPack
4074 = getCanonicalTemplateArgument(subst->getArgumentPack());
4075 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4076 }
4077 }
4078
4079 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004080}
4081
Douglas Gregoradee3e32009-11-11 23:06:43 +00004082bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4083 X = getCanonicalTemplateName(X);
4084 Y = getCanonicalTemplateName(Y);
4085 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4086}
4087
Mike Stump11289f42009-09-09 15:08:12 +00004088TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004089ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004090 switch (Arg.getKind()) {
4091 case TemplateArgument::Null:
4092 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004093
Douglas Gregora8e02e72009-07-28 23:00:59 +00004094 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004095 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004096
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004097 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004098 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4099 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004100 }
Mike Stump11289f42009-09-09 15:08:12 +00004101
Eli Friedmanb826a002012-09-26 02:36:12 +00004102 case TemplateArgument::NullPtr:
4103 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4104 /*isNullPtr*/true);
4105
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004106 case TemplateArgument::Template:
4107 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004108
4109 case TemplateArgument::TemplateExpansion:
4110 return TemplateArgument(getCanonicalTemplateName(
4111 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004112 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004113
Douglas Gregora8e02e72009-07-28 23:00:59 +00004114 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004115 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004116
Douglas Gregora8e02e72009-07-28 23:00:59 +00004117 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004118 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004119
Douglas Gregora8e02e72009-07-28 23:00:59 +00004120 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004121 if (Arg.pack_size() == 0)
4122 return Arg;
4123
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004124 TemplateArgument *CanonArgs
4125 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004126 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004127 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004128 AEnd = Arg.pack_end();
4129 A != AEnd; (void)++A, ++Idx)
4130 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004131
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004132 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004133 }
4134 }
4135
4136 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004137 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004138}
4139
Douglas Gregor333489b2009-03-27 23:10:48 +00004140NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004141ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004142 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004143 return 0;
4144
4145 switch (NNS->getKind()) {
4146 case NestedNameSpecifier::Identifier:
4147 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004148 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004149 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4150 NNS->getAsIdentifier());
4151
4152 case NestedNameSpecifier::Namespace:
4153 // A namespace is canonical; build a nested-name-specifier with
4154 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004155 return NestedNameSpecifier::Create(*this, 0,
4156 NNS->getAsNamespace()->getOriginalNamespace());
4157
4158 case NestedNameSpecifier::NamespaceAlias:
4159 // A namespace is canonical; build a nested-name-specifier with
4160 // this namespace and no prefix.
4161 return NestedNameSpecifier::Create(*this, 0,
4162 NNS->getAsNamespaceAlias()->getNamespace()
4163 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004164
4165 case NestedNameSpecifier::TypeSpec:
4166 case NestedNameSpecifier::TypeSpecWithTemplate: {
4167 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004168
4169 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4170 // break it apart into its prefix and identifier, then reconsititute those
4171 // as the canonical nested-name-specifier. This is required to canonicalize
4172 // a dependent nested-name-specifier involving typedefs of dependent-name
4173 // types, e.g.,
4174 // typedef typename T::type T1;
4175 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004176 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4177 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004178 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004179
Eli Friedman5358a0a2012-03-03 04:09:56 +00004180 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4181 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4182 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004183 return NestedNameSpecifier::Create(*this, 0, false,
4184 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004185 }
4186
4187 case NestedNameSpecifier::Global:
4188 // The global specifier is canonical and unique.
4189 return NNS;
4190 }
4191
David Blaikie8a40f702012-01-17 06:56:22 +00004192 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004193}
4194
Chris Lattner7adf0762008-08-04 07:31:14 +00004195
Jay Foad39c79802011-01-12 09:06:06 +00004196const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004197 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004198 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004199 // Handle the common positive case fast.
4200 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4201 return AT;
4202 }
Mike Stump11289f42009-09-09 15:08:12 +00004203
John McCall8ccfcb52009-09-24 19:53:00 +00004204 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004205 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004206 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004207
John McCall8ccfcb52009-09-24 19:53:00 +00004208 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004209 // implements C99 6.7.3p8: "If the specification of an array type includes
4210 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004211
Chris Lattner7adf0762008-08-04 07:31:14 +00004212 // If we get here, we either have type qualifiers on the type, or we have
4213 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004214 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004215
John McCall33ddac02011-01-19 10:06:00 +00004216 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004217 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004218
Chris Lattner7adf0762008-08-04 07:31:14 +00004219 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004220 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004221 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004222 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004223
Chris Lattner7adf0762008-08-04 07:31:14 +00004224 // Otherwise, we have an array and we have qualifiers on it. Push the
4225 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004226 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004227
Chris Lattner7adf0762008-08-04 07:31:14 +00004228 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4229 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4230 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004231 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004232 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4233 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4234 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004235 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004236
Mike Stump11289f42009-09-09 15:08:12 +00004237 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004238 = dyn_cast<DependentSizedArrayType>(ATy))
4239 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004240 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004241 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004242 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004243 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004244 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004245
Chris Lattner7adf0762008-08-04 07:31:14 +00004246 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004247 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004248 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004249 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004250 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004251 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004252}
4253
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004254QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004255 if (T->isArrayType() || T->isFunctionType())
4256 return getDecayedType(T);
4257 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004258}
4259
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004260QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004261 T = getVariableArrayDecayedType(T);
4262 T = getAdjustedParameterType(T);
4263 return T.getUnqualifiedType();
4264}
4265
Chris Lattnera21ad802008-04-02 05:18:44 +00004266/// getArrayDecayedType - Return the properly qualified result of decaying the
4267/// specified array type to a pointer. This operation is non-trivial when
4268/// handling typedefs etc. The canonical type of "T" must be an array type,
4269/// this returns a pointer to a properly qualified element of the array.
4270///
4271/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004272QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004273 // Get the element type with 'getAsArrayType' so that we don't lose any
4274 // typedefs in the element type of the array. This also handles propagation
4275 // of type qualifiers from the array type into the element type if present
4276 // (C99 6.7.3p8).
4277 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4278 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004279
Chris Lattner7adf0762008-08-04 07:31:14 +00004280 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004281
4282 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004283 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004284}
4285
John McCall33ddac02011-01-19 10:06:00 +00004286QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4287 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004288}
4289
John McCall33ddac02011-01-19 10:06:00 +00004290QualType ASTContext::getBaseElementType(QualType type) const {
4291 Qualifiers qs;
4292 while (true) {
4293 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004294 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004295 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004296
John McCall33ddac02011-01-19 10:06:00 +00004297 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004298 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004299 }
Mike Stump11289f42009-09-09 15:08:12 +00004300
John McCall33ddac02011-01-19 10:06:00 +00004301 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004302}
4303
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004304/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004305uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004306ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4307 uint64_t ElementCount = 1;
4308 do {
4309 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004310 CA = dyn_cast_or_null<ConstantArrayType>(
4311 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004312 } while (CA);
4313 return ElementCount;
4314}
4315
Steve Naroff0af91202007-04-27 21:51:21 +00004316/// getFloatingRank - Return a relative rank for floating point types.
4317/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004318static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004319 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004320 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004321
John McCall9dd450b2009-09-21 23:43:11 +00004322 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4323 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004324 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004325 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004326 case BuiltinType::Float: return FloatRank;
4327 case BuiltinType::Double: return DoubleRank;
4328 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004329 }
4330}
4331
Mike Stump11289f42009-09-09 15:08:12 +00004332/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4333/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004334/// 'typeDomain' is a real floating point or complex type.
4335/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004336QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4337 QualType Domain) const {
4338 FloatingRank EltRank = getFloatingRank(Size);
4339 if (Domain->isComplexType()) {
4340 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004341 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004342 case FloatRank: return FloatComplexTy;
4343 case DoubleRank: return DoubleComplexTy;
4344 case LongDoubleRank: return LongDoubleComplexTy;
4345 }
Steve Naroff0af91202007-04-27 21:51:21 +00004346 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004347
4348 assert(Domain->isRealFloatingType() && "Unknown domain!");
4349 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004350 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004351 case FloatRank: return FloatTy;
4352 case DoubleRank: return DoubleTy;
4353 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004354 }
David Blaikief47fa302012-01-17 02:30:50 +00004355 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004356}
4357
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004358/// getFloatingTypeOrder - Compare the rank of the two specified floating
4359/// point types, ignoring the domain of the type (i.e. 'double' ==
4360/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004361/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004362int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004363 FloatingRank LHSR = getFloatingRank(LHS);
4364 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004365
Chris Lattnerb90739d2008-04-06 23:38:49 +00004366 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004367 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004368 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004369 return 1;
4370 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004371}
4372
Chris Lattner76a00cf2008-04-06 22:59:24 +00004373/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4374/// routine will assert if passed a built-in type that isn't an integer or enum,
4375/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004376unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004377 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004378
Chris Lattner76a00cf2008-04-06 22:59:24 +00004379 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004380 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004381 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004382 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004383 case BuiltinType::Char_S:
4384 case BuiltinType::Char_U:
4385 case BuiltinType::SChar:
4386 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004387 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004388 case BuiltinType::Short:
4389 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004390 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004391 case BuiltinType::Int:
4392 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004393 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004394 case BuiltinType::Long:
4395 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004396 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004397 case BuiltinType::LongLong:
4398 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004399 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004400 case BuiltinType::Int128:
4401 case BuiltinType::UInt128:
4402 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004403 }
4404}
4405
Eli Friedman629ffb92009-08-20 04:21:42 +00004406/// \brief Whether this is a promotable bitfield reference according
4407/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4408///
4409/// \returns the type this bit-field will promote to, or NULL if no
4410/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004411QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004412 if (E->isTypeDependent() || E->isValueDependent())
4413 return QualType();
4414
John McCalld25db7e2013-05-06 21:39:12 +00004415 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004416 if (!Field)
4417 return QualType();
4418
4419 QualType FT = Field->getType();
4420
Richard Smithcaf33902011-10-10 18:28:20 +00004421 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004422 uint64_t IntSize = getTypeSize(IntTy);
4423 // GCC extension compatibility: if the bit-field size is less than or equal
4424 // to the size of int, it gets promoted no matter what its type is.
4425 // For instance, unsigned long bf : 4 gets promoted to signed int.
4426 if (BitWidth < IntSize)
4427 return IntTy;
4428
4429 if (BitWidth == IntSize)
4430 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4431
4432 // Types bigger than int are not subject to promotions, and therefore act
4433 // like the base type.
4434 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4435 // is ridiculous.
4436 return QualType();
4437}
4438
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004439/// getPromotedIntegerType - Returns the type that Promotable will
4440/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4441/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004442QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004443 assert(!Promotable.isNull());
4444 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004445 if (const EnumType *ET = Promotable->getAs<EnumType>())
4446 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004447
4448 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4449 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4450 // (3.9.1) can be converted to a prvalue of the first of the following
4451 // types that can represent all the values of its underlying type:
4452 // int, unsigned int, long int, unsigned long int, long long int, or
4453 // unsigned long long int [...]
4454 // FIXME: Is there some better way to compute this?
4455 if (BT->getKind() == BuiltinType::WChar_S ||
4456 BT->getKind() == BuiltinType::WChar_U ||
4457 BT->getKind() == BuiltinType::Char16 ||
4458 BT->getKind() == BuiltinType::Char32) {
4459 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4460 uint64_t FromSize = getTypeSize(BT);
4461 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4462 LongLongTy, UnsignedLongLongTy };
4463 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4464 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4465 if (FromSize < ToSize ||
4466 (FromSize == ToSize &&
4467 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4468 return PromoteTypes[Idx];
4469 }
4470 llvm_unreachable("char type should fit into long long");
4471 }
4472 }
4473
4474 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004475 if (Promotable->isSignedIntegerType())
4476 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004477 uint64_t PromotableSize = getIntWidth(Promotable);
4478 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004479 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4480 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4481}
4482
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004483/// \brief Recurses in pointer/array types until it finds an objc retainable
4484/// type and returns its ownership.
4485Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4486 while (!T.isNull()) {
4487 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4488 return T.getObjCLifetime();
4489 if (T->isArrayType())
4490 T = getBaseElementType(T);
4491 else if (const PointerType *PT = T->getAs<PointerType>())
4492 T = PT->getPointeeType();
4493 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004494 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004495 else
4496 break;
4497 }
4498
4499 return Qualifiers::OCL_None;
4500}
4501
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004502static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4503 // Incomplete enum types are not treated as integer types.
4504 // FIXME: In C++, enum types are never integer types.
4505 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4506 return ET->getDecl()->getIntegerType().getTypePtr();
4507 return NULL;
4508}
4509
Mike Stump11289f42009-09-09 15:08:12 +00004510/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004511/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004512/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004513int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004514 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4515 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004516
4517 // Unwrap enums to their underlying type.
4518 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4519 LHSC = getIntegerTypeForEnum(ET);
4520 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4521 RHSC = getIntegerTypeForEnum(ET);
4522
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004523 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004524
Chris Lattner76a00cf2008-04-06 22:59:24 +00004525 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4526 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004527
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004528 unsigned LHSRank = getIntegerRank(LHSC);
4529 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004530
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004531 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4532 if (LHSRank == RHSRank) return 0;
4533 return LHSRank > RHSRank ? 1 : -1;
4534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004536 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4537 if (LHSUnsigned) {
4538 // If the unsigned [LHS] type is larger, return it.
4539 if (LHSRank >= RHSRank)
4540 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004541
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004542 // If the signed type can represent all values of the unsigned type, it
4543 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004544 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004545 return -1;
4546 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004547
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004548 // If the unsigned [RHS] type is larger, return it.
4549 if (RHSRank >= LHSRank)
4550 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004551
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004552 // If the signed type can represent all values of the unsigned type, it
4553 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004554 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004555 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004556}
Anders Carlsson98f07902007-08-17 05:31:46 +00004557
Mike Stump11289f42009-09-09 15:08:12 +00004558// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004559QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004560 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004561 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004562 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004563
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004564 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004565
Anders Carlsson98f07902007-08-17 05:31:46 +00004566 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004567 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004568 // int flags;
4569 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004570 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004571 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004572 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004573 FieldTypes[3] = LongTy;
4574
Anders Carlsson98f07902007-08-17 05:31:46 +00004575 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004576 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004577 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004578 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004579 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004580 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004581 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004582 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004583 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004584 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004585 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004586 }
4587
Douglas Gregord5058122010-02-11 01:19:42 +00004588 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004589 }
Mike Stump11289f42009-09-09 15:08:12 +00004590
Anders Carlsson98f07902007-08-17 05:31:46 +00004591 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004592}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004593
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004594QualType ASTContext::getObjCSuperType() const {
4595 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004596 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004597 TUDecl->addDecl(ObjCSuperTypeDecl);
4598 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4599 }
4600 return ObjCSuperType;
4601}
4602
Douglas Gregor512b0772009-04-23 22:29:11 +00004603void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004604 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004605 assert(Rec && "Invalid CFConstantStringType");
4606 CFConstantStringTypeDecl = Rec->getDecl();
4607}
4608
Jay Foad39c79802011-01-12 09:06:06 +00004609QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004610 if (BlockDescriptorType)
4611 return getTagDeclType(BlockDescriptorType);
4612
Alp Toker2dea15b2013-12-17 01:22:38 +00004613 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004614 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004615 RD = buildImplicitRecord("__block_descriptor");
4616 RD->startDefinition();
4617
Mike Stumpd0153282009-10-20 02:12:22 +00004618 QualType FieldTypes[] = {
4619 UnsignedLongTy,
4620 UnsignedLongTy,
4621 };
4622
Craig Topperd6d31ac2013-07-15 08:24:27 +00004623 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004624 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004625 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004626 };
4627
4628 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004629 FieldDecl *Field = FieldDecl::Create(
4630 *this, RD, SourceLocation(), SourceLocation(),
4631 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4632 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004633 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004634 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004635 }
4636
Alp Toker2dea15b2013-12-17 01:22:38 +00004637 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004638
Alp Toker2dea15b2013-12-17 01:22:38 +00004639 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004640
4641 return getTagDeclType(BlockDescriptorType);
4642}
4643
Jay Foad39c79802011-01-12 09:06:06 +00004644QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004645 if (BlockDescriptorExtendedType)
4646 return getTagDeclType(BlockDescriptorExtendedType);
4647
Alp Toker2dea15b2013-12-17 01:22:38 +00004648 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004649 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004650 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4651 RD->startDefinition();
4652
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004653 QualType FieldTypes[] = {
4654 UnsignedLongTy,
4655 UnsignedLongTy,
4656 getPointerType(VoidPtrTy),
4657 getPointerType(VoidPtrTy)
4658 };
4659
Craig Topperd6d31ac2013-07-15 08:24:27 +00004660 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004661 "reserved",
4662 "Size",
4663 "CopyFuncPtr",
4664 "DestroyFuncPtr"
4665 };
4666
4667 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004668 FieldDecl *Field = FieldDecl::Create(
4669 *this, RD, SourceLocation(), SourceLocation(),
4670 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4671 /*BitWidth=*/0,
4672 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004673 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004674 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004675 }
4676
Alp Toker2dea15b2013-12-17 01:22:38 +00004677 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004678
Alp Toker2dea15b2013-12-17 01:22:38 +00004679 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004680 return getTagDeclType(BlockDescriptorExtendedType);
4681}
4682
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004683/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4684/// requires copy/dispose. Note that this must match the logic
4685/// in buildByrefHelpers.
4686bool ASTContext::BlockRequiresCopying(QualType Ty,
4687 const VarDecl *D) {
4688 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4689 const Expr *copyExpr = getBlockVarCopyInits(D);
4690 if (!copyExpr && record->hasTrivialDestructor()) return false;
4691
Mike Stump94967902009-10-21 18:16:27 +00004692 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004693 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004694
4695 if (!Ty->isObjCRetainableType()) return false;
4696
4697 Qualifiers qs = Ty.getQualifiers();
4698
4699 // If we have lifetime, that dominates.
4700 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4701 assert(getLangOpts().ObjCAutoRefCount);
4702
4703 switch (lifetime) {
4704 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4705
4706 // These are just bits as far as the runtime is concerned.
4707 case Qualifiers::OCL_ExplicitNone:
4708 case Qualifiers::OCL_Autoreleasing:
4709 return false;
4710
4711 // Tell the runtime that this is ARC __weak, called by the
4712 // byref routines.
4713 case Qualifiers::OCL_Weak:
4714 // ARC __strong __block variables need to be retained.
4715 case Qualifiers::OCL_Strong:
4716 return true;
4717 }
4718 llvm_unreachable("fell out of lifetime switch!");
4719 }
4720 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4721 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004722}
4723
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004724bool ASTContext::getByrefLifetime(QualType Ty,
4725 Qualifiers::ObjCLifetime &LifeTime,
4726 bool &HasByrefExtendedLayout) const {
4727
4728 if (!getLangOpts().ObjC1 ||
4729 getLangOpts().getGC() != LangOptions::NonGC)
4730 return false;
4731
4732 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004733 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004734 HasByrefExtendedLayout = true;
4735 LifeTime = Qualifiers::OCL_None;
4736 }
4737 else if (getLangOpts().ObjCAutoRefCount)
4738 LifeTime = Ty.getObjCLifetime();
4739 // MRR.
4740 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4741 LifeTime = Qualifiers::OCL_ExplicitNone;
4742 else
4743 LifeTime = Qualifiers::OCL_None;
4744 return true;
4745}
4746
Douglas Gregorbab8a962011-09-08 01:46:34 +00004747TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4748 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004749 ObjCInstanceTypeDecl =
4750 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004751 return ObjCInstanceTypeDecl;
4752}
4753
Anders Carlsson18acd442007-10-29 06:33:42 +00004754// This returns true if a type has been typedefed to BOOL:
4755// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004756static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004757 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004758 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4759 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004760
Anders Carlssond8499822007-10-29 05:01:08 +00004761 return false;
4762}
4763
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004764/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004765/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004766CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004767 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4768 return CharUnits::Zero();
4769
Ken Dyck40775002010-01-11 17:06:35 +00004770 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004771
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004772 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004773 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004774 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004775 // Treat arrays as pointers, since that's how they're passed in.
4776 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004777 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004778 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004779}
4780
4781static inline
4782std::string charUnitsToString(const CharUnits &CU) {
4783 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004784}
4785
John McCall351762c2011-02-07 10:33:21 +00004786/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004787/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004788std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4789 std::string S;
4790
David Chisnall950a9512009-11-17 19:33:30 +00004791 const BlockDecl *Decl = Expr->getBlockDecl();
4792 QualType BlockTy =
4793 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4794 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004795 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004796 getObjCEncodingForMethodParameter(
4797 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4798 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004799 else
Alp Toker314cc812014-01-25 16:55:45 +00004800 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004801 // Compute size of all parameters.
4802 // Start with computing size of a pointer in number of bytes.
4803 // FIXME: There might(should) be a better way of doing this computation!
4804 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004805 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4806 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004807 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004808 E = Decl->param_end(); PI != E; ++PI) {
4809 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004810 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004811 if (sz.isZero())
4812 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004813 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004814 ParmOffset += sz;
4815 }
4816 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004817 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004818 // Block pointer and offset.
4819 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004820
4821 // Argument types.
4822 ParmOffset = PtrSize;
4823 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4824 Decl->param_end(); PI != E; ++PI) {
4825 ParmVarDecl *PVDecl = *PI;
4826 QualType PType = PVDecl->getOriginalType();
4827 if (const ArrayType *AT =
4828 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4829 // Use array's original type only if it has known number of
4830 // elements.
4831 if (!isa<ConstantArrayType>(AT))
4832 PType = PVDecl->getType();
4833 } else if (PType->isFunctionType())
4834 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004835 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004836 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4837 S, true /*Extended*/);
4838 else
4839 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004840 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004841 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004842 }
John McCall351762c2011-02-07 10:33:21 +00004843
4844 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004845}
4846
Douglas Gregora9d84932011-05-27 01:19:52 +00004847bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004848 std::string& S) {
4849 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004850 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004851 CharUnits ParmOffset;
4852 // Compute size of all parameters.
4853 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4854 E = Decl->param_end(); PI != E; ++PI) {
4855 QualType PType = (*PI)->getType();
4856 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004857 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004858 continue;
4859
David Chisnall50e4eba2010-12-30 14:05:53 +00004860 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004861 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004862 ParmOffset += sz;
4863 }
4864 S += charUnitsToString(ParmOffset);
4865 ParmOffset = CharUnits::Zero();
4866
4867 // Argument types.
4868 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4869 E = Decl->param_end(); PI != E; ++PI) {
4870 ParmVarDecl *PVDecl = *PI;
4871 QualType PType = PVDecl->getOriginalType();
4872 if (const ArrayType *AT =
4873 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4874 // Use array's original type only if it has known number of
4875 // elements.
4876 if (!isa<ConstantArrayType>(AT))
4877 PType = PVDecl->getType();
4878 } else if (PType->isFunctionType())
4879 PType = PVDecl->getType();
4880 getObjCEncodingForType(PType, S);
4881 S += charUnitsToString(ParmOffset);
4882 ParmOffset += getObjCEncodingTypeSize(PType);
4883 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004884
4885 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004886}
4887
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004888/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4889/// method parameter or return type. If Extended, include class names and
4890/// block object types.
4891void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4892 QualType T, std::string& S,
4893 bool Extended) const {
4894 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4895 getObjCEncodingForTypeQualifier(QT, S);
4896 // Encode parameter type.
4897 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4898 true /*OutermostType*/,
4899 false /*EncodingProperty*/,
4900 false /*StructField*/,
4901 Extended /*EncodeBlockParameters*/,
4902 Extended /*EncodeClassNames*/);
4903}
4904
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004905/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004906/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004907bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004908 std::string& S,
4909 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004910 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004911 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004912 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4913 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004914 // Compute size of all parameters.
4915 // Start with computing size of a pointer in number of bytes.
4916 // FIXME: There might(should) be a better way of doing this computation!
4917 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004918 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004919 // The first two arguments (self and _cmd) are pointers; account for
4920 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004921 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004922 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004923 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004924 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004925 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004926 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004927 continue;
4928
Ken Dyck40775002010-01-11 17:06:35 +00004929 assert (sz.isPositive() &&
4930 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004931 ParmOffset += sz;
4932 }
Ken Dyck40775002010-01-11 17:06:35 +00004933 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004934 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004935 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004936
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004937 // Argument types.
4938 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004939 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004940 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004941 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004942 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004943 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004944 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4945 // Use array's original type only if it has known number of
4946 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004947 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004948 PType = PVDecl->getType();
4949 } else if (PType->isFunctionType())
4950 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004951 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4952 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004953 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004954 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004955 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004956
4957 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004958}
4959
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004960ObjCPropertyImplDecl *
4961ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4962 const ObjCPropertyDecl *PD,
4963 const Decl *Container) const {
4964 if (!Container)
4965 return 0;
4966 if (const ObjCCategoryImplDecl *CID =
4967 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4968 for (ObjCCategoryImplDecl::propimpl_iterator
4969 i = CID->propimpl_begin(), e = CID->propimpl_end();
4970 i != e; ++i) {
4971 ObjCPropertyImplDecl *PID = *i;
4972 if (PID->getPropertyDecl() == PD)
4973 return PID;
4974 }
4975 } else {
4976 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4977 for (ObjCCategoryImplDecl::propimpl_iterator
4978 i = OID->propimpl_begin(), e = OID->propimpl_end();
4979 i != e; ++i) {
4980 ObjCPropertyImplDecl *PID = *i;
4981 if (PID->getPropertyDecl() == PD)
4982 return PID;
4983 }
4984 }
4985 return 0;
4986}
4987
Daniel Dunbar4932b362008-08-28 04:38:10 +00004988/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004989/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004990/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4991/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004992/// Property attributes are stored as a comma-delimited C string. The simple
4993/// attributes readonly and bycopy are encoded as single characters. The
4994/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4995/// encoded as single characters, followed by an identifier. Property types
4996/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004997/// these attributes are defined by the following enumeration:
4998/// @code
4999/// enum PropertyAttributes {
5000/// kPropertyReadOnly = 'R', // property is read-only.
5001/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5002/// kPropertyByref = '&', // property is a reference to the value last assigned
5003/// kPropertyDynamic = 'D', // property is dynamic
5004/// kPropertyGetter = 'G', // followed by getter selector name
5005/// kPropertySetter = 'S', // followed by setter selector name
5006/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005007/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005008/// kPropertyWeak = 'W' // 'weak' property
5009/// kPropertyStrong = 'P' // property GC'able
5010/// kPropertyNonAtomic = 'N' // property non-atomic
5011/// };
5012/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005013void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005014 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005015 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005016 // Collect information from the property implementation decl(s).
5017 bool Dynamic = false;
5018 ObjCPropertyImplDecl *SynthesizePID = 0;
5019
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005020 if (ObjCPropertyImplDecl *PropertyImpDecl =
5021 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5022 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5023 Dynamic = true;
5024 else
5025 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005026 }
5027
5028 // FIXME: This is not very efficient.
5029 S = "T";
5030
5031 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005032 // GCC has some special rules regarding encoding of properties which
5033 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005034 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005035 true /* outermost type */,
5036 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005037
5038 if (PD->isReadOnly()) {
5039 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005040 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5041 S += ",C";
5042 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5043 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005044 } else {
5045 switch (PD->getSetterKind()) {
5046 case ObjCPropertyDecl::Assign: break;
5047 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005048 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005049 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005050 }
5051 }
5052
5053 // It really isn't clear at all what this means, since properties
5054 // are "dynamic by default".
5055 if (Dynamic)
5056 S += ",D";
5057
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005058 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5059 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005060
Daniel Dunbar4932b362008-08-28 04:38:10 +00005061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5062 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005063 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005064 }
5065
5066 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5067 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005068 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005069 }
5070
5071 if (SynthesizePID) {
5072 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5073 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005074 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005075 }
5076
5077 // FIXME: OBJCGC: weak & strong
5078}
5079
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005080/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005081/// Another legacy compatibility encoding: 32-bit longs are encoded as
5082/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005083/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5084///
5085void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005086 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005087 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005088 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005089 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005090 else
Jay Foad39c79802011-01-12 09:06:06 +00005091 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005092 PointeeTy = IntTy;
5093 }
5094 }
5095}
5096
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005097void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005098 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005099 // We follow the behavior of gcc, expanding structures which are
5100 // directly pointed to, and expanding embedded structures. Note that
5101 // these rules are sufficient to prevent recursive encoding of the
5102 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005103 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005104 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005105}
5106
John McCall393a78d2012-12-20 02:45:14 +00005107static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5108 BuiltinType::Kind kind) {
5109 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005110 case BuiltinType::Void: return 'v';
5111 case BuiltinType::Bool: return 'B';
5112 case BuiltinType::Char_U:
5113 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005114 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005115 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005116 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005117 case BuiltinType::UInt: return 'I';
5118 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005119 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005120 case BuiltinType::UInt128: return 'T';
5121 case BuiltinType::ULongLong: return 'Q';
5122 case BuiltinType::Char_S:
5123 case BuiltinType::SChar: return 'c';
5124 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005125 case BuiltinType::WChar_S:
5126 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005127 case BuiltinType::Int: return 'i';
5128 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005129 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005130 case BuiltinType::LongLong: return 'q';
5131 case BuiltinType::Int128: return 't';
5132 case BuiltinType::Float: return 'f';
5133 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005134 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005135 case BuiltinType::NullPtr: return '*'; // like char*
5136
5137 case BuiltinType::Half:
5138 // FIXME: potentially need @encodes for these!
5139 return ' ';
5140
5141 case BuiltinType::ObjCId:
5142 case BuiltinType::ObjCClass:
5143 case BuiltinType::ObjCSel:
5144 llvm_unreachable("@encoding ObjC primitive type");
5145
5146 // OpenCL and placeholder types don't need @encodings.
5147 case BuiltinType::OCLImage1d:
5148 case BuiltinType::OCLImage1dArray:
5149 case BuiltinType::OCLImage1dBuffer:
5150 case BuiltinType::OCLImage2d:
5151 case BuiltinType::OCLImage2dArray:
5152 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005153 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005154 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005155 case BuiltinType::Dependent:
5156#define BUILTIN_TYPE(KIND, ID)
5157#define PLACEHOLDER_TYPE(KIND, ID) \
5158 case BuiltinType::KIND:
5159#include "clang/AST/BuiltinTypes.def"
5160 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005161 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005162 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005163}
5164
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005165static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5166 EnumDecl *Enum = ET->getDecl();
5167
5168 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5169 if (!Enum->isFixed())
5170 return 'i';
5171
5172 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005173 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5174 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005175}
5176
Jay Foad39c79802011-01-12 09:06:06 +00005177static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005178 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005179 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005180 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005181 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5182 // The GNU runtime requires more information; bitfields are encoded as b,
5183 // then the offset (in bits) of the first element, then the type of the
5184 // bitfield, then the size in bits. For example, in this structure:
5185 //
5186 // struct
5187 // {
5188 // int integer;
5189 // int flags:2;
5190 // };
5191 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5192 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5193 // information is not especially sensible, but we're stuck with it for
5194 // compatibility with GCC, although providing it breaks anything that
5195 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005196 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005197 const RecordDecl *RD = FD->getParent();
5198 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005199 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005200 if (const EnumType *ET = T->getAs<EnumType>())
5201 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005202 else {
5203 const BuiltinType *BT = T->castAs<BuiltinType>();
5204 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5205 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005206 }
Richard Smithcaf33902011-10-10 18:28:20 +00005207 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005208}
5209
Daniel Dunbar07d07852009-10-18 21:17:35 +00005210// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005211void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5212 bool ExpandPointedToStructures,
5213 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005214 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005215 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005216 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005217 bool StructField,
5218 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005219 bool EncodeClassNames,
5220 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005221 CanQualType CT = getCanonicalType(T);
5222 switch (CT->getTypeClass()) {
5223 case Type::Builtin:
5224 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005225 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005226 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005227 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5228 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5229 else
5230 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005231 return;
Mike Stump11289f42009-09-09 15:08:12 +00005232
John McCall393a78d2012-12-20 02:45:14 +00005233 case Type::Complex: {
5234 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005235 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005236 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005237 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005238 return;
5239 }
John McCall393a78d2012-12-20 02:45:14 +00005240
5241 case Type::Atomic: {
5242 const AtomicType *AT = T->castAs<AtomicType>();
5243 S += 'A';
5244 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5245 false, false);
5246 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005247 }
John McCall393a78d2012-12-20 02:45:14 +00005248
5249 // encoding for pointer or reference types.
5250 case Type::Pointer:
5251 case Type::LValueReference:
5252 case Type::RValueReference: {
5253 QualType PointeeTy;
5254 if (isa<PointerType>(CT)) {
5255 const PointerType *PT = T->castAs<PointerType>();
5256 if (PT->isObjCSelType()) {
5257 S += ':';
5258 return;
5259 }
5260 PointeeTy = PT->getPointeeType();
5261 } else {
5262 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5263 }
5264
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005265 bool isReadOnly = false;
5266 // For historical/compatibility reasons, the read-only qualifier of the
5267 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5268 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005269 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005270 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005271 if (OutermostType && T.isConstQualified()) {
5272 isReadOnly = true;
5273 S += 'r';
5274 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005275 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005276 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005277 while (P->getAs<PointerType>())
5278 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005279 if (P.isConstQualified()) {
5280 isReadOnly = true;
5281 S += 'r';
5282 }
5283 }
5284 if (isReadOnly) {
5285 // Another legacy compatibility encoding. Some ObjC qualifier and type
5286 // combinations need to be rearranged.
5287 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005288 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005289 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005290 }
Mike Stump11289f42009-09-09 15:08:12 +00005291
Anders Carlssond8499822007-10-29 05:01:08 +00005292 if (PointeeTy->isCharType()) {
5293 // char pointer types should be encoded as '*' unless it is a
5294 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005295 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005296 S += '*';
5297 return;
5298 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005299 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005300 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5301 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5302 S += '#';
5303 return;
5304 }
5305 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5306 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5307 S += '@';
5308 return;
5309 }
5310 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005311 }
Anders Carlssond8499822007-10-29 05:01:08 +00005312 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005313 getLegacyIntegralTypeEncoding(PointeeTy);
5314
Mike Stump11289f42009-09-09 15:08:12 +00005315 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005316 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005317 return;
5318 }
John McCall393a78d2012-12-20 02:45:14 +00005319
5320 case Type::ConstantArray:
5321 case Type::IncompleteArray:
5322 case Type::VariableArray: {
5323 const ArrayType *AT = cast<ArrayType>(CT);
5324
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005325 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005326 // Incomplete arrays are encoded as a pointer to the array element.
5327 S += '^';
5328
Mike Stump11289f42009-09-09 15:08:12 +00005329 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005330 false, ExpandStructures, FD);
5331 } else {
5332 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005333
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005334 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5335 S += llvm::utostr(CAT->getSize().getZExtValue());
5336 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005337 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005338 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5339 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005340 S += '0';
5341 }
Mike Stump11289f42009-09-09 15:08:12 +00005342
5343 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005344 false, ExpandStructures, FD);
5345 S += ']';
5346 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005347 return;
5348 }
Mike Stump11289f42009-09-09 15:08:12 +00005349
John McCall393a78d2012-12-20 02:45:14 +00005350 case Type::FunctionNoProto:
5351 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005352 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005353 return;
Mike Stump11289f42009-09-09 15:08:12 +00005354
John McCall393a78d2012-12-20 02:45:14 +00005355 case Type::Record: {
5356 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005357 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005358 // Anonymous structures print as '?'
5359 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5360 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005361 if (ClassTemplateSpecializationDecl *Spec
5362 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5363 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005364 llvm::raw_string_ostream OS(S);
5365 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005366 TemplateArgs.data(),
5367 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005368 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005369 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005370 } else {
5371 S += '?';
5372 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005373 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005374 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005375 if (!RDecl->isUnion()) {
5376 getObjCEncodingForStructureImpl(RDecl, S, FD);
5377 } else {
5378 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5379 FieldEnd = RDecl->field_end();
5380 Field != FieldEnd; ++Field) {
5381 if (FD) {
5382 S += '"';
5383 S += Field->getNameAsString();
5384 S += '"';
5385 }
Mike Stump11289f42009-09-09 15:08:12 +00005386
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005387 // Special case bit-fields.
5388 if (Field->isBitField()) {
5389 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005390 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005391 } else {
5392 QualType qt = Field->getType();
5393 getLegacyIntegralTypeEncoding(qt);
5394 getObjCEncodingForTypeImpl(qt, S, false, true,
5395 FD, /*OutermostType*/false,
5396 /*EncodingProperty*/false,
5397 /*StructField*/true);
5398 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005399 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005400 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005401 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005402 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005403 return;
5404 }
Mike Stump11289f42009-09-09 15:08:12 +00005405
John McCall393a78d2012-12-20 02:45:14 +00005406 case Type::BlockPointer: {
5407 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005408 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005409 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005410 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005411
5412 S += '<';
5413 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005414 getObjCEncodingForTypeImpl(
5415 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5416 FD, false /* OutermostType */, EncodingProperty,
5417 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005418 // Block self
5419 S += "@?";
5420 // Block parameters
5421 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005422 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5423 E = FPT->param_type_end();
5424 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005425 getObjCEncodingForTypeImpl(*I, S,
5426 ExpandPointedToStructures,
5427 ExpandStructures,
5428 FD,
5429 false /* OutermostType */,
5430 EncodingProperty,
5431 false /* StructField */,
5432 EncodeBlockParameters,
5433 EncodeClassNames);
5434 }
5435 }
5436 S += '>';
5437 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005438 return;
5439 }
Mike Stump11289f42009-09-09 15:08:12 +00005440
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005441 case Type::ObjCObject: {
5442 // hack to match legacy encoding of *id and *Class
5443 QualType Ty = getObjCObjectPointerType(CT);
5444 if (Ty->isObjCIdType()) {
5445 S += "{objc_object=}";
5446 return;
5447 }
5448 else if (Ty->isObjCClassType()) {
5449 S += "{objc_class=}";
5450 return;
5451 }
5452 }
5453
John McCall393a78d2012-12-20 02:45:14 +00005454 case Type::ObjCInterface: {
5455 // Ignore protocol qualifiers when mangling at this level.
5456 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005457
John McCall393a78d2012-12-20 02:45:14 +00005458 // The assumption seems to be that this assert will succeed
5459 // because nested levels will have filtered out 'id' and 'Class'.
5460 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005461 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005462 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005463 S += '{';
5464 const IdentifierInfo *II = OI->getIdentifier();
5465 S += II->getName();
5466 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005467 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005468 DeepCollectObjCIvars(OI, true, Ivars);
5469 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005470 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005471 if (Field->isBitField())
5472 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005473 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005474 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5475 false, false, false, false, false,
5476 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005477 }
5478 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005479 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005480 }
Mike Stump11289f42009-09-09 15:08:12 +00005481
John McCall393a78d2012-12-20 02:45:14 +00005482 case Type::ObjCObjectPointer: {
5483 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005484 if (OPT->isObjCIdType()) {
5485 S += '@';
5486 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005487 }
Mike Stump11289f42009-09-09 15:08:12 +00005488
Steve Narofff0c86112009-10-28 22:03:49 +00005489 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5490 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5491 // Since this is a binary compatibility issue, need to consult with runtime
5492 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005493 S += '#';
5494 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005495 }
Mike Stump11289f42009-09-09 15:08:12 +00005496
Chris Lattnere7cabb92009-07-13 00:10:46 +00005497 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005498 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005499 ExpandPointedToStructures,
5500 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005501 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005502 // Note that we do extended encoding of protocol qualifer list
5503 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005504 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005505 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5506 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005507 S += '<';
5508 S += (*I)->getNameAsString();
5509 S += '>';
5510 }
5511 S += '"';
5512 }
5513 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005514 }
Mike Stump11289f42009-09-09 15:08:12 +00005515
Chris Lattnere7cabb92009-07-13 00:10:46 +00005516 QualType PointeeTy = OPT->getPointeeType();
5517 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005518 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5519 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005520 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005521 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005522 // {...};
5523 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005524 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005525 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005526 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5527 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5528 DeepCollectObjCIvars(OI, true, Ivars);
5529 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5530 if (cast<FieldDecl>(Ivars[i]) == FD) {
5531 S += '{';
5532 S += OI->getIdentifier()->getName();
5533 S += '}';
5534 return;
5535 }
5536 }
5537 }
Mike Stump11289f42009-09-09 15:08:12 +00005538 getObjCEncodingForTypeImpl(PointeeTy, S,
5539 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005540 NULL,
5541 false, false, false, false, false,
5542 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005543 return;
5544 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005545
5546 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005547 if (OPT->getInterfaceDecl() &&
5548 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005549 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005550 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005551 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5552 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005553 S += '<';
5554 S += (*I)->getNameAsString();
5555 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005556 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005557 S += '"';
5558 }
5559 return;
5560 }
Mike Stump11289f42009-09-09 15:08:12 +00005561
John McCalla9e6e8d2010-05-17 23:56:34 +00005562 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005563 // FIXME: we shoul do better than that. 'M' is available.
5564 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005565 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005566
John McCall393a78d2012-12-20 02:45:14 +00005567 case Type::Vector:
5568 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005569 // This matches gcc's encoding, even though technically it is
5570 // insufficient.
5571 // FIXME. We should do a better job than gcc.
5572 return;
John McCall393a78d2012-12-20 02:45:14 +00005573
Richard Smith27d807c2013-04-30 13:56:41 +00005574 case Type::Auto:
5575 // We could see an undeduced auto type here during error recovery.
5576 // Just ignore it.
5577 return;
5578
John McCall393a78d2012-12-20 02:45:14 +00005579#define ABSTRACT_TYPE(KIND, BASE)
5580#define TYPE(KIND, BASE)
5581#define DEPENDENT_TYPE(KIND, BASE) \
5582 case Type::KIND:
5583#define NON_CANONICAL_TYPE(KIND, BASE) \
5584 case Type::KIND:
5585#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5586 case Type::KIND:
5587#include "clang/AST/TypeNodes.def"
5588 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005589 }
John McCall393a78d2012-12-20 02:45:14 +00005590 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005591}
5592
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005593void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5594 std::string &S,
5595 const FieldDecl *FD,
5596 bool includeVBases) const {
5597 assert(RDecl && "Expected non-null RecordDecl");
5598 assert(!RDecl->isUnion() && "Should not be called for unions");
5599 if (!RDecl->getDefinition())
5600 return;
5601
5602 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5603 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5604 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5605
5606 if (CXXRec) {
5607 for (CXXRecordDecl::base_class_iterator
5608 BI = CXXRec->bases_begin(),
5609 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5610 if (!BI->isVirtual()) {
5611 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005612 if (base->isEmpty())
5613 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005614 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005615 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5616 std::make_pair(offs, base));
5617 }
5618 }
5619 }
5620
5621 unsigned i = 0;
5622 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5623 FieldEnd = RDecl->field_end();
5624 Field != FieldEnd; ++Field, ++i) {
5625 uint64_t offs = layout.getFieldOffset(i);
5626 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005627 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005628 }
5629
5630 if (CXXRec && includeVBases) {
5631 for (CXXRecordDecl::base_class_iterator
5632 BI = CXXRec->vbases_begin(),
5633 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5634 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005635 if (base->isEmpty())
5636 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005637 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005638 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5639 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005640 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5641 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005642 }
5643 }
5644
5645 CharUnits size;
5646 if (CXXRec) {
5647 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5648 } else {
5649 size = layout.getSize();
5650 }
5651
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005652#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005653 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005654#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005655 std::multimap<uint64_t, NamedDecl *>::iterator
5656 CurLayObj = FieldOrBaseOffsets.begin();
5657
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005658 if (CXXRec && CXXRec->isDynamicClass() &&
5659 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005660 if (FD) {
5661 S += "\"_vptr$";
5662 std::string recname = CXXRec->getNameAsString();
5663 if (recname.empty()) recname = "?";
5664 S += recname;
5665 S += '"';
5666 }
5667 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005668#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005669 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005670#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005671 }
5672
5673 if (!RDecl->hasFlexibleArrayMember()) {
5674 // Mark the end of the structure.
5675 uint64_t offs = toBits(size);
5676 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5677 std::make_pair(offs, (NamedDecl*)0));
5678 }
5679
5680 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005681#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005682 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005683 if (CurOffs < CurLayObj->first) {
5684 uint64_t padding = CurLayObj->first - CurOffs;
5685 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5686 // packing/alignment of members is different that normal, in which case
5687 // the encoding will be out-of-sync with the real layout.
5688 // If the runtime switches to just consider the size of types without
5689 // taking into account alignment, we could make padding explicit in the
5690 // encoding (e.g. using arrays of chars). The encoding strings would be
5691 // longer then though.
5692 CurOffs += padding;
5693 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005694#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005695
5696 NamedDecl *dcl = CurLayObj->second;
5697 if (dcl == 0)
5698 break; // reached end of structure.
5699
5700 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5701 // We expand the bases without their virtual bases since those are going
5702 // in the initial structure. Note that this differs from gcc which
5703 // expands virtual bases each time one is encountered in the hierarchy,
5704 // making the encoding type bigger than it really is.
5705 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005706 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005707#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005708 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005709#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005710 } else {
5711 FieldDecl *field = cast<FieldDecl>(dcl);
5712 if (FD) {
5713 S += '"';
5714 S += field->getNameAsString();
5715 S += '"';
5716 }
5717
5718 if (field->isBitField()) {
5719 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005720#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005721 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005722#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005723 } else {
5724 QualType qt = field->getType();
5725 getLegacyIntegralTypeEncoding(qt);
5726 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5727 /*OutermostType*/false,
5728 /*EncodingProperty*/false,
5729 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005730#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005731 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005732#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005733 }
5734 }
5735 }
5736}
5737
Mike Stump11289f42009-09-09 15:08:12 +00005738void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005739 std::string& S) const {
5740 if (QT & Decl::OBJC_TQ_In)
5741 S += 'n';
5742 if (QT & Decl::OBJC_TQ_Inout)
5743 S += 'N';
5744 if (QT & Decl::OBJC_TQ_Out)
5745 S += 'o';
5746 if (QT & Decl::OBJC_TQ_Bycopy)
5747 S += 'O';
5748 if (QT & Decl::OBJC_TQ_Byref)
5749 S += 'R';
5750 if (QT & Decl::OBJC_TQ_Oneway)
5751 S += 'V';
5752}
5753
Douglas Gregor3ea72692011-08-12 05:46:01 +00005754TypedefDecl *ASTContext::getObjCIdDecl() const {
5755 if (!ObjCIdDecl) {
5756 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5757 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005758 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005759 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005760 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005761}
5762
Douglas Gregor52e02802011-08-12 06:17:30 +00005763TypedefDecl *ASTContext::getObjCSelDecl() const {
5764 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005765 QualType T = getPointerType(ObjCBuiltinSelTy);
5766 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005767 }
5768 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005769}
5770
Douglas Gregor0a586182011-08-12 05:59:41 +00005771TypedefDecl *ASTContext::getObjCClassDecl() const {
5772 if (!ObjCClassDecl) {
5773 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5774 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005775 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005776 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005777 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005778}
5779
Douglas Gregord53ae832012-01-17 18:09:05 +00005780ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5781 if (!ObjCProtocolClassDecl) {
5782 ObjCProtocolClassDecl
5783 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5784 SourceLocation(),
5785 &Idents.get("Protocol"),
5786 /*PrevDecl=*/0,
5787 SourceLocation(), true);
5788 }
5789
5790 return ObjCProtocolClassDecl;
5791}
5792
Meador Inge5d3fb222012-06-16 03:34:49 +00005793//===----------------------------------------------------------------------===//
5794// __builtin_va_list Construction Functions
5795//===----------------------------------------------------------------------===//
5796
5797static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5798 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005799 QualType T = Context->getPointerType(Context->CharTy);
5800 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005801}
5802
5803static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5804 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005805 QualType T = Context->getPointerType(Context->VoidTy);
5806 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005807}
5808
Tim Northover9bb857a2013-01-31 12:13:10 +00005809static TypedefDecl *
5810CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005811 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005812 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005813 if (Context->getLangOpts().CPlusPlus) {
5814 // namespace std { struct __va_list {
5815 NamespaceDecl *NS;
5816 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5817 Context->getTranslationUnitDecl(),
5818 /*Inline*/false, SourceLocation(),
5819 SourceLocation(), &Context->Idents.get("std"),
5820 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005821 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005822 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005823 }
5824
5825 VaListTagDecl->startDefinition();
5826
5827 const size_t NumFields = 5;
5828 QualType FieldTypes[NumFields];
5829 const char *FieldNames[NumFields];
5830
5831 // void *__stack;
5832 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5833 FieldNames[0] = "__stack";
5834
5835 // void *__gr_top;
5836 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5837 FieldNames[1] = "__gr_top";
5838
5839 // void *__vr_top;
5840 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5841 FieldNames[2] = "__vr_top";
5842
5843 // int __gr_offs;
5844 FieldTypes[3] = Context->IntTy;
5845 FieldNames[3] = "__gr_offs";
5846
5847 // int __vr_offs;
5848 FieldTypes[4] = Context->IntTy;
5849 FieldNames[4] = "__vr_offs";
5850
5851 // Create fields
5852 for (unsigned i = 0; i < NumFields; ++i) {
5853 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5854 VaListTagDecl,
5855 SourceLocation(),
5856 SourceLocation(),
5857 &Context->Idents.get(FieldNames[i]),
5858 FieldTypes[i], /*TInfo=*/0,
5859 /*BitWidth=*/0,
5860 /*Mutable=*/false,
5861 ICIS_NoInit);
5862 Field->setAccess(AS_public);
5863 VaListTagDecl->addDecl(Field);
5864 }
5865 VaListTagDecl->completeDefinition();
5866 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5867 Context->VaListTagTy = VaListTagType;
5868
5869 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005870 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005871}
5872
Meador Inge5d3fb222012-06-16 03:34:49 +00005873static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5874 // typedef struct __va_list_tag {
5875 RecordDecl *VaListTagDecl;
5876
Alp Toker2dea15b2013-12-17 01:22:38 +00005877 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005878 VaListTagDecl->startDefinition();
5879
5880 const size_t NumFields = 5;
5881 QualType FieldTypes[NumFields];
5882 const char *FieldNames[NumFields];
5883
5884 // unsigned char gpr;
5885 FieldTypes[0] = Context->UnsignedCharTy;
5886 FieldNames[0] = "gpr";
5887
5888 // unsigned char fpr;
5889 FieldTypes[1] = Context->UnsignedCharTy;
5890 FieldNames[1] = "fpr";
5891
5892 // unsigned short reserved;
5893 FieldTypes[2] = Context->UnsignedShortTy;
5894 FieldNames[2] = "reserved";
5895
5896 // void* overflow_arg_area;
5897 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5898 FieldNames[3] = "overflow_arg_area";
5899
5900 // void* reg_save_area;
5901 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5902 FieldNames[4] = "reg_save_area";
5903
5904 // Create fields
5905 for (unsigned i = 0; i < NumFields; ++i) {
5906 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5907 SourceLocation(),
5908 SourceLocation(),
5909 &Context->Idents.get(FieldNames[i]),
5910 FieldTypes[i], /*TInfo=*/0,
5911 /*BitWidth=*/0,
5912 /*Mutable=*/false,
5913 ICIS_NoInit);
5914 Field->setAccess(AS_public);
5915 VaListTagDecl->addDecl(Field);
5916 }
5917 VaListTagDecl->completeDefinition();
5918 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005919 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005920
5921 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005922 TypedefDecl *VaListTagTypedefDecl =
5923 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5924
Meador Inge5d3fb222012-06-16 03:34:49 +00005925 QualType VaListTagTypedefType =
5926 Context->getTypedefType(VaListTagTypedefDecl);
5927
5928 // typedef __va_list_tag __builtin_va_list[1];
5929 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5930 QualType VaListTagArrayType
5931 = Context->getConstantArrayType(VaListTagTypedefType,
5932 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005933 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005934}
5935
5936static TypedefDecl *
5937CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5938 // typedef struct __va_list_tag {
5939 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005940 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005941 VaListTagDecl->startDefinition();
5942
5943 const size_t NumFields = 4;
5944 QualType FieldTypes[NumFields];
5945 const char *FieldNames[NumFields];
5946
5947 // unsigned gp_offset;
5948 FieldTypes[0] = Context->UnsignedIntTy;
5949 FieldNames[0] = "gp_offset";
5950
5951 // unsigned fp_offset;
5952 FieldTypes[1] = Context->UnsignedIntTy;
5953 FieldNames[1] = "fp_offset";
5954
5955 // void* overflow_arg_area;
5956 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5957 FieldNames[2] = "overflow_arg_area";
5958
5959 // void* reg_save_area;
5960 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5961 FieldNames[3] = "reg_save_area";
5962
5963 // Create fields
5964 for (unsigned i = 0; i < NumFields; ++i) {
5965 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5966 VaListTagDecl,
5967 SourceLocation(),
5968 SourceLocation(),
5969 &Context->Idents.get(FieldNames[i]),
5970 FieldTypes[i], /*TInfo=*/0,
5971 /*BitWidth=*/0,
5972 /*Mutable=*/false,
5973 ICIS_NoInit);
5974 Field->setAccess(AS_public);
5975 VaListTagDecl->addDecl(Field);
5976 }
5977 VaListTagDecl->completeDefinition();
5978 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005979 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005980
5981 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005982 TypedefDecl *VaListTagTypedefDecl =
5983 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5984
Meador Inge5d3fb222012-06-16 03:34:49 +00005985 QualType VaListTagTypedefType =
5986 Context->getTypedefType(VaListTagTypedefDecl);
5987
5988 // typedef __va_list_tag __builtin_va_list[1];
5989 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5990 QualType VaListTagArrayType
5991 = Context->getConstantArrayType(VaListTagTypedefType,
5992 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005993 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005994}
5995
5996static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5997 // typedef int __builtin_va_list[4];
5998 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5999 QualType IntArrayType
6000 = Context->getConstantArrayType(Context->IntTy,
6001 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006002 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006003}
6004
Logan Chien57086ce2012-10-10 06:56:20 +00006005static TypedefDecl *
6006CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006007 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006008 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006009 if (Context->getLangOpts().CPlusPlus) {
6010 // namespace std { struct __va_list {
6011 NamespaceDecl *NS;
6012 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6013 Context->getTranslationUnitDecl(),
6014 /*Inline*/false, SourceLocation(),
6015 SourceLocation(), &Context->Idents.get("std"),
6016 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006017 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006018 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006019 }
6020
6021 VaListDecl->startDefinition();
6022
6023 // void * __ap;
6024 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6025 VaListDecl,
6026 SourceLocation(),
6027 SourceLocation(),
6028 &Context->Idents.get("__ap"),
6029 Context->getPointerType(Context->VoidTy),
6030 /*TInfo=*/0,
6031 /*BitWidth=*/0,
6032 /*Mutable=*/false,
6033 ICIS_NoInit);
6034 Field->setAccess(AS_public);
6035 VaListDecl->addDecl(Field);
6036
6037 // };
6038 VaListDecl->completeDefinition();
6039
6040 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006041 QualType T = Context->getRecordType(VaListDecl);
6042 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006043}
6044
Ulrich Weigand47445072013-05-06 16:26:41 +00006045static TypedefDecl *
6046CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6047 // typedef struct __va_list_tag {
6048 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006049 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006050 VaListTagDecl->startDefinition();
6051
6052 const size_t NumFields = 4;
6053 QualType FieldTypes[NumFields];
6054 const char *FieldNames[NumFields];
6055
6056 // long __gpr;
6057 FieldTypes[0] = Context->LongTy;
6058 FieldNames[0] = "__gpr";
6059
6060 // long __fpr;
6061 FieldTypes[1] = Context->LongTy;
6062 FieldNames[1] = "__fpr";
6063
6064 // void *__overflow_arg_area;
6065 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6066 FieldNames[2] = "__overflow_arg_area";
6067
6068 // void *__reg_save_area;
6069 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6070 FieldNames[3] = "__reg_save_area";
6071
6072 // Create fields
6073 for (unsigned i = 0; i < NumFields; ++i) {
6074 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6075 VaListTagDecl,
6076 SourceLocation(),
6077 SourceLocation(),
6078 &Context->Idents.get(FieldNames[i]),
6079 FieldTypes[i], /*TInfo=*/0,
6080 /*BitWidth=*/0,
6081 /*Mutable=*/false,
6082 ICIS_NoInit);
6083 Field->setAccess(AS_public);
6084 VaListTagDecl->addDecl(Field);
6085 }
6086 VaListTagDecl->completeDefinition();
6087 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6088 Context->VaListTagTy = VaListTagType;
6089
6090 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006091 TypedefDecl *VaListTagTypedefDecl =
6092 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006093 QualType VaListTagTypedefType =
6094 Context->getTypedefType(VaListTagTypedefDecl);
6095
6096 // typedef __va_list_tag __builtin_va_list[1];
6097 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6098 QualType VaListTagArrayType
6099 = Context->getConstantArrayType(VaListTagTypedefType,
6100 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006101
Alp Toker56b5cc92013-12-15 10:36:26 +00006102 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006103}
6104
Meador Inge5d3fb222012-06-16 03:34:49 +00006105static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6106 TargetInfo::BuiltinVaListKind Kind) {
6107 switch (Kind) {
6108 case TargetInfo::CharPtrBuiltinVaList:
6109 return CreateCharPtrBuiltinVaListDecl(Context);
6110 case TargetInfo::VoidPtrBuiltinVaList:
6111 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006112 case TargetInfo::AArch64ABIBuiltinVaList:
6113 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006114 case TargetInfo::PowerABIBuiltinVaList:
6115 return CreatePowerABIBuiltinVaListDecl(Context);
6116 case TargetInfo::X86_64ABIBuiltinVaList:
6117 return CreateX86_64ABIBuiltinVaListDecl(Context);
6118 case TargetInfo::PNaClABIBuiltinVaList:
6119 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006120 case TargetInfo::AAPCSABIBuiltinVaList:
6121 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006122 case TargetInfo::SystemZBuiltinVaList:
6123 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006124 }
6125
6126 llvm_unreachable("Unhandled __builtin_va_list type kind");
6127}
6128
6129TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006130 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006131 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006132 assert(BuiltinVaListDecl->isImplicit());
6133 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006134
6135 return BuiltinVaListDecl;
6136}
6137
Meador Ingecfb60902012-07-01 15:57:25 +00006138QualType ASTContext::getVaListTagType() const {
6139 // Force the creation of VaListTagTy by building the __builtin_va_list
6140 // declaration.
6141 if (VaListTagTy.isNull())
6142 (void) getBuiltinVaListDecl();
6143
6144 return VaListTagTy;
6145}
6146
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006147void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006148 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006149 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006150
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006151 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006152}
6153
John McCalld28ae272009-12-02 08:04:21 +00006154/// \brief Retrieve the template name that corresponds to a non-empty
6155/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006156TemplateName
6157ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6158 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006159 unsigned size = End - Begin;
6160 assert(size > 1 && "set is not overloaded!");
6161
6162 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6163 size * sizeof(FunctionTemplateDecl*));
6164 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6165
6166 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006167 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006168 NamedDecl *D = *I;
6169 assert(isa<FunctionTemplateDecl>(D) ||
6170 (isa<UsingShadowDecl>(D) &&
6171 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6172 *Storage++ = D;
6173 }
6174
6175 return TemplateName(OT);
6176}
6177
Douglas Gregordc572a32009-03-30 22:58:21 +00006178/// \brief Retrieve the template name that represents a qualified
6179/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006180TemplateName
6181ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6182 bool TemplateKeyword,
6183 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006184 assert(NNS && "Missing nested-name-specifier in qualified template name");
6185
Douglas Gregorc42075a2010-02-04 18:10:26 +00006186 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006187 llvm::FoldingSetNodeID ID;
6188 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6189
6190 void *InsertPos = 0;
6191 QualifiedTemplateName *QTN =
6192 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6193 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006194 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6195 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006196 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6197 }
6198
6199 return TemplateName(QTN);
6200}
6201
6202/// \brief Retrieve the template name that represents a dependent
6203/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006204TemplateName
6205ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6206 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006207 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006208 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006209
6210 llvm::FoldingSetNodeID ID;
6211 DependentTemplateName::Profile(ID, NNS, Name);
6212
6213 void *InsertPos = 0;
6214 DependentTemplateName *QTN =
6215 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6216
6217 if (QTN)
6218 return TemplateName(QTN);
6219
6220 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6221 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006222 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6223 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006224 } else {
6225 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006226 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6227 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006228 DependentTemplateName *CheckQTN =
6229 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6230 assert(!CheckQTN && "Dependent type name canonicalization broken");
6231 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006232 }
6233
6234 DependentTemplateNames.InsertNode(QTN, InsertPos);
6235 return TemplateName(QTN);
6236}
6237
Douglas Gregor71395fa2009-11-04 00:56:37 +00006238/// \brief Retrieve the template name that represents a dependent
6239/// template name such as \c MetaFun::template operator+.
6240TemplateName
6241ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006242 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006243 assert((!NNS || NNS->isDependent()) &&
6244 "Nested name specifier must be dependent");
6245
6246 llvm::FoldingSetNodeID ID;
6247 DependentTemplateName::Profile(ID, NNS, Operator);
6248
6249 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006250 DependentTemplateName *QTN
6251 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006252
6253 if (QTN)
6254 return TemplateName(QTN);
6255
6256 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6257 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006258 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6259 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006260 } else {
6261 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006262 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6263 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006264
6265 DependentTemplateName *CheckQTN
6266 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6267 assert(!CheckQTN && "Dependent template name canonicalization broken");
6268 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006269 }
6270
6271 DependentTemplateNames.InsertNode(QTN, InsertPos);
6272 return TemplateName(QTN);
6273}
6274
Douglas Gregor5590be02011-01-15 06:45:20 +00006275TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006276ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6277 TemplateName replacement) const {
6278 llvm::FoldingSetNodeID ID;
6279 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6280
6281 void *insertPos = 0;
6282 SubstTemplateTemplateParmStorage *subst
6283 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6284
6285 if (!subst) {
6286 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6287 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6288 }
6289
6290 return TemplateName(subst);
6291}
6292
6293TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006294ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6295 const TemplateArgument &ArgPack) const {
6296 ASTContext &Self = const_cast<ASTContext &>(*this);
6297 llvm::FoldingSetNodeID ID;
6298 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6299
6300 void *InsertPos = 0;
6301 SubstTemplateTemplateParmPackStorage *Subst
6302 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6303
6304 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006305 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006306 ArgPack.pack_size(),
6307 ArgPack.pack_begin());
6308 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6309 }
6310
6311 return TemplateName(Subst);
6312}
6313
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006314/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006315/// TargetInfo, produce the corresponding type. The unsigned @p Type
6316/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006317CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006318 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006319 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006320 case TargetInfo::SignedChar: return SignedCharTy;
6321 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006322 case TargetInfo::SignedShort: return ShortTy;
6323 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6324 case TargetInfo::SignedInt: return IntTy;
6325 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6326 case TargetInfo::SignedLong: return LongTy;
6327 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6328 case TargetInfo::SignedLongLong: return LongLongTy;
6329 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6330 }
6331
David Blaikie83d382b2011-09-23 05:06:16 +00006332 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006333}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006334
6335//===----------------------------------------------------------------------===//
6336// Type Predicates.
6337//===----------------------------------------------------------------------===//
6338
Fariborz Jahanian96207692009-02-18 21:49:28 +00006339/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6340/// garbage collection attribute.
6341///
John McCall553d45a2011-01-12 00:34:59 +00006342Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006343 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006344 return Qualifiers::GCNone;
6345
David Blaikiebbafb8a2012-03-11 07:00:24 +00006346 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006347 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6348
6349 // Default behaviour under objective-C's gc is for ObjC pointers
6350 // (or pointers to them) be treated as though they were declared
6351 // as __strong.
6352 if (GCAttrs == Qualifiers::GCNone) {
6353 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6354 return Qualifiers::Strong;
6355 else if (Ty->isPointerType())
6356 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6357 } else {
6358 // It's not valid to set GC attributes on anything that isn't a
6359 // pointer.
6360#ifndef NDEBUG
6361 QualType CT = Ty->getCanonicalTypeInternal();
6362 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6363 CT = AT->getElementType();
6364 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6365#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006366 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006367 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006368}
6369
Chris Lattner49af6a42008-04-07 06:51:04 +00006370//===----------------------------------------------------------------------===//
6371// Type Compatibility Testing
6372//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006373
Mike Stump11289f42009-09-09 15:08:12 +00006374/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006375/// compatible.
6376static bool areCompatVectorTypes(const VectorType *LHS,
6377 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006378 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006379 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006380 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006381}
6382
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006383bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6384 QualType SecondVec) {
6385 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6386 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6387
6388 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6389 return true;
6390
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006391 // Treat Neon vector types and most AltiVec vector types as if they are the
6392 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006393 const VectorType *First = FirstVec->getAs<VectorType>();
6394 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006395 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006396 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006397 First->getVectorKind() != VectorType::AltiVecPixel &&
6398 First->getVectorKind() != VectorType::AltiVecBool &&
6399 Second->getVectorKind() != VectorType::AltiVecPixel &&
6400 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006401 return true;
6402
6403 return false;
6404}
6405
Steve Naroff8e6aee52009-07-23 01:01:38 +00006406//===----------------------------------------------------------------------===//
6407// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6408//===----------------------------------------------------------------------===//
6409
6410/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6411/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006412bool
6413ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6414 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006415 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006416 return true;
6417 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6418 E = rProto->protocol_end(); PI != E; ++PI)
6419 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6420 return true;
6421 return false;
6422}
6423
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006424/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6425/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006426bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6427 QualType rhs) {
6428 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6429 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6430 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6431
6432 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6433 E = lhsQID->qual_end(); I != E; ++I) {
6434 bool match = false;
6435 ObjCProtocolDecl *lhsProto = *I;
6436 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6437 E = rhsOPT->qual_end(); J != E; ++J) {
6438 ObjCProtocolDecl *rhsProto = *J;
6439 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6440 match = true;
6441 break;
6442 }
6443 }
6444 if (!match)
6445 return false;
6446 }
6447 return true;
6448}
6449
Steve Naroff8e6aee52009-07-23 01:01:38 +00006450/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6451/// ObjCQualifiedIDType.
6452bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6453 bool compare) {
6454 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006455 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006456 lhs->isObjCIdType() || lhs->isObjCClassType())
6457 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006458 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006459 rhs->isObjCIdType() || rhs->isObjCClassType())
6460 return true;
6461
6462 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006463 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006464
Steve Naroff8e6aee52009-07-23 01:01:38 +00006465 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006466
Steve Naroff8e6aee52009-07-23 01:01:38 +00006467 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006468 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006469 // make sure we check the class hierarchy.
6470 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6471 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6472 E = lhsQID->qual_end(); I != E; ++I) {
6473 // when comparing an id<P> on lhs with a static type on rhs,
6474 // see if static class implements all of id's protocols, directly or
6475 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006476 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006477 return false;
6478 }
6479 }
6480 // If there are no qualifiers and no interface, we have an 'id'.
6481 return true;
6482 }
Mike Stump11289f42009-09-09 15:08:12 +00006483 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006484 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6485 E = lhsQID->qual_end(); I != E; ++I) {
6486 ObjCProtocolDecl *lhsProto = *I;
6487 bool match = false;
6488
6489 // when comparing an id<P> on lhs with a static type on rhs,
6490 // see if static class implements all of id's protocols, directly or
6491 // through its super class and categories.
6492 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6493 E = rhsOPT->qual_end(); J != E; ++J) {
6494 ObjCProtocolDecl *rhsProto = *J;
6495 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6496 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6497 match = true;
6498 break;
6499 }
6500 }
Mike Stump11289f42009-09-09 15:08:12 +00006501 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006502 // make sure we check the class hierarchy.
6503 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6504 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6505 E = lhsQID->qual_end(); I != E; ++I) {
6506 // when comparing an id<P> on lhs with a static type on rhs,
6507 // see if static class implements all of id's protocols, directly or
6508 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006509 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006510 match = true;
6511 break;
6512 }
6513 }
6514 }
6515 if (!match)
6516 return false;
6517 }
Mike Stump11289f42009-09-09 15:08:12 +00006518
Steve Naroff8e6aee52009-07-23 01:01:38 +00006519 return true;
6520 }
Mike Stump11289f42009-09-09 15:08:12 +00006521
Steve Naroff8e6aee52009-07-23 01:01:38 +00006522 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6523 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6524
Mike Stump11289f42009-09-09 15:08:12 +00006525 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006526 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006527 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006528 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6529 E = lhsOPT->qual_end(); I != E; ++I) {
6530 ObjCProtocolDecl *lhsProto = *I;
6531 bool match = false;
6532
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006533 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006534 // see if static class implements all of id's protocols, directly or
6535 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006536 // First, lhs protocols in the qualifier list must be found, direct
6537 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006538 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6539 E = rhsQID->qual_end(); J != E; ++J) {
6540 ObjCProtocolDecl *rhsProto = *J;
6541 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6542 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6543 match = true;
6544 break;
6545 }
6546 }
6547 if (!match)
6548 return false;
6549 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006550
6551 // Static class's protocols, or its super class or category protocols
6552 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6553 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6554 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6555 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6556 // This is rather dubious but matches gcc's behavior. If lhs has
6557 // no type qualifier and its class has no static protocol(s)
6558 // assume that it is mismatch.
6559 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6560 return false;
6561 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6562 LHSInheritedProtocols.begin(),
6563 E = LHSInheritedProtocols.end(); I != E; ++I) {
6564 bool match = false;
6565 ObjCProtocolDecl *lhsProto = (*I);
6566 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6567 E = rhsQID->qual_end(); J != E; ++J) {
6568 ObjCProtocolDecl *rhsProto = *J;
6569 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6570 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6571 match = true;
6572 break;
6573 }
6574 }
6575 if (!match)
6576 return false;
6577 }
6578 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006579 return true;
6580 }
6581 return false;
6582}
6583
Eli Friedman47f77112008-08-22 00:56:42 +00006584/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006585/// compatible for assignment from RHS to LHS. This handles validation of any
6586/// protocol qualifiers on the LHS or RHS.
6587///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006588bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6589 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006590 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6591 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6592
Steve Naroff1329fa02009-07-15 18:40:39 +00006593 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006594 if (LHS->isObjCUnqualifiedIdOrClass() ||
6595 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006596 return true;
6597
John McCall8b07ec22010-05-15 11:32:37 +00006598 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006599 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6600 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006601 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006602
6603 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6604 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6605 QualType(RHSOPT,0));
6606
John McCall8b07ec22010-05-15 11:32:37 +00006607 // If we have 2 user-defined types, fall into that path.
6608 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006609 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006610
Steve Naroff8e6aee52009-07-23 01:01:38 +00006611 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006612}
6613
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006614/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006615/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006616/// arguments in block literals. When passed as arguments, passing 'A*' where
6617/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6618/// not OK. For the return type, the opposite is not OK.
6619bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6620 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006621 const ObjCObjectPointerType *RHSOPT,
6622 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006623 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006624 return true;
6625
6626 if (LHSOPT->isObjCBuiltinType()) {
6627 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6628 }
6629
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006630 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006631 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6632 QualType(RHSOPT,0),
6633 false);
6634
6635 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6636 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6637 if (LHS && RHS) { // We have 2 user-defined types.
6638 if (LHS != RHS) {
6639 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006640 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006641 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006642 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006643 }
6644 else
6645 return true;
6646 }
6647 return false;
6648}
6649
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006650/// getIntersectionOfProtocols - This routine finds the intersection of set
6651/// of protocols inherited from two distinct objective-c pointer objects.
6652/// It is used to build composite qualifier list of the composite type of
6653/// the conditional expression involving two objective-c pointer objects.
6654static
6655void getIntersectionOfProtocols(ASTContext &Context,
6656 const ObjCObjectPointerType *LHSOPT,
6657 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006658 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006659
John McCall8b07ec22010-05-15 11:32:37 +00006660 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6661 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6662 assert(LHS->getInterface() && "LHS must have an interface base");
6663 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006664
6665 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6666 unsigned LHSNumProtocols = LHS->getNumProtocols();
6667 if (LHSNumProtocols > 0)
6668 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6669 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006670 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006671 Context.CollectInheritedProtocols(LHS->getInterface(),
6672 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006673 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6674 LHSInheritedProtocols.end());
6675 }
6676
6677 unsigned RHSNumProtocols = RHS->getNumProtocols();
6678 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006679 ObjCProtocolDecl **RHSProtocols =
6680 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006681 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6682 if (InheritedProtocolSet.count(RHSProtocols[i]))
6683 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006684 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006685 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006686 Context.CollectInheritedProtocols(RHS->getInterface(),
6687 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006688 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6689 RHSInheritedProtocols.begin(),
6690 E = RHSInheritedProtocols.end(); I != E; ++I)
6691 if (InheritedProtocolSet.count((*I)))
6692 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006693 }
6694}
6695
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006696/// areCommonBaseCompatible - Returns common base class of the two classes if
6697/// one found. Note that this is O'2 algorithm. But it will be called as the
6698/// last type comparison in a ?-exp of ObjC pointer types before a
6699/// warning is issued. So, its invokation is extremely rare.
6700QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006701 const ObjCObjectPointerType *Lptr,
6702 const ObjCObjectPointerType *Rptr) {
6703 const ObjCObjectType *LHS = Lptr->getObjectType();
6704 const ObjCObjectType *RHS = Rptr->getObjectType();
6705 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6706 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006707 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006708 return QualType();
6709
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006710 do {
John McCall8b07ec22010-05-15 11:32:37 +00006711 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006712 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006713 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006714 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6715
6716 QualType Result = QualType(LHS, 0);
6717 if (!Protocols.empty())
6718 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6719 Result = getObjCObjectPointerType(Result);
6720 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006721 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006722 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006723
6724 return QualType();
6725}
6726
John McCall8b07ec22010-05-15 11:32:37 +00006727bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6728 const ObjCObjectType *RHS) {
6729 assert(LHS->getInterface() && "LHS is not an interface type");
6730 assert(RHS->getInterface() && "RHS is not an interface type");
6731
Chris Lattner49af6a42008-04-07 06:51:04 +00006732 // Verify that the base decls are compatible: the RHS must be a subclass of
6733 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006734 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006735 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006736
Chris Lattner49af6a42008-04-07 06:51:04 +00006737 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6738 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006739 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006740 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006741
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006742 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6743 // more detailed analysis is required.
6744 if (RHS->getNumProtocols() == 0) {
6745 // OK, if LHS is a superclass of RHS *and*
6746 // this superclass is assignment compatible with LHS.
6747 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006748 bool IsSuperClass =
6749 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6750 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006751 // OK if conversion of LHS to SuperClass results in narrowing of types
6752 // ; i.e., SuperClass may implement at least one of the protocols
6753 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6754 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6755 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006756 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006757 // If super class has no protocols, it is not a match.
6758 if (SuperClassInheritedProtocols.empty())
6759 return false;
6760
6761 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6762 LHSPE = LHS->qual_end();
6763 LHSPI != LHSPE; LHSPI++) {
6764 bool SuperImplementsProtocol = false;
6765 ObjCProtocolDecl *LHSProto = (*LHSPI);
6766
6767 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6768 SuperClassInheritedProtocols.begin(),
6769 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6770 ObjCProtocolDecl *SuperClassProto = (*I);
6771 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6772 SuperImplementsProtocol = true;
6773 break;
6774 }
6775 }
6776 if (!SuperImplementsProtocol)
6777 return false;
6778 }
6779 return true;
6780 }
6781 return false;
6782 }
Mike Stump11289f42009-09-09 15:08:12 +00006783
John McCall8b07ec22010-05-15 11:32:37 +00006784 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6785 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006786 LHSPI != LHSPE; LHSPI++) {
6787 bool RHSImplementsProtocol = false;
6788
6789 // If the RHS doesn't implement the protocol on the left, the types
6790 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006791 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6792 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006793 RHSPI != RHSPE; RHSPI++) {
6794 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006795 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006796 break;
6797 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006798 }
6799 // FIXME: For better diagnostics, consider passing back the protocol name.
6800 if (!RHSImplementsProtocol)
6801 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006802 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006803 // The RHS implements all protocols listed on the LHS.
6804 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006805}
6806
Steve Naroffb7605152009-02-12 17:52:19 +00006807bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6808 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006809 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6810 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006811
Steve Naroff7cae42b2009-07-10 23:34:53 +00006812 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006813 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006814
6815 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6816 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006817}
6818
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006819bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6820 return canAssignObjCInterfaces(
6821 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6822 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6823}
6824
Mike Stump11289f42009-09-09 15:08:12 +00006825/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006826/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006827/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006828/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006829bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6830 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006831 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006832 return hasSameType(LHS, RHS);
6833
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006834 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006835}
6836
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006837bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006838 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006839}
6840
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006841bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6842 return !mergeTypes(LHS, RHS, true).isNull();
6843}
6844
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006845/// mergeTransparentUnionType - if T is a transparent union type and a member
6846/// of T is compatible with SubType, return the merged type, else return
6847/// QualType()
6848QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6849 bool OfBlockPointer,
6850 bool Unqualified) {
6851 if (const RecordType *UT = T->getAsUnionType()) {
6852 RecordDecl *UD = UT->getDecl();
6853 if (UD->hasAttr<TransparentUnionAttr>()) {
6854 for (RecordDecl::field_iterator it = UD->field_begin(),
6855 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006856 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006857 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6858 if (!MT.isNull())
6859 return MT;
6860 }
6861 }
6862 }
6863
6864 return QualType();
6865}
6866
Alp Toker9cacbab2014-01-20 20:26:09 +00006867/// mergeFunctionParameterTypes - merge two types which appear as function
6868/// parameter types
6869QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6870 bool OfBlockPointer,
6871 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006872 // GNU extension: two types are compatible if they appear as a function
6873 // argument, one of the types is a transparent union type and the other
6874 // type is compatible with a union member
6875 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6876 Unqualified);
6877 if (!lmerge.isNull())
6878 return lmerge;
6879
6880 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6881 Unqualified);
6882 if (!rmerge.isNull())
6883 return rmerge;
6884
6885 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6886}
6887
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006888QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006889 bool OfBlockPointer,
6890 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006891 const FunctionType *lbase = lhs->getAs<FunctionType>();
6892 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006893 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6894 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006895 bool allLTypes = true;
6896 bool allRTypes = true;
6897
6898 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006899 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006900 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006901 QualType RHS = rbase->getReturnType();
6902 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006903 bool UnqualifiedResult = Unqualified;
6904 if (!UnqualifiedResult)
6905 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006906 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006907 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006908 else
Alp Toker314cc812014-01-25 16:55:45 +00006909 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006910 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006911 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006912
6913 if (Unqualified)
6914 retType = retType.getUnqualifiedType();
6915
Alp Toker314cc812014-01-25 16:55:45 +00006916 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6917 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006918 if (Unqualified) {
6919 LRetType = LRetType.getUnqualifiedType();
6920 RRetType = RRetType.getUnqualifiedType();
6921 }
6922
6923 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006924 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006925 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006926 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006927
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006928 // FIXME: double check this
6929 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6930 // rbase->getRegParmAttr() != 0 &&
6931 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006932 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6933 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006934
Douglas Gregor8c940862010-01-18 17:14:39 +00006935 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006936 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006937 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006938
John McCall8c6b56f2010-12-15 01:06:38 +00006939 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006940 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6941 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006942 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6943 return QualType();
6944
John McCall31168b02011-06-15 23:02:42 +00006945 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6946 return QualType();
6947
John McCall8c6b56f2010-12-15 01:06:38 +00006948 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6949 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006950
Rafael Espindola8778c282012-11-29 16:09:03 +00006951 if (lbaseInfo.getNoReturn() != NoReturn)
6952 allLTypes = false;
6953 if (rbaseInfo.getNoReturn() != NoReturn)
6954 allRTypes = false;
6955
John McCall31168b02011-06-15 23:02:42 +00006956 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006957
Eli Friedman47f77112008-08-22 00:56:42 +00006958 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006959 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6960 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006961 // Compatible functions must have the same number of parameters
6962 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006963 return QualType();
6964
6965 // Variadic and non-variadic functions aren't compatible
6966 if (lproto->isVariadic() != rproto->isVariadic())
6967 return QualType();
6968
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006969 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6970 return QualType();
6971
Fariborz Jahanian97676972011-09-28 21:52:05 +00006972 if (LangOpts.ObjCAutoRefCount &&
6973 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6974 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006975
6976 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006977 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006978 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6979 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6980 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6981 QualType paramType = mergeFunctionParameterTypes(
6982 lParamType, rParamType, OfBlockPointer, Unqualified);
6983 if (paramType.isNull())
6984 return QualType();
6985
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006986 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006987 paramType = paramType.getUnqualifiedType();
6988
6989 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006990 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006991 lParamType = lParamType.getUnqualifiedType();
6992 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006993 }
Alp Toker601b22c2014-01-21 23:35:24 +00006994
6995 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006996 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006997 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006998 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006999 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007000
Eli Friedman47f77112008-08-22 00:56:42 +00007001 if (allLTypes) return lhs;
7002 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007003
7004 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7005 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007006 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007007 }
7008
7009 if (lproto) allRTypes = false;
7010 if (rproto) allLTypes = false;
7011
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007012 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007013 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007014 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007015 if (proto->isVariadic()) return QualType();
7016 // Check that the types are compatible with the types that
7017 // would result from default argument promotions (C99 6.7.5.3p15).
7018 // The only types actually affected are promotable integer
7019 // types and floats, which would be passed as a different
7020 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007021 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7022 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007023
Eli Friedman448ce402012-08-30 00:44:15 +00007024 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007025 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007026 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7027 paramTy = Enum->getDecl()->getIntegerType();
7028 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007029 return QualType();
7030 }
Alp Toker601b22c2014-01-21 23:35:24 +00007031
7032 if (paramTy->isPromotableIntegerType() ||
7033 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007034 return QualType();
7035 }
7036
7037 if (allLTypes) return lhs;
7038 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007039
7040 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7041 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007042 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007043 }
7044
7045 if (allLTypes) return lhs;
7046 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007047 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007048}
7049
John McCall433c2e62013-03-21 00:10:07 +00007050/// Given that we have an enum type and a non-enum type, try to merge them.
7051static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7052 QualType other, bool isBlockReturnType) {
7053 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7054 // a signed integer type, or an unsigned integer type.
7055 // Compatibility is based on the underlying type, not the promotion
7056 // type.
7057 QualType underlyingType = ET->getDecl()->getIntegerType();
7058 if (underlyingType.isNull()) return QualType();
7059 if (Context.hasSameType(underlyingType, other))
7060 return other;
7061
7062 // In block return types, we're more permissive and accept any
7063 // integral type of the same size.
7064 if (isBlockReturnType && other->isIntegerType() &&
7065 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7066 return other;
7067
7068 return QualType();
7069}
7070
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007071QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007072 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007073 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007074 // C++ [expr]: If an expression initially has the type "reference to T", the
7075 // type is adjusted to "T" prior to any further analysis, the expression
7076 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007077 // expression is an lvalue unless the reference is an rvalue reference and
7078 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007079 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7080 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007081
7082 if (Unqualified) {
7083 LHS = LHS.getUnqualifiedType();
7084 RHS = RHS.getUnqualifiedType();
7085 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007086
Eli Friedman47f77112008-08-22 00:56:42 +00007087 QualType LHSCan = getCanonicalType(LHS),
7088 RHSCan = getCanonicalType(RHS);
7089
7090 // If two types are identical, they are compatible.
7091 if (LHSCan == RHSCan)
7092 return LHS;
7093
John McCall8ccfcb52009-09-24 19:53:00 +00007094 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007095 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7096 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007097 if (LQuals != RQuals) {
7098 // If any of these qualifiers are different, we have a type
7099 // mismatch.
7100 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007101 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7102 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007103 return QualType();
7104
7105 // Exactly one GC qualifier difference is allowed: __strong is
7106 // okay if the other type has no GC qualifier but is an Objective
7107 // C object pointer (i.e. implicitly strong by default). We fix
7108 // this by pretending that the unqualified type was actually
7109 // qualified __strong.
7110 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7111 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7112 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7113
7114 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7115 return QualType();
7116
7117 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7118 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7119 }
7120 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7121 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7122 }
Eli Friedman47f77112008-08-22 00:56:42 +00007123 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007124 }
7125
7126 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007127
Eli Friedmandcca6332009-06-01 01:22:52 +00007128 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7129 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007130
Chris Lattnerfd652912008-01-14 05:45:46 +00007131 // We want to consider the two function types to be the same for these
7132 // comparisons, just force one to the other.
7133 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7134 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007135
7136 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007137 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7138 LHSClass = Type::ConstantArray;
7139 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7140 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007141
John McCall8b07ec22010-05-15 11:32:37 +00007142 // ObjCInterfaces are just specialized ObjCObjects.
7143 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7144 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7145
Nate Begemance4d7fc2008-04-18 23:10:10 +00007146 // Canonicalize ExtVector -> Vector.
7147 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7148 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007149
Chris Lattner95554662008-04-07 05:43:21 +00007150 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007151 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007152 // Note that we only have special rules for turning block enum
7153 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007154 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007155 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007156 }
John McCall9dd450b2009-09-21 23:43:11 +00007157 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007158 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007159 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007160 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007161 if (OfBlockPointer && !BlockReturnType) {
7162 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7163 return LHS;
7164 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7165 return RHS;
7166 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007167
Eli Friedman47f77112008-08-22 00:56:42 +00007168 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007169 }
Eli Friedman47f77112008-08-22 00:56:42 +00007170
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007171 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007172 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007173#define TYPE(Class, Base)
7174#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007175#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007176#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7177#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7178#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007179 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007180
Richard Smith27d807c2013-04-30 13:56:41 +00007181 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007182 case Type::LValueReference:
7183 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007184 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007185 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007186
John McCall8b07ec22010-05-15 11:32:37 +00007187 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007188 case Type::IncompleteArray:
7189 case Type::VariableArray:
7190 case Type::FunctionProto:
7191 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007192 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007193
Chris Lattnerfd652912008-01-14 05:45:46 +00007194 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007195 {
7196 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007197 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7198 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007199 if (Unqualified) {
7200 LHSPointee = LHSPointee.getUnqualifiedType();
7201 RHSPointee = RHSPointee.getUnqualifiedType();
7202 }
7203 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7204 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007205 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007206 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007207 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007208 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007209 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007210 return getPointerType(ResultType);
7211 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007212 case Type::BlockPointer:
7213 {
7214 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007215 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7216 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007217 if (Unqualified) {
7218 LHSPointee = LHSPointee.getUnqualifiedType();
7219 RHSPointee = RHSPointee.getUnqualifiedType();
7220 }
7221 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7222 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007223 if (ResultType.isNull()) return QualType();
7224 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7225 return LHS;
7226 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7227 return RHS;
7228 return getBlockPointerType(ResultType);
7229 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007230 case Type::Atomic:
7231 {
7232 // Merge two pointer types, while trying to preserve typedef info
7233 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7234 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7235 if (Unqualified) {
7236 LHSValue = LHSValue.getUnqualifiedType();
7237 RHSValue = RHSValue.getUnqualifiedType();
7238 }
7239 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7240 Unqualified);
7241 if (ResultType.isNull()) return QualType();
7242 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7243 return LHS;
7244 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7245 return RHS;
7246 return getAtomicType(ResultType);
7247 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007248 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007249 {
7250 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7251 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7252 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7253 return QualType();
7254
7255 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7256 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007257 if (Unqualified) {
7258 LHSElem = LHSElem.getUnqualifiedType();
7259 RHSElem = RHSElem.getUnqualifiedType();
7260 }
7261
7262 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007263 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007264 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7265 return LHS;
7266 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7267 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007268 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7269 ArrayType::ArraySizeModifier(), 0);
7270 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7271 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007272 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7273 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007274 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7275 return LHS;
7276 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7277 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007278 if (LVAT) {
7279 // FIXME: This isn't correct! But tricky to implement because
7280 // the array's size has to be the size of LHS, but the type
7281 // has to be different.
7282 return LHS;
7283 }
7284 if (RVAT) {
7285 // FIXME: This isn't correct! But tricky to implement because
7286 // the array's size has to be the size of RHS, but the type
7287 // has to be different.
7288 return RHS;
7289 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007290 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7291 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007292 return getIncompleteArrayType(ResultType,
7293 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007294 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007295 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007296 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007297 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007298 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007299 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007300 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007301 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007302 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007303 case Type::Complex:
7304 // Distinct complex types are incompatible.
7305 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007306 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007307 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007308 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7309 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007310 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007311 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007312 case Type::ObjCObject: {
7313 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007314 // FIXME: This should be type compatibility, e.g. whether
7315 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007316 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7317 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7318 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007319 return LHS;
7320
Eli Friedman47f77112008-08-22 00:56:42 +00007321 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007322 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007323 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007324 if (OfBlockPointer) {
7325 if (canAssignObjCInterfacesInBlockPointer(
7326 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007327 RHS->getAs<ObjCObjectPointerType>(),
7328 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007329 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007330 return QualType();
7331 }
John McCall9dd450b2009-09-21 23:43:11 +00007332 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7333 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007334 return LHS;
7335
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007336 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007337 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007338 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007339
David Blaikie8a40f702012-01-17 06:56:22 +00007340 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007341}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007342
Fariborz Jahanian97676972011-09-28 21:52:05 +00007343bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7344 const FunctionProtoType *FromFunctionType,
7345 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007346 if (FromFunctionType->hasAnyConsumedParams() !=
7347 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007348 return false;
7349 FunctionProtoType::ExtProtoInfo FromEPI =
7350 FromFunctionType->getExtProtoInfo();
7351 FunctionProtoType::ExtProtoInfo ToEPI =
7352 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007353 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007354 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7355 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007356 return false;
7357 }
7358 return true;
7359}
7360
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007361/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7362/// 'RHS' attributes and returns the merged version; including for function
7363/// return types.
7364QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7365 QualType LHSCan = getCanonicalType(LHS),
7366 RHSCan = getCanonicalType(RHS);
7367 // If two types are identical, they are compatible.
7368 if (LHSCan == RHSCan)
7369 return LHS;
7370 if (RHSCan->isFunctionType()) {
7371 if (!LHSCan->isFunctionType())
7372 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007373 QualType OldReturnType =
7374 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007375 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007376 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007377 QualType ResReturnType =
7378 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7379 if (ResReturnType.isNull())
7380 return QualType();
7381 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7382 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7383 // In either case, use OldReturnType to build the new function type.
7384 const FunctionType *F = LHS->getAs<FunctionType>();
7385 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007386 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7387 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007388 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007389 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007390 return ResultType;
7391 }
7392 }
7393 return QualType();
7394 }
7395
7396 // If the qualifiers are different, the types can still be merged.
7397 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7398 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7399 if (LQuals != RQuals) {
7400 // If any of these qualifiers are different, we have a type mismatch.
7401 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7402 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7403 return QualType();
7404
7405 // Exactly one GC qualifier difference is allowed: __strong is
7406 // okay if the other type has no GC qualifier but is an Objective
7407 // C object pointer (i.e. implicitly strong by default). We fix
7408 // this by pretending that the unqualified type was actually
7409 // qualified __strong.
7410 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7411 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7412 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7413
7414 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7415 return QualType();
7416
7417 if (GC_L == Qualifiers::Strong)
7418 return LHS;
7419 if (GC_R == Qualifiers::Strong)
7420 return RHS;
7421 return QualType();
7422 }
7423
7424 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7425 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7426 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7427 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7428 if (ResQT == LHSBaseQT)
7429 return LHS;
7430 if (ResQT == RHSBaseQT)
7431 return RHS;
7432 }
7433 return QualType();
7434}
7435
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007436//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007437// Integer Predicates
7438//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007439
Jay Foad39c79802011-01-12 09:06:06 +00007440unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007441 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007442 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007443 if (T->isBooleanType())
7444 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007445 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007446 return (unsigned)getTypeSize(T);
7447}
7448
Abramo Bagnara13640492012-09-09 10:21:24 +00007449QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007450 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007451
7452 // Turn <4 x signed int> -> <4 x unsigned int>
7453 if (const VectorType *VTy = T->getAs<VectorType>())
7454 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007455 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007456
7457 // For enums, we return the unsigned version of the base type.
7458 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007459 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007460
7461 const BuiltinType *BTy = T->getAs<BuiltinType>();
7462 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007463 switch (BTy->getKind()) {
7464 case BuiltinType::Char_S:
7465 case BuiltinType::SChar:
7466 return UnsignedCharTy;
7467 case BuiltinType::Short:
7468 return UnsignedShortTy;
7469 case BuiltinType::Int:
7470 return UnsignedIntTy;
7471 case BuiltinType::Long:
7472 return UnsignedLongTy;
7473 case BuiltinType::LongLong:
7474 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007475 case BuiltinType::Int128:
7476 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007477 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007478 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007479 }
7480}
7481
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007482ASTMutationListener::~ASTMutationListener() { }
7483
Richard Smith1fa5d642013-05-11 05:45:24 +00007484void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7485 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007486
7487//===----------------------------------------------------------------------===//
7488// Builtin Type Computation
7489//===----------------------------------------------------------------------===//
7490
7491/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007492/// pointer over the consumed characters. This returns the resultant type. If
7493/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7494/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7495/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007496///
7497/// RequiresICE is filled in on return to indicate whether the value is required
7498/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007499static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007500 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007501 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007502 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007503 // Modifiers.
7504 int HowLong = 0;
7505 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007506 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007507
Chris Lattnerdc226c22010-10-01 22:42:38 +00007508 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007509 bool Done = false;
7510 while (!Done) {
7511 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007512 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007513 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007514 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007515 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007516 case 'S':
7517 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7518 assert(!Signed && "Can't use 'S' modifier multiple times!");
7519 Signed = true;
7520 break;
7521 case 'U':
7522 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7523 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7524 Unsigned = true;
7525 break;
7526 case 'L':
7527 assert(HowLong <= 2 && "Can't have LLLL modifier");
7528 ++HowLong;
7529 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007530 case 'W':
7531 // This modifier represents int64 type.
7532 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7533 switch (Context.getTargetInfo().getInt64Type()) {
7534 default:
7535 llvm_unreachable("Unexpected integer type");
7536 case TargetInfo::SignedLong:
7537 HowLong = 1;
7538 break;
7539 case TargetInfo::SignedLongLong:
7540 HowLong = 2;
7541 break;
7542 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007543 }
7544 }
7545
7546 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007547
Chris Lattnerecd79c62009-06-14 00:45:47 +00007548 // Read the base type.
7549 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007550 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007551 case 'v':
7552 assert(HowLong == 0 && !Signed && !Unsigned &&
7553 "Bad modifiers used with 'v'!");
7554 Type = Context.VoidTy;
7555 break;
Jack Carter24bef982013-08-15 15:16:57 +00007556 case 'h':
7557 assert(HowLong == 0 && !Signed && !Unsigned &&
7558 "Bad modifiers used with 'f'!");
7559 Type = Context.HalfTy;
7560 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007561 case 'f':
7562 assert(HowLong == 0 && !Signed && !Unsigned &&
7563 "Bad modifiers used with 'f'!");
7564 Type = Context.FloatTy;
7565 break;
7566 case 'd':
7567 assert(HowLong < 2 && !Signed && !Unsigned &&
7568 "Bad modifiers used with 'd'!");
7569 if (HowLong)
7570 Type = Context.LongDoubleTy;
7571 else
7572 Type = Context.DoubleTy;
7573 break;
7574 case 's':
7575 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7576 if (Unsigned)
7577 Type = Context.UnsignedShortTy;
7578 else
7579 Type = Context.ShortTy;
7580 break;
7581 case 'i':
7582 if (HowLong == 3)
7583 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7584 else if (HowLong == 2)
7585 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7586 else if (HowLong == 1)
7587 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7588 else
7589 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7590 break;
7591 case 'c':
7592 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7593 if (Signed)
7594 Type = Context.SignedCharTy;
7595 else if (Unsigned)
7596 Type = Context.UnsignedCharTy;
7597 else
7598 Type = Context.CharTy;
7599 break;
7600 case 'b': // boolean
7601 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7602 Type = Context.BoolTy;
7603 break;
7604 case 'z': // size_t.
7605 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7606 Type = Context.getSizeType();
7607 break;
7608 case 'F':
7609 Type = Context.getCFConstantStringType();
7610 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007611 case 'G':
7612 Type = Context.getObjCIdType();
7613 break;
7614 case 'H':
7615 Type = Context.getObjCSelType();
7616 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007617 case 'M':
7618 Type = Context.getObjCSuperType();
7619 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 case 'a':
7621 Type = Context.getBuiltinVaListType();
7622 assert(!Type.isNull() && "builtin va list type not initialized!");
7623 break;
7624 case 'A':
7625 // This is a "reference" to a va_list; however, what exactly
7626 // this means depends on how va_list is defined. There are two
7627 // different kinds of va_list: ones passed by value, and ones
7628 // passed by reference. An example of a by-value va_list is
7629 // x86, where va_list is a char*. An example of by-ref va_list
7630 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7631 // we want this argument to be a char*&; for x86-64, we want
7632 // it to be a __va_list_tag*.
7633 Type = Context.getBuiltinVaListType();
7634 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007635 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007636 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007637 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007638 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007639 break;
7640 case 'V': {
7641 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007642 unsigned NumElements = strtoul(Str, &End, 10);
7643 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007644 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007645
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007646 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7647 RequiresICE, false);
7648 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007649
7650 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007651 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007652 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007653 break;
7654 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007655 case 'E': {
7656 char *End;
7657
7658 unsigned NumElements = strtoul(Str, &End, 10);
7659 assert(End != Str && "Missing vector size");
7660
7661 Str = End;
7662
7663 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7664 false);
7665 Type = Context.getExtVectorType(ElementType, NumElements);
7666 break;
7667 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007668 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007669 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7670 false);
7671 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007672 Type = Context.getComplexType(ElementType);
7673 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007674 }
7675 case 'Y' : {
7676 Type = Context.getPointerDiffType();
7677 break;
7678 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007679 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007680 Type = Context.getFILEType();
7681 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007682 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007683 return QualType();
7684 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007685 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007686 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007687 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007688 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007689 else
7690 Type = Context.getjmp_bufType();
7691
Mike Stump2adb4da2009-07-28 23:47:15 +00007692 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007693 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007694 return QualType();
7695 }
7696 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007697 case 'K':
7698 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7699 Type = Context.getucontext_tType();
7700
7701 if (Type.isNull()) {
7702 Error = ASTContext::GE_Missing_ucontext;
7703 return QualType();
7704 }
7705 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007706 case 'p':
7707 Type = Context.getProcessIDType();
7708 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007709 }
Mike Stump11289f42009-09-09 15:08:12 +00007710
Chris Lattnerdc226c22010-10-01 22:42:38 +00007711 // If there are modifiers and if we're allowed to parse them, go for it.
7712 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007713 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007714 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007715 default: Done = true; --Str; break;
7716 case '*':
7717 case '&': {
7718 // Both pointers and references can have their pointee types
7719 // qualified with an address space.
7720 char *End;
7721 unsigned AddrSpace = strtoul(Str, &End, 10);
7722 if (End != Str && AddrSpace != 0) {
7723 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7724 Str = End;
7725 }
7726 if (c == '*')
7727 Type = Context.getPointerType(Type);
7728 else
7729 Type = Context.getLValueReferenceType(Type);
7730 break;
7731 }
7732 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7733 case 'C':
7734 Type = Type.withConst();
7735 break;
7736 case 'D':
7737 Type = Context.getVolatileType(Type);
7738 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007739 case 'R':
7740 Type = Type.withRestrict();
7741 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007742 }
7743 }
Chris Lattner84733392010-10-01 07:13:18 +00007744
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007745 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007746 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007747
Chris Lattnerecd79c62009-06-14 00:45:47 +00007748 return Type;
7749}
7750
7751/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007752QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007753 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007754 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007755 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007756
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007757 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007758
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007759 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007760 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007761 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7762 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007763 if (Error != GE_None)
7764 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007765
7766 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7767
Chris Lattnerecd79c62009-06-14 00:45:47 +00007768 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007769 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007770 if (Error != GE_None)
7771 return QualType();
7772
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007773 // If this argument is required to be an IntegerConstantExpression and the
7774 // caller cares, fill in the bitmask we return.
7775 if (RequiresICE && IntegerConstantArgs)
7776 *IntegerConstantArgs |= 1 << ArgTypes.size();
7777
Chris Lattnerecd79c62009-06-14 00:45:47 +00007778 // Do array -> pointer decay. The builtin should use the decayed type.
7779 if (Ty->isArrayType())
7780 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007781
Chris Lattnerecd79c62009-06-14 00:45:47 +00007782 ArgTypes.push_back(Ty);
7783 }
7784
7785 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7786 "'.' should only occur at end of builtin type list!");
7787
Reid Kleckner78af0702013-08-27 23:08:25 +00007788 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007789 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7790
7791 bool Variadic = (TypeStr[0] == '.');
7792
7793 // We really shouldn't be making a no-proto type here, especially in C++.
7794 if (ArgTypes.empty() && Variadic)
7795 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007796
John McCalldb40c7f2010-12-14 08:05:40 +00007797 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007798 EPI.ExtInfo = EI;
7799 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007800
Jordan Rose5c382722013-03-08 21:51:21 +00007801 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007802}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007803
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007804GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007805 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007806 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007807
Rafael Espindola3ae00052013-05-13 00:12:11 +00007808 GVALinkage External = GVA_StrongExternal;
7809 switch (FD->getTemplateSpecializationKind()) {
7810 case TSK_Undeclared:
7811 case TSK_ExplicitSpecialization:
7812 External = GVA_StrongExternal;
7813 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007814
Rafael Espindola3ae00052013-05-13 00:12:11 +00007815 case TSK_ExplicitInstantiationDefinition:
7816 return GVA_ExplicitTemplateInstantiation;
7817
7818 case TSK_ExplicitInstantiationDeclaration:
7819 case TSK_ImplicitInstantiation:
7820 External = GVA_TemplateInstantiation;
7821 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007822 }
7823
7824 if (!FD->isInlined())
7825 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007826
Alp Tokerbfa39342014-01-14 12:51:41 +00007827 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007828 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007829 // GNU or C99 inline semantics. Determine whether this symbol should be
7830 // externally visible.
7831 if (FD->isInlineDefinitionExternallyVisible())
7832 return External;
7833
7834 // C99 inline semantics, where the symbol is not externally visible.
7835 return GVA_C99Inline;
7836 }
7837
7838 // C++0x [temp.explicit]p9:
7839 // [ Note: The intent is that an inline function that is the subject of
7840 // an explicit instantiation declaration will still be implicitly
7841 // instantiated when used so that the body can be considered for
7842 // inlining, but that no out-of-line copy of the inline function would be
7843 // generated in the translation unit. -- end note ]
7844 if (FD->getTemplateSpecializationKind()
7845 == TSK_ExplicitInstantiationDeclaration)
7846 return GVA_C99Inline;
7847
7848 return GVA_CXXInline;
7849}
7850
7851GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007852 if (!VD->isExternallyVisible())
7853 return GVA_Internal;
7854
Richard Smith8809a0c2013-09-27 20:14:12 +00007855 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007856 case TSK_Undeclared:
7857 case TSK_ExplicitSpecialization:
7858 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007859
Rafael Espindola3ae00052013-05-13 00:12:11 +00007860 case TSK_ExplicitInstantiationDeclaration:
7861 llvm_unreachable("Variable should not be instantiated");
7862 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007863
Rafael Espindola3ae00052013-05-13 00:12:11 +00007864 case TSK_ExplicitInstantiationDefinition:
7865 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007866
Rafael Espindola3ae00052013-05-13 00:12:11 +00007867 case TSK_ImplicitInstantiation:
7868 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007869 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007870
7871 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007872}
7873
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007874bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007875 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7876 if (!VD->isFileVarDecl())
7877 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007878 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7879 // We never need to emit an uninstantiated function template.
7880 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7881 return false;
7882 } else
7883 return false;
7884
7885 // If this is a member of a class template, we do not need to emit it.
7886 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007887 return false;
7888
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007889 // Weak references don't produce any output by themselves.
7890 if (D->hasAttr<WeakRefAttr>())
7891 return false;
7892
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007893 // Aliases and used decls are required.
7894 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7895 return true;
7896
7897 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7898 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007899 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007900 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007901
7902 // Constructors and destructors are required.
7903 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7904 return true;
7905
John McCall6bd2a892013-01-25 22:31:03 +00007906 // The key function for a class is required. This rule only comes
7907 // into play when inline functions can be key functions, though.
7908 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7909 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7910 const CXXRecordDecl *RD = MD->getParent();
7911 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7912 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7913 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7914 return true;
7915 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007916 }
7917 }
7918
7919 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7920
7921 // static, static inline, always_inline, and extern inline functions can
7922 // always be deferred. Normal inline functions can be deferred in C99/C++.
7923 // Implicit template instantiations can also be deferred in C++.
7924 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007925 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007926 return false;
7927 return true;
7928 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007929
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007930 const VarDecl *VD = cast<VarDecl>(D);
7931 assert(VD->isFileVarDecl() && "Expected file scoped var");
7932
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007933 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7934 return false;
7935
Richard Smitha0e5e542012-11-12 21:38:00 +00007936 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007937 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007938 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7939 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007940
Richard Smitha0e5e542012-11-12 21:38:00 +00007941 // Variables that have destruction with side-effects are required.
7942 if (VD->getType().isDestructedType())
7943 return true;
7944
7945 // Variables that have initialization with side-effects are required.
7946 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7947 return true;
7948
7949 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007950}
Charles Davis53c59df2010-08-16 03:33:14 +00007951
Reid Kleckner78af0702013-08-27 23:08:25 +00007952CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7953 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007954 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007955 if (IsCXXMethod)
7956 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007957
Reid Kleckner78af0702013-08-27 23:08:25 +00007958 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007959}
7960
Jay Foad39c79802011-01-12 09:06:06 +00007961bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007962 // Pass through to the C++ ABI object
7963 return ABI->isNearlyEmpty(RD);
7964}
7965
Reid Kleckner96f8f932014-02-05 17:27:08 +00007966VTableContextBase *ASTContext::getVTableContext() {
7967 if (!VTContext.get()) {
7968 if (Target->getCXXABI().isMicrosoft())
7969 VTContext.reset(new MicrosoftVTableContext(*this));
7970 else
7971 VTContext.reset(new ItaniumVTableContext(*this));
7972 }
7973 return VTContext.get();
7974}
7975
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007976MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007977 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007978 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007979 case TargetCXXABI::GenericItanium:
7980 case TargetCXXABI::GenericARM:
7981 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007982 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007983 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007984 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007985 }
David Blaikie83d382b2011-09-23 05:06:16 +00007986 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007987}
7988
Charles Davis53c59df2010-08-16 03:33:14 +00007989CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007990
7991size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007992 return ASTRecordLayouts.getMemorySize() +
7993 llvm::capacity_in_bytes(ObjCLayouts) +
7994 llvm::capacity_in_bytes(KeyFunctions) +
7995 llvm::capacity_in_bytes(ObjCImpls) +
7996 llvm::capacity_in_bytes(BlockVarCopyInits) +
7997 llvm::capacity_in_bytes(DeclAttrs) +
7998 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7999 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8000 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8001 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8002 llvm::capacity_in_bytes(OverriddenMethods) +
8003 llvm::capacity_in_bytes(Types) +
8004 llvm::capacity_in_bytes(VariableArrayTypes) +
8005 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008006}
Ted Kremenek540017e2011-10-06 05:00:56 +00008007
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008008/// getIntTypeForBitwidth -
8009/// sets integer QualTy according to specified details:
8010/// bitwidth, signed/unsigned.
8011/// Returns empty type if there is no appropriate target types.
8012QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8013 unsigned Signed) const {
8014 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8015 CanQualType QualTy = getFromTargetType(Ty);
8016 if (!QualTy && DestWidth == 128)
8017 return Signed ? Int128Ty : UnsignedInt128Ty;
8018 return QualTy;
8019}
8020
8021/// getRealTypeForBitwidth -
8022/// sets floating point QualTy according to specified bitwidth.
8023/// Returns empty type if there is no appropriate target types.
8024QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8025 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8026 switch (Ty) {
8027 case TargetInfo::Float:
8028 return FloatTy;
8029 case TargetInfo::Double:
8030 return DoubleTy;
8031 case TargetInfo::LongDouble:
8032 return LongDoubleTy;
8033 case TargetInfo::NoFloat:
8034 return QualType();
8035 }
8036
8037 llvm_unreachable("Unhandled TargetInfo::RealType value");
8038}
8039
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008040void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8041 if (Number > 1)
8042 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008043}
8044
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008045unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8046 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8047 MangleNumbers.find(ND);
8048 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008049}
8050
David Majnemer2206bf52014-03-05 08:57:59 +00008051void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8052 if (Number > 1)
8053 StaticLocalNumbers[VD] = Number;
8054}
8055
8056unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8057 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8058 StaticLocalNumbers.find(VD);
8059 return I != StaticLocalNumbers.end() ? I->second : 1;
8060}
8061
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008062MangleNumberingContext &
8063ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008064 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8065 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8066 if (!MCtx)
8067 MCtx = createMangleNumberingContext();
8068 return *MCtx;
8069}
8070
8071MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8072 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008073}
8074
Ted Kremenek540017e2011-10-06 05:00:56 +00008075void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8076 ParamIndices[D] = index;
8077}
8078
8079unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8080 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8081 assert(I != ParamIndices.end() &&
8082 "ParmIndices lacks entry set by ParmVarDecl");
8083 return I->second;
8084}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008085
Richard Smithe6c01442013-06-05 00:46:14 +00008086APValue *
8087ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8088 bool MayCreate) {
8089 assert(E && E->getStorageDuration() == SD_Static &&
8090 "don't need to cache the computed value for this temporary");
8091 if (MayCreate)
8092 return &MaterializedTemporaryValues[E];
8093
8094 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8095 MaterializedTemporaryValues.find(E);
8096 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8097}
8098
Fariborz Jahanian615de762013-05-28 17:37:39 +00008099bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8100 const llvm::Triple &T = getTargetInfo().getTriple();
8101 if (!T.isOSDarwin())
8102 return false;
8103
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008104 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8105 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8106 return false;
8107
Fariborz Jahanian615de762013-05-28 17:37:39 +00008108 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8109 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8110 uint64_t Size = sizeChars.getQuantity();
8111 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8112 unsigned Align = alignChars.getQuantity();
8113 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8114 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8115}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008116
8117namespace {
8118
8119 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8120 /// parents as defined by the \c RecursiveASTVisitor.
8121 ///
8122 /// Note that the relationship described here is purely in terms of AST
8123 /// traversal - there are other relationships (for example declaration context)
8124 /// in the AST that are better modeled by special matchers.
8125 ///
8126 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8127 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8128
8129 public:
8130 /// \brief Builds and returns the translation unit's parent map.
8131 ///
8132 /// The caller takes ownership of the returned \c ParentMap.
8133 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8134 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8135 Visitor.TraverseDecl(&TU);
8136 return Visitor.Parents;
8137 }
8138
8139 private:
8140 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8141
8142 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8143 }
8144
8145 bool shouldVisitTemplateInstantiations() const {
8146 return true;
8147 }
8148 bool shouldVisitImplicitCode() const {
8149 return true;
8150 }
8151 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8152 // are not triggered during data recursion.
8153 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8154 return false;
8155 }
8156
8157 template <typename T>
8158 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8159 if (Node == NULL)
8160 return true;
8161 if (ParentStack.size() > 0)
8162 // FIXME: Currently we add the same parent multiple times, for example
8163 // when we visit all subexpressions of template instantiations; this is
8164 // suboptimal, bug benign: the only way to visit those is with
8165 // hasAncestor / hasParent, and those do not create new matches.
8166 // The plan is to enable DynTypedNode to be storable in a map or hash
8167 // map. The main problem there is to implement hash functions /
8168 // comparison operators for all types that DynTypedNode supports that
8169 // do not have pointer identity.
8170 (*Parents)[Node].push_back(ParentStack.back());
8171 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8172 bool Result = (this ->* traverse) (Node);
8173 ParentStack.pop_back();
8174 return Result;
8175 }
8176
8177 bool TraverseDecl(Decl *DeclNode) {
8178 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8179 }
8180
8181 bool TraverseStmt(Stmt *StmtNode) {
8182 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8183 }
8184
8185 ASTContext::ParentMap *Parents;
8186 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8187
8188 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8189 };
8190
8191} // end namespace
8192
8193ASTContext::ParentVector
8194ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8195 assert(Node.getMemoizationData() &&
8196 "Invariant broken: only nodes that support memoization may be "
8197 "used in the parent map.");
8198 if (!AllParents) {
8199 // We always need to run over the whole translation unit, as
8200 // hasAncestor can escape any subtree.
8201 AllParents.reset(
8202 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8203 }
8204 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8205 if (I == AllParents->end()) {
8206 return ParentVector();
8207 }
8208 return I->second;
8209}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008210
8211bool
8212ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8213 const ObjCMethodDecl *MethodImpl) {
8214 // No point trying to match an unavailable/deprecated mothod.
8215 if (MethodDecl->hasAttr<UnavailableAttr>()
8216 || MethodDecl->hasAttr<DeprecatedAttr>())
8217 return false;
8218 if (MethodDecl->getObjCDeclQualifier() !=
8219 MethodImpl->getObjCDeclQualifier())
8220 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008221 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008222 return false;
8223
8224 if (MethodDecl->param_size() != MethodImpl->param_size())
8225 return false;
8226
8227 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8228 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8229 EF = MethodDecl->param_end();
8230 IM != EM && IF != EF; ++IM, ++IF) {
8231 const ParmVarDecl *DeclVar = (*IF);
8232 const ParmVarDecl *ImplVar = (*IM);
8233 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8234 return false;
8235 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8236 return false;
8237 }
8238 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8239
8240}