blob: 3e0d6d1144bd981cc851daedbb3820a643a15466 [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();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000687 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000688 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000690 return CreateMicrosoftCXXABI(*this);
691 }
David Blaikie8a40f702012-01-17 06:56:22 +0000692 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000693}
694
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 const LangOptions &LOpts) {
697 if (LOpts.FakeAddressSpaceMap) {
698 // The fake address space map must have a distinct entry for each
699 // language-specific address space.
700 static const unsigned FakeAddrSpaceMap[] = {
701 1, // opencl_global
702 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000703 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000704 4, // opencl_generic
705 5, // cuda_device
706 6, // cuda_constant
707 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 }
713}
714
David Tweed31d09b02013-09-13 12:04:22 +0000715static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
716 const LangOptions &LangOpts) {
717 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000718 case LangOptions::ASMM_Target:
719 return TI.useAddressSpaceMapMangling();
720 case LangOptions::ASMM_On:
721 return true;
722 case LangOptions::ASMM_Off:
723 return false;
724 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000725 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000726}
727
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000728ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000729 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000730 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
732 DependentTemplateSpecializationTypes(this_()),
733 SubstTemplateTemplateParmPacks(this_()),
734 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
735 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000736 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
737 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
738 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000739 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
740 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
741 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
742 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000743 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
744 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000745 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000746 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
747 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
748 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
749 Comments(SM), CommentsLoaded(false),
750 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751 TUDecl = TranslationUnitDecl::Create(*this);
752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000755 ReleaseParentMapEntries();
756
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000757 // Release the DenseMaps associated with DeclContext objects.
758 // FIXME: Is this the ideal solution?
759 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000760
Manuel Klimeka7328992013-06-03 13:51:33 +0000761 // Call all of the deallocation functions on all of their targets.
762 for (DeallocationMap::const_iterator I = Deallocations.begin(),
763 E = Deallocations.end(); I != E; ++I)
764 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
765 (I->first)((I->second)[J]);
766
Ted Kremenek076baeb2010-06-08 23:00:58 +0000767 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000768 // because they can contain DenseMaps.
769 for (llvm::DenseMap<const ObjCContainerDecl*,
770 const ASTRecordLayout*>::iterator
771 I = ObjCLayouts.begin(), E = ObjCLayouts.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
Ted Kremenek076baeb2010-06-08 23:00:58 +0000776 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
777 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000782
783 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
784 AEnd = DeclAttrs.end();
785 A != AEnd; ++A)
786 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000787
David Majnemere694f3e2015-08-14 14:43:50 +0000788 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
789 MaterializedTemporaryValues)
790 MTVPair.second->~APValue();
791
Reid Kleckner588c9372014-02-19 23:44:52 +0000792 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000793}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000794
Manuel Klimek95403e62014-05-21 13:28:59 +0000795void ASTContext::ReleaseParentMapEntries() {
796 if (!AllParents) return;
797 for (const auto &Entry : *AllParents) {
798 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
799 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
800 } else {
801 assert(Entry.second.is<ParentVector *>());
802 delete Entry.second.get<ParentVector *>();
803 }
804 }
805}
806
Douglas Gregor1a809332010-05-23 18:26:36 +0000807void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000808 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000809}
810
Mike Stump11289f42009-09-09 15:08:12 +0000811void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000812ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
813 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000814}
815
Chris Lattner4eb445d2007-01-26 01:27:23 +0000816void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000817 llvm::errs() << "\n*** AST Context Stats:\n";
818 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000819
Douglas Gregora30d0462009-05-26 14:40:08 +0000820 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000821#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000822#define ABSTRACT_TYPE(Name, Parent)
823#include "clang/AST/TypeNodes.def"
824 0 // Extra
825 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000826
Chris Lattner4eb445d2007-01-26 01:27:23 +0000827 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
828 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000829 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000830 }
831
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 unsigned Idx = 0;
833 unsigned TotalBytes = 0;
834#define TYPE(Name, Parent) \
835 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << " " << counts[Idx] << " " << #Name \
837 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000838 TotalBytes += counts[Idx] * sizeof(Name##Type); \
839 ++Idx;
840#define ABSTRACT_TYPE(Name, Parent)
841#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chandler Carruth3c147a72011-07-04 05:32:14 +0000843 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
844
Douglas Gregor7454c562010-07-02 20:37:36 +0000845 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
847 << NumImplicitDefaultConstructors
848 << " implicit default constructors created\n";
849 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
850 << NumImplicitCopyConstructors
851 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
854 << NumImplicitMoveConstructors
855 << " implicit move constructors created\n";
856 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
857 << NumImplicitCopyAssignmentOperators
858 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
861 << NumImplicitMoveAssignmentOperators
862 << " implicit move assignment operators created\n";
863 llvm::errs() << NumImplicitDestructorsDeclared << "/"
864 << NumImplicitDestructors
865 << " implicit destructors created\n";
866
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000867 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000869 ExternalSource->PrintStats();
870 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000871
Douglas Gregor5b11d492010-07-25 17:53:33 +0000872 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000873}
874
Richard Smith42413142015-05-15 20:05:43 +0000875void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
876 bool NotifyListeners) {
877 if (NotifyListeners)
878 if (auto *Listener = getASTMutationListener())
879 Listener->RedefinedHiddenDefinition(ND, M);
880
881 if (getLangOpts().ModulesLocalVisibility)
882 MergedDefModules[ND].push_back(M);
883 else
884 ND->setHidden(false);
885}
886
887void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
888 auto It = MergedDefModules.find(ND);
889 if (It == MergedDefModules.end())
890 return;
891
892 auto &Merged = It->second;
893 llvm::DenseSet<Module*> Found;
894 for (Module *&M : Merged)
895 if (!Found.insert(M).second)
896 M = nullptr;
897 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
898}
899
Richard Smithf19e1272015-03-07 00:04:49 +0000900ExternCContextDecl *ASTContext::getExternCContextDecl() const {
901 if (!ExternCContext)
902 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
903
904 return ExternCContext;
905}
906
Alp Toker2dea15b2013-12-17 01:22:38 +0000907RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
908 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000909 SourceLocation Loc;
910 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000911 if (getLangOpts().CPlusPlus)
912 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
913 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000914 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000915 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
916 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000917 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000918 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
919 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000920 return NewDecl;
921}
922
923TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
924 StringRef Name) const {
925 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
926 TypedefDecl *NewDecl = TypedefDecl::Create(
927 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
928 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
929 NewDecl->setImplicit();
930 return NewDecl;
931}
932
Douglas Gregor801c99d2011-08-12 06:49:56 +0000933TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 if (!Int128Decl)
935 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000936 return Int128Decl;
937}
938
939TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000940 if (!UInt128Decl)
941 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000942 return UInt128Decl;
943}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000944
Nico Webere1687c52013-06-20 21:44:55 +0000945TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000946 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000947 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000948 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000949
Nico Webere1687c52013-06-20 21:44:55 +0000950 return Float128StubDecl;
951}
952
John McCall48f2d582009-10-23 23:03:21 +0000953void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000954 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000955 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000956 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000957}
958
Douglas Gregore8bbc122011-09-02 00:18:52 +0000959void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
960 assert((!this->Target || this->Target == &Target) &&
961 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000962 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000963
Douglas Gregore8bbc122011-09-02 00:18:52 +0000964 this->Target = &Target;
965
966 ABI.reset(createCXXABI(Target));
967 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000968 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000969
Chris Lattner970e54e2006-11-12 00:37:36 +0000970 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000971 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattner970e54e2006-11-12 00:37:36 +0000973 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000974 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000975 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000976 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000977 InitBuiltinType(CharTy, BuiltinType::Char_S);
978 else
979 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000980 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000981 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
982 InitBuiltinType(ShortTy, BuiltinType::Short);
983 InitBuiltinType(IntTy, BuiltinType::Int);
984 InitBuiltinType(LongTy, BuiltinType::Long);
985 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattner970e54e2006-11-12 00:37:36 +0000987 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000988 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
989 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
990 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
991 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
992 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chris Lattner970e54e2006-11-12 00:37:36 +0000994 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000995 InitBuiltinType(FloatTy, BuiltinType::Float);
996 InitBuiltinType(DoubleTy, BuiltinType::Double);
997 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000998
Chris Lattnerf122cef2009-04-30 02:43:43 +0000999 // GNU extension, 128-bit integers.
1000 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1001 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1002
Hans Wennborg0d81e012013-05-10 10:08:40 +00001003 // C++ 3.9.1p5
1004 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1005 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1006 else // -fshort-wchar makes wchar_t be unsigned.
1007 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1008 if (LangOpts.CPlusPlus && LangOpts.WChar)
1009 WideCharTy = WCharTy;
1010 else {
1011 // C99 (or C++ using -fno-wchar).
1012 WideCharTy = getFromTargetType(Target.getWCharType());
1013 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001014
James Molloy36365542012-05-04 10:55:22 +00001015 WIntTy = getFromTargetType(Target.getWIntType());
1016
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001017 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1018 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1019 else // C99
1020 Char16Ty = getFromTargetType(Target.getChar16Type());
1021
1022 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1023 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1024 else // C99
1025 Char32Ty = getFromTargetType(Target.getChar32Type());
1026
Douglas Gregor4619e432008-12-05 23:32:09 +00001027 // Placeholder type for type-dependent expressions whose type is
1028 // completely unknown. No code should ever check a type against
1029 // DependentTy and users should never see it; however, it is here to
1030 // help diagnose failures to properly check for type-dependent
1031 // expressions.
1032 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001033
John McCall36e7fe32010-10-12 00:20:44 +00001034 // Placeholder type for functions.
1035 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1036
John McCall0009fcc2011-04-26 20:42:42 +00001037 // Placeholder type for bound members.
1038 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1039
John McCall526ab472011-10-25 17:37:35 +00001040 // Placeholder type for pseudo-objects.
1041 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1042
John McCall31996342011-04-07 08:22:57 +00001043 // "any" type; useful for debugger-like clients.
1044 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1045
John McCall8a6b59a2011-10-17 18:09:15 +00001046 // Placeholder type for unbridged ARC casts.
1047 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1048
Eli Friedman34866c72012-08-31 00:14:07 +00001049 // Placeholder type for builtin functions.
1050 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1051
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001052 // Placeholder type for OMP array sections.
1053 if (LangOpts.OpenMP)
1054 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1055
Chris Lattner970e54e2006-11-12 00:37:36 +00001056 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001057 FloatComplexTy = getComplexType(FloatTy);
1058 DoubleComplexTy = getComplexType(DoubleTy);
1059 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001061 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001062 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1063 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001064 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001065
1066 if (LangOpts.OpenCL) {
1067 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1068 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1069 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1070 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1071 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001072 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1073 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1074 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1075 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1076 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1077 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1078 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001079 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001080
Guy Benyei61054192013-02-07 10:55:47 +00001081 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001082 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001083 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1084 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1085 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1086 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001087 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001088
1089 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001090 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1091 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001092
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001093 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001094
1095 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001096
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001097 // void * type
1098 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001099
1100 // nullptr type (C++0x 2.14.7)
1101 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001102
1103 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1104 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001105
1106 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001107 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001108}
1109
David Blaikie9c902b52011-09-25 23:23:43 +00001110DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001111 return SourceMgr.getDiagnostics();
1112}
1113
Douglas Gregor561eceb2010-08-30 16:49:28 +00001114AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1115 AttrVec *&Result = DeclAttrs[D];
1116 if (!Result) {
1117 void *Mem = Allocate(sizeof(AttrVec));
1118 Result = new (Mem) AttrVec;
1119 }
1120
1121 return *Result;
1122}
1123
1124/// \brief Erase the attributes corresponding to the given declaration.
1125void ASTContext::eraseDeclAttrs(const Decl *D) {
1126 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1127 if (Pos != DeclAttrs.end()) {
1128 Pos->second->~AttrVec();
1129 DeclAttrs.erase(Pos);
1130 }
1131}
1132
Larisse Voufo39a1e502013-08-06 01:03:05 +00001133// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001134MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001135ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001136 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001137 return getTemplateOrSpecializationInfo(Var)
1138 .dyn_cast<MemberSpecializationInfo *>();
1139}
1140
1141ASTContext::TemplateOrSpecializationInfo
1142ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1143 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1144 TemplateOrInstantiation.find(Var);
1145 if (Pos == TemplateOrInstantiation.end())
1146 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001147
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001148 return Pos->second;
1149}
1150
Mike Stump11289f42009-09-09 15:08:12 +00001151void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001152ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001153 TemplateSpecializationKind TSK,
1154 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001155 assert(Inst->isStaticDataMember() && "Not a static data member");
1156 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001157 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1158 Tmpl, TSK, PointOfInstantiation));
1159}
1160
1161void
1162ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1163 TemplateOrSpecializationInfo TSI) {
1164 assert(!TemplateOrInstantiation[Inst] &&
1165 "Already noted what the variable was instantiated from");
1166 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001167}
1168
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001169FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1170 const FunctionDecl *FD){
1171 assert(FD && "Specialization is 0");
1172 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001173 = ClassScopeSpecializationPattern.find(FD);
1174 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001175 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001176
1177 return Pos->second;
1178}
1179
1180void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1181 FunctionDecl *Pattern) {
1182 assert(FD && "Specialization is 0");
1183 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001184 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001185}
1186
John McCalle61f2ba2009-11-18 02:36:19 +00001187NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001188ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001189 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001190 = InstantiatedFromUsingDecl.find(UUD);
1191 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001192 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001193
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001194 return Pos->second;
1195}
1196
1197void
John McCallb96ec562009-12-04 22:46:56 +00001198ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1199 assert((isa<UsingDecl>(Pattern) ||
1200 isa<UnresolvedUsingValueDecl>(Pattern) ||
1201 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1202 "pattern decl is not a using decl");
1203 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1204 InstantiatedFromUsingDecl[Inst] = Pattern;
1205}
1206
1207UsingShadowDecl *
1208ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1209 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1210 = InstantiatedFromUsingShadowDecl.find(Inst);
1211 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001212 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001213
1214 return Pos->second;
1215}
1216
1217void
1218ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1219 UsingShadowDecl *Pattern) {
1220 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1221 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001222}
1223
Anders Carlsson5da84842009-09-01 04:26:58 +00001224FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1225 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1226 = InstantiatedFromUnnamedFieldDecl.find(Field);
1227 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001228 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001229
Anders Carlsson5da84842009-09-01 04:26:58 +00001230 return Pos->second;
1231}
1232
1233void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1234 FieldDecl *Tmpl) {
1235 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1236 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1237 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1238 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001239
Anders Carlsson5da84842009-09-01 04:26:58 +00001240 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1241}
1242
Douglas Gregor832940b2010-03-02 23:58:15 +00001243ASTContext::overridden_cxx_method_iterator
1244ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1245 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001246 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001247 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001248 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001249
1250 return Pos->second.begin();
1251}
1252
1253ASTContext::overridden_cxx_method_iterator
1254ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1255 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001256 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001257 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001258 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001259
1260 return Pos->second.end();
1261}
1262
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001263unsigned
1264ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1265 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001266 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001267 if (Pos == OverriddenMethods.end())
1268 return 0;
1269
1270 return Pos->second.size();
1271}
1272
Douglas Gregor832940b2010-03-02 23:58:15 +00001273void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1274 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001275 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001276 OverriddenMethods[Method].push_back(Overridden);
1277}
1278
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001279void ASTContext::getOverriddenMethods(
1280 const NamedDecl *D,
1281 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001282 assert(D);
1283
1284 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001285 Overridden.append(overridden_methods_begin(CXXMethod),
1286 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001287 return;
1288 }
1289
1290 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1291 if (!Method)
1292 return;
1293
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001294 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1295 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001296 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001297}
1298
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001299void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1300 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1301 assert(!Import->isFromASTFile() && "Non-local import declaration");
1302 if (!FirstLocalImport) {
1303 FirstLocalImport = Import;
1304 LastLocalImport = Import;
1305 return;
1306 }
1307
1308 LastLocalImport->NextLocalImport = Import;
1309 LastLocalImport = Import;
1310}
1311
Chris Lattner53cfe802007-07-18 17:52:12 +00001312//===----------------------------------------------------------------------===//
1313// Type Sizing and Analysis
1314//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001315
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001316/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1317/// scalar floating point type.
1318const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001319 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001320 assert(BT && "Not a floating point type!");
1321 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001322 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001323 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001324 case BuiltinType::Float: return Target->getFloatFormat();
1325 case BuiltinType::Double: return Target->getDoubleFormat();
1326 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001327 }
1328}
1329
Rafael Espindola71eccb32013-08-08 19:53:46 +00001330CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001331 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001332
John McCall94268702010-10-08 18:24:19 +00001333 bool UseAlignAttrOnly = false;
1334 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1335 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001336
John McCall94268702010-10-08 18:24:19 +00001337 // __attribute__((aligned)) can increase or decrease alignment
1338 // *except* on a struct or struct member, where it only increases
1339 // alignment unless 'packed' is also specified.
1340 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001341 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001342 // ignore that possibility; Sema should diagnose it.
1343 if (isa<FieldDecl>(D)) {
1344 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1345 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1346 } else {
1347 UseAlignAttrOnly = true;
1348 }
1349 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001350 else if (isa<FieldDecl>(D))
1351 UseAlignAttrOnly =
1352 D->hasAttr<PackedAttr>() ||
1353 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001354
John McCall4e819612011-01-20 07:57:12 +00001355 // If we're using the align attribute only, just ignore everything
1356 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001357 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001358 // do nothing
1359
John McCall94268702010-10-08 18:24:19 +00001360 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001361 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001362 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001363 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001364 T = RT->getPointeeType();
1365 else
1366 T = getPointerType(RT->getPointeeType());
1367 }
Richard Smithf6d70302014-06-10 23:34:28 +00001368 QualType BaseT = getBaseElementType(T);
1369 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001370 // Adjust alignments of declarations with array type by the
1371 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001372 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001373 unsigned MinWidth = Target->getLargeArrayMinWidth();
1374 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001375 if (isa<VariableArrayType>(arrayType))
1376 Align = std::max(Align, Target->getLargeArrayAlign());
1377 else if (isa<ConstantArrayType>(arrayType) &&
1378 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1379 Align = std::max(Align, Target->getLargeArrayAlign());
1380 }
John McCall33ddac02011-01-19 10:06:00 +00001381 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001382 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001383 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001384 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001385 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1386 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001387 }
John McCall4e819612011-01-20 07:57:12 +00001388
1389 // Fields can be subject to extra alignment constraints, like if
1390 // the field is packed, the struct is packed, or the struct has a
1391 // a max-field-alignment constraint (#pragma pack). So calculate
1392 // the actual alignment of the field within the struct, and then
1393 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001394 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1395 const RecordDecl *Parent = Field->getParent();
1396 // We can only produce a sensible answer if the record is valid.
1397 if (!Parent->isInvalidDecl()) {
1398 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001399
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001400 // Start with the record's overall alignment.
1401 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001402
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001403 // Use the GCD of that and the offset within the record.
1404 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1405 if (Offset > 0) {
1406 // Alignment is always a power of 2, so the GCD will be a power of 2,
1407 // which means we get to do this crazy thing instead of Euclid's.
1408 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1409 if (LowBitOfOffset < FieldAlign)
1410 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1411 }
1412
1413 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001414 }
Charles Davis3fc51072010-02-23 04:52:00 +00001415 }
Chris Lattner68061312009-01-24 21:53:27 +00001416 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001417
Ken Dyckcc56c542011-01-15 18:38:59 +00001418 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001419}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001420
John McCallf1249922012-08-21 04:10:00 +00001421// getTypeInfoDataSizeInChars - Return the size of a type, in
1422// chars. If the type is a record, its data size is returned. This is
1423// the size of the memcpy that's performed when assigning this type
1424// using a trivial copy/move assignment operator.
1425std::pair<CharUnits, CharUnits>
1426ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1427 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1428
1429 // In C++, objects can sometimes be allocated into the tail padding
1430 // of a base-class subobject. We decide whether that's possible
1431 // during class layout, so here we can just trust the layout results.
1432 if (getLangOpts().CPlusPlus) {
1433 if (const RecordType *RT = T->getAs<RecordType>()) {
1434 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1435 sizeAndAlign.first = layout.getDataSize();
1436 }
1437 }
1438
1439 return sizeAndAlign;
1440}
1441
Richard Trieu04d2d942013-05-14 21:59:17 +00001442/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1443/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1444std::pair<CharUnits, CharUnits>
1445static getConstantArrayInfoInChars(const ASTContext &Context,
1446 const ConstantArrayType *CAT) {
1447 std::pair<CharUnits, CharUnits> EltInfo =
1448 Context.getTypeInfoInChars(CAT->getElementType());
1449 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001450 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1451 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001452 "Overflow in array type char size evaluation");
1453 uint64_t Width = EltInfo.first.getQuantity() * Size;
1454 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001455 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1456 Context.getTargetInfo().getPointerWidth(0) == 64)
1457 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001458 return std::make_pair(CharUnits::fromQuantity(Width),
1459 CharUnits::fromQuantity(Align));
1460}
1461
John McCall87fe5d52010-05-20 01:18:31 +00001462std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001463ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001464 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1465 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001466 TypeInfo Info = getTypeInfo(T);
1467 return std::make_pair(toCharUnitsFromBits(Info.Width),
1468 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001469}
1470
1471std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001472ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001473 return getTypeInfoInChars(T.getTypePtr());
1474}
1475
David Majnemer34b57492014-07-30 01:30:47 +00001476bool ASTContext::isAlignmentRequired(const Type *T) const {
1477 return getTypeInfo(T).AlignIsRequired;
1478}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001479
David Majnemer34b57492014-07-30 01:30:47 +00001480bool ASTContext::isAlignmentRequired(QualType T) const {
1481 return isAlignmentRequired(T.getTypePtr());
1482}
1483
1484TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001485 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1486 if (I != MemoizedTypeInfo.end())
1487 return I->second;
1488
1489 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1490 TypeInfo TI = getTypeInfoImpl(T);
1491 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001492 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001493}
1494
1495/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1496/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001497///
1498/// FIXME: Pointers into different addr spaces could have different sizes and
1499/// alignment requirements: getPointerInfo should take an AddrSpace, this
1500/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001501TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1502 uint64_t Width = 0;
1503 unsigned Align = 8;
1504 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001505 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001506#define TYPE(Class, Base)
1507#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001508#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001509#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001510#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1511 case Type::Class: \
1512 assert(!T->isDependentType() && "should not see dependent types here"); \
1513 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001514#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001515 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001516
Chris Lattner355332d2007-07-13 22:27:08 +00001517 case Type::FunctionNoProto:
1518 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001519 // GCC extension: alignof(function) = 32 bits
1520 Width = 0;
1521 Align = 32;
1522 break;
1523
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001524 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001525 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001526 Width = 0;
1527 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1528 break;
1529
Steve Naroff5c131802007-08-30 01:06:46 +00001530 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001531 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001532
David Majnemer34b57492014-07-30 01:30:47 +00001533 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001534 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001535 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001536 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001537 Width = EltInfo.Width * Size;
1538 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001539 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1540 getTargetInfo().getPointerWidth(0) == 64)
1541 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001542 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001543 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001544 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001545 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001546 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001547 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1548 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001549 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001550 // If the alignment is not a power of 2, round up to the next power of 2.
1551 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001552 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001553 Align = llvm::NextPowerOf2(Align);
1554 Width = llvm::RoundUpToAlignment(Width, Align);
1555 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001556 // Adjust the alignment based on the target max.
1557 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1558 if (TargetVectorAlign && TargetVectorAlign < Align)
1559 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001560 break;
1561 }
Chris Lattner647fb222007-07-18 18:26:58 +00001562
Chris Lattner7570e9c2008-03-08 08:52:55 +00001563 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001564 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001565 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001566 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001567 // GCC extension: alignof(void) = 8 bits.
1568 Width = 0;
1569 Align = 8;
1570 break;
1571
Chris Lattner6a4f7452007-12-19 19:23:28 +00001572 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001573 Width = Target->getBoolWidth();
1574 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001575 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001576 case BuiltinType::Char_S:
1577 case BuiltinType::Char_U:
1578 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001579 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001580 Width = Target->getCharWidth();
1581 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001582 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001583 case BuiltinType::WChar_S:
1584 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001585 Width = Target->getWCharWidth();
1586 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001587 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001588 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001589 Width = Target->getChar16Width();
1590 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001591 break;
1592 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001593 Width = Target->getChar32Width();
1594 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001595 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001596 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001597 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001598 Width = Target->getShortWidth();
1599 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001600 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001601 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001602 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001603 Width = Target->getIntWidth();
1604 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001605 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001606 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001608 Width = Target->getLongWidth();
1609 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001610 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001611 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001612 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001613 Width = Target->getLongLongWidth();
1614 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001615 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001616 case BuiltinType::Int128:
1617 case BuiltinType::UInt128:
1618 Width = 128;
1619 Align = 128; // int128_t is 128-bit aligned on all targets.
1620 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001621 case BuiltinType::Half:
1622 Width = Target->getHalfWidth();
1623 Align = Target->getHalfAlign();
1624 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001625 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001626 Width = Target->getFloatWidth();
1627 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001628 break;
1629 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001630 Width = Target->getDoubleWidth();
1631 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001632 break;
1633 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001634 Width = Target->getLongDoubleWidth();
1635 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001636 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001637 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001638 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1639 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001640 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001641 case BuiltinType::ObjCId:
1642 case BuiltinType::ObjCClass:
1643 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001644 Width = Target->getPointerWidth(0);
1645 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001646 break;
Guy Benyei61054192013-02-07 10:55:47 +00001647 case BuiltinType::OCLSampler:
1648 // Samplers are modeled as integers.
1649 Width = Target->getIntWidth();
1650 Align = Target->getIntAlign();
1651 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001652 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001653 case BuiltinType::OCLClkEvent:
1654 case BuiltinType::OCLQueue:
1655 case BuiltinType::OCLNDRange:
1656 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001657 case BuiltinType::OCLImage1d:
1658 case BuiltinType::OCLImage1dArray:
1659 case BuiltinType::OCLImage1dBuffer:
1660 case BuiltinType::OCLImage2d:
1661 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001662 case BuiltinType::OCLImage2dDepth:
1663 case BuiltinType::OCLImage2dArrayDepth:
1664 case BuiltinType::OCLImage2dMSAA:
1665 case BuiltinType::OCLImage2dArrayMSAA:
1666 case BuiltinType::OCLImage2dMSAADepth:
1667 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001668 case BuiltinType::OCLImage3d:
1669 // Currently these types are pointers to opaque types.
1670 Width = Target->getPointerWidth(0);
1671 Align = Target->getPointerAlign(0);
1672 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001673 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001674 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001675 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001676 Width = Target->getPointerWidth(0);
1677 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001678 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001679 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001680 unsigned AS = getTargetAddressSpace(
1681 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001682 Width = Target->getPointerWidth(AS);
1683 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001684 break;
1685 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001686 case Type::LValueReference:
1687 case Type::RValueReference: {
1688 // alignof and sizeof should never enter this code path here, so we go
1689 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001690 unsigned AS = getTargetAddressSpace(
1691 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001692 Width = Target->getPointerWidth(AS);
1693 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001694 break;
1695 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001696 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001697 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001698 Width = Target->getPointerWidth(AS);
1699 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001700 break;
1701 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001702 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001703 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001704 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001705 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001706 }
Chris Lattner647fb222007-07-18 18:26:58 +00001707 case Type::Complex: {
1708 // Complex types have the same alignment as their elements, but twice the
1709 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001710 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1711 Width = EltInfo.Width * 2;
1712 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001713 break;
1714 }
John McCall8b07ec22010-05-15 11:32:37 +00001715 case Type::ObjCObject:
1716 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001717 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001718 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001719 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001720 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001721 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001722 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001723 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001724 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001725 break;
1726 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001727 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001728 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001729 const TagType *TT = cast<TagType>(T);
1730
1731 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001732 Width = 8;
1733 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001734 break;
1735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736
David Majnemer475b25e2015-01-21 10:54:38 +00001737 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1738 const EnumDecl *ED = ET->getDecl();
1739 TypeInfo Info =
1740 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1741 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1742 Info.Align = AttrAlign;
1743 Info.AlignIsRequired = true;
1744 }
1745 return Info;
1746 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001747
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001748 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001749 const RecordDecl *RD = RT->getDecl();
1750 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001751 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001752 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001753 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001754 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001755 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001756
Chris Lattner63d2b362009-10-22 05:17:15 +00001757 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001758 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1759 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001760
Richard Smith30482bc2011-02-20 03:19:35 +00001761 case Type::Auto: {
1762 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001763 assert(!A->getDeducedType().isNull() &&
1764 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001765 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001766 }
1767
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001768 case Type::Paren:
1769 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1770
Douglas Gregoref462e62009-04-30 17:32:17 +00001771 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001772 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001773 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001774 // If the typedef has an aligned attribute on it, it overrides any computed
1775 // alignment we have. This violates the GCC documentation (which says that
1776 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001777 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001778 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001779 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001780 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001781 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001782 AlignIsRequired = Info.AlignIsRequired;
1783 }
David Majnemer34b57492014-07-30 01:30:47 +00001784 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001785 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001786 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001787
Abramo Bagnara6150c882010-05-11 21:36:43 +00001788 case Type::Elaborated:
1789 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001790
John McCall81904512011-01-06 01:58:22 +00001791 case Type::Attributed:
1792 return getTypeInfo(
1793 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1794
Eli Friedman0dfb8892011-10-06 23:00:33 +00001795 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001796 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001797 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1798 Width = Info.Width;
1799 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001800
1801 // If the size of the type doesn't exceed the platform's max
1802 // atomic promotion width, make the size and alignment more
1803 // favorable to atomic operations:
1804 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1805 // Round the size up to a power of 2.
1806 if (!llvm::isPowerOf2_64(Width))
1807 Width = llvm::NextPowerOf2(Width);
1808
1809 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001810 Align = static_cast<unsigned>(Width);
1811 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001812 }
1813
Douglas Gregoref462e62009-04-30 17:32:17 +00001814 }
Mike Stump11289f42009-09-09 15:08:12 +00001815
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001816 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001817 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001818}
1819
Alexey Bataev00396512015-07-02 03:40:19 +00001820unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1821 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1822 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1823 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1824 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1825 getTargetInfo().getABI() == "elfv1-qpx" &&
1826 T->isSpecificBuiltinType(BuiltinType::Double))
1827 SimdAlign = 256;
1828 return SimdAlign;
1829}
1830
Ken Dyckcc56c542011-01-15 18:38:59 +00001831/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1832CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1833 return CharUnits::fromQuantity(BitSize / getCharWidth());
1834}
1835
Ken Dyckb0fcc592011-02-11 01:54:29 +00001836/// toBits - Convert a size in characters to a size in characters.
1837int64_t ASTContext::toBits(CharUnits CharSize) const {
1838 return CharSize.getQuantity() * getCharWidth();
1839}
1840
Ken Dyck8c89d592009-12-22 14:23:30 +00001841/// getTypeSizeInChars - Return the size of the specified type, in characters.
1842/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001843CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001844 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001845}
Jay Foad39c79802011-01-12 09:06:06 +00001846CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001847 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001848}
1849
Ken Dycka6046ab2010-01-26 17:25:18 +00001850/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001851/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001852CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001853 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001854}
Jay Foad39c79802011-01-12 09:06:06 +00001855CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001856 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001857}
1858
Chris Lattnera3402cd2009-01-27 18:08:34 +00001859/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1860/// type for the current target in bits. This can be different than the ABI
1861/// alignment in cases where it is beneficial for performance to overalign
1862/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001863unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001864 TypeInfo TI = getTypeInfo(T);
1865 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001866
David Majnemere1544562015-04-24 01:25:05 +00001867 T = T->getBaseElementTypeUnsafe();
1868
1869 // The preferred alignment of member pointers is that of a pointer.
1870 if (T->isMemberPointerType())
1871 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1872
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001873 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1874 return ABIAlign; // Never overalign on XCore.
1875
Eli Friedman7ab09572009-05-25 21:27:19 +00001876 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001877 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001878 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001879 if (const EnumType *ET = T->getAs<EnumType>())
1880 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001881 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001882 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1883 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001884 // Don't increase the alignment if an alignment attribute was specified on a
1885 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001886 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001887 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001888
Chris Lattnera3402cd2009-01-27 18:08:34 +00001889 return ABIAlign;
1890}
1891
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001892/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1893/// for __attribute__((aligned)) on this target, to be used if no alignment
1894/// value is specified.
1895unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1896 return getTargetInfo().getDefaultAlignForAttributeAligned();
1897}
1898
Ulrich Weigandfa806422013-05-06 16:23:57 +00001899/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1900/// to a global variable of the specified type.
1901unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1902 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1903}
1904
1905/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1906/// should be given to a global variable of the specified type.
1907CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1908 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1909}
1910
David Majnemer08ef2ba2015-06-23 20:34:18 +00001911CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1912 CharUnits Offset = CharUnits::Zero();
1913 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1914 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1915 Offset += Layout->getBaseClassOffset(Base);
1916 Layout = &getASTRecordLayout(Base);
1917 }
1918 return Offset;
1919}
1920
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001921/// DeepCollectObjCIvars -
1922/// This routine first collects all declared, but not synthesized, ivars in
1923/// super class and then collects all ivars, including those synthesized for
1924/// current class. This routine is used for implementation of current class
1925/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001926///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001927void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1928 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001929 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001930 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1931 DeepCollectObjCIvars(SuperClass, false, Ivars);
1932 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001933 for (const auto *I : OI->ivars())
1934 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001935 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001936 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001937 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001938 Iv= Iv->getNextIvar())
1939 Ivars.push_back(Iv);
1940 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001941}
1942
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001943/// CollectInheritedProtocols - Collect all protocols in current class and
1944/// those inherited by it.
1945void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001946 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001947 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001948 // We can use protocol_iterator here instead of
1949 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001950 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001951 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001952 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001953
1954 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001955 for (const auto *Cat : OI->visible_categories())
1956 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001957
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001958 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1959 while (SD) {
1960 CollectInheritedProtocols(SD, Protocols);
1961 SD = SD->getSuperClass();
1962 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001963 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001964 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001965 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001966 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001967 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001968 // Insert the protocol.
1969 if (!Protocols.insert(
1970 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1971 return;
1972
1973 for (auto *Proto : OP->protocols())
1974 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001975 }
1976}
1977
Jay Foad39c79802011-01-12 09:06:06 +00001978unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001979 unsigned count = 0;
1980 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001981 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001982 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001983
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001984 // Count ivar defined in this class's implementation. This
1985 // includes synthesized ivars.
1986 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001987 count += ImplDecl->ivar_size();
1988
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001989 return count;
1990}
1991
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001992bool ASTContext::isSentinelNullExpr(const Expr *E) {
1993 if (!E)
1994 return false;
1995
1996 // nullptr_t is always treated as null.
1997 if (E->getType()->isNullPtrType()) return true;
1998
1999 if (E->getType()->isAnyPointerType() &&
2000 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2001 Expr::NPC_ValueDependentIsNull))
2002 return true;
2003
2004 // Unfortunately, __null has type 'int'.
2005 if (isa<GNUNullExpr>(E)) return true;
2006
2007 return false;
2008}
2009
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002010/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2011ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2012 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2013 I = ObjCImpls.find(D);
2014 if (I != ObjCImpls.end())
2015 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002016 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002017}
2018/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2019ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2020 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2021 I = ObjCImpls.find(D);
2022 if (I != ObjCImpls.end())
2023 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002024 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002025}
2026
2027/// \brief Set the implementation of ObjCInterfaceDecl.
2028void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2029 ObjCImplementationDecl *ImplD) {
2030 assert(IFaceD && ImplD && "Passed null params");
2031 ObjCImpls[IFaceD] = ImplD;
2032}
2033/// \brief Set the implementation of ObjCCategoryDecl.
2034void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2035 ObjCCategoryImplDecl *ImplD) {
2036 assert(CatD && ImplD && "Passed null params");
2037 ObjCImpls[CatD] = ImplD;
2038}
2039
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002040const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2041 const NamedDecl *ND) const {
2042 if (const ObjCInterfaceDecl *ID =
2043 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002044 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002045 if (const ObjCCategoryDecl *CD =
2046 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002047 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002048 if (const ObjCImplDecl *IMD =
2049 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002050 return IMD->getClassInterface();
2051
Craig Topper36250ad2014-05-12 05:36:57 +00002052 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002053}
2054
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002055/// \brief Get the copy initialization expression of VarDecl,or NULL if
2056/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002057Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002058 assert(VD && "Passed null params");
2059 assert(VD->hasAttr<BlocksAttr>() &&
2060 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002061 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002062 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002063 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002064}
2065
2066/// \brief Set the copy inialization expression of a block var decl.
2067void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2068 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002069 assert(VD->hasAttr<BlocksAttr>() &&
2070 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002071 BlockVarCopyInits[VD] = Init;
2072}
2073
John McCallbcd03502009-12-07 02:54:59 +00002074TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002075 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002076 if (!DataSize)
2077 DataSize = TypeLoc::getFullDataSizeForType(T);
2078 else
2079 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002080 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002081
John McCallbcd03502009-12-07 02:54:59 +00002082 TypeSourceInfo *TInfo =
2083 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2084 new (TInfo) TypeSourceInfo(T);
2085 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002086}
2087
John McCallbcd03502009-12-07 02:54:59 +00002088TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002089 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002090 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002091 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002092 return DI;
2093}
2094
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002095const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002096ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002097 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002098}
2099
2100const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002101ASTContext::getASTObjCImplementationLayout(
2102 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002103 return getObjCLayout(D->getClassInterface(), D);
2104}
2105
Chris Lattner983a8bb2007-07-13 22:13:22 +00002106//===----------------------------------------------------------------------===//
2107// Type creation/memoization methods
2108//===----------------------------------------------------------------------===//
2109
Jay Foad39c79802011-01-12 09:06:06 +00002110QualType
John McCall33ddac02011-01-19 10:06:00 +00002111ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2112 unsigned fastQuals = quals.getFastQualifiers();
2113 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002114
2115 // Check if we've already instantiated this type.
2116 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002117 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002118 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002119 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2120 assert(eq->getQualifiers() == quals);
2121 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002122 }
2123
John McCall33ddac02011-01-19 10:06:00 +00002124 // If the base type is not canonical, make the appropriate canonical type.
2125 QualType canon;
2126 if (!baseType->isCanonicalUnqualified()) {
2127 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002128 canonSplit.Quals.addConsistentQualifiers(quals);
2129 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002130
2131 // Re-find the insert position.
2132 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2133 }
2134
2135 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2136 ExtQualNodes.InsertNode(eq, insertPos);
2137 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002138}
2139
Jay Foad39c79802011-01-12 09:06:06 +00002140QualType
2141ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002142 QualType CanT = getCanonicalType(T);
2143 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002144 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002145
John McCall8ccfcb52009-09-24 19:53:00 +00002146 // If we are composing extended qualifiers together, merge together
2147 // into one ExtQuals node.
2148 QualifierCollector Quals;
2149 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002150
John McCall8ccfcb52009-09-24 19:53:00 +00002151 // If this type already has an address space specified, it cannot get
2152 // another one.
2153 assert(!Quals.hasAddressSpace() &&
2154 "Type cannot be in multiple addr spaces!");
2155 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002156
John McCall8ccfcb52009-09-24 19:53:00 +00002157 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002158}
2159
Chris Lattnerd60183d2009-02-18 22:53:11 +00002160QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002161 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002162 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002163 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002164 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002165
John McCall53fa7142010-12-24 02:08:15 +00002166 if (const PointerType *ptr = T->getAs<PointerType>()) {
2167 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002168 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002169 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2170 return getPointerType(ResultType);
2171 }
2172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
John McCall8ccfcb52009-09-24 19:53:00 +00002174 // If we are composing extended qualifiers together, merge together
2175 // into one ExtQuals node.
2176 QualifierCollector Quals;
2177 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002178
John McCall8ccfcb52009-09-24 19:53:00 +00002179 // If this type already has an ObjCGC specified, it cannot get
2180 // another one.
2181 assert(!Quals.hasObjCGCAttr() &&
2182 "Type cannot have multiple ObjCGCs!");
2183 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002184
John McCall8ccfcb52009-09-24 19:53:00 +00002185 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002186}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002187
John McCall4f5019e2010-12-19 02:44:49 +00002188const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2189 FunctionType::ExtInfo Info) {
2190 if (T->getExtInfo() == Info)
2191 return T;
2192
2193 QualType Result;
2194 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002195 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002196 } else {
2197 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2198 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2199 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002200 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002201 }
2202
2203 return cast<FunctionType>(Result.getTypePtr());
2204}
2205
Richard Smith2a7d4812013-05-04 07:00:32 +00002206void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2207 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002208 FD = FD->getMostRecentDecl();
2209 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002210 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2211 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002212 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002213 if (FunctionDecl *Next = FD->getPreviousDecl())
2214 FD = Next;
2215 else
2216 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002217 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002218 if (ASTMutationListener *L = getASTMutationListener())
2219 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002220}
2221
Richard Smith0b3a4622014-11-13 20:01:57 +00002222/// Get a function type and produce the equivalent function type with the
2223/// specified exception specification. Type sugar that can be present on a
2224/// declaration of a function with an exception specification is permitted
2225/// and preserved. Other type sugar (for instance, typedefs) is not.
2226static QualType getFunctionTypeWithExceptionSpec(
2227 ASTContext &Context, QualType Orig,
2228 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2229 // Might have some parens.
2230 if (auto *PT = dyn_cast<ParenType>(Orig))
2231 return Context.getParenType(
2232 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2233
2234 // Might have a calling-convention attribute.
2235 if (auto *AT = dyn_cast<AttributedType>(Orig))
2236 return Context.getAttributedType(
2237 AT->getAttrKind(),
2238 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2239 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2240 ESI));
2241
2242 // Anything else must be a function type. Rebuild it with the new exception
2243 // specification.
2244 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2245 return Context.getFunctionType(
2246 Proto->getReturnType(), Proto->getParamTypes(),
2247 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2248}
2249
2250void ASTContext::adjustExceptionSpec(
2251 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2252 bool AsWritten) {
2253 // Update the type.
2254 QualType Updated =
2255 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2256 FD->setType(Updated);
2257
2258 if (!AsWritten)
2259 return;
2260
2261 // Update the type in the type source information too.
2262 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2263 // If the type and the type-as-written differ, we may need to update
2264 // the type-as-written too.
2265 if (TSInfo->getType() != FD->getType())
2266 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2267
2268 // FIXME: When we get proper type location information for exceptions,
2269 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2270 // up the TypeSourceInfo;
2271 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2272 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2273 "TypeLoc size mismatch from updating exception specification");
2274 TSInfo->overrideType(Updated);
2275 }
2276}
2277
Chris Lattnerc6395932007-06-22 20:56:16 +00002278/// getComplexType - Return the uniqued reference to the type for a complex
2279/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002280QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002281 // Unique pointers, to guarantee there is only one pointer of a particular
2282 // structure.
2283 llvm::FoldingSetNodeID ID;
2284 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002285
Craig Topper36250ad2014-05-12 05:36:57 +00002286 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002287 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2288 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002289
Chris Lattnerc6395932007-06-22 20:56:16 +00002290 // If the pointee type isn't canonical, this won't be a canonical type either,
2291 // so fill in the canonical type field.
2292 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002293 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002294 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattnerc6395932007-06-22 20:56:16 +00002296 // Get the new insert position for the node we care about.
2297 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002298 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002299 }
John McCall90d1c2d2009-09-24 23:30:46 +00002300 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002301 Types.push_back(New);
2302 ComplexTypes.InsertNode(New, InsertPos);
2303 return QualType(New, 0);
2304}
2305
Chris Lattner970e54e2006-11-12 00:37:36 +00002306/// getPointerType - Return the uniqued reference to the type for a pointer to
2307/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002308QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002309 // Unique pointers, to guarantee there is only one pointer of a particular
2310 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002311 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002312 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002313
Craig Topper36250ad2014-05-12 05:36:57 +00002314 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002315 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002316 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattner7ccecb92006-11-12 08:50:50 +00002318 // If the pointee type isn't canonical, this won't be a canonical type either,
2319 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002320 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002321 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002322 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002323
Bob Wilsonc8541f22013-03-15 17:12:43 +00002324 // Get the new insert position for the node we care about.
2325 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002326 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002327 }
John McCall90d1c2d2009-09-24 23:30:46 +00002328 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002329 Types.push_back(New);
2330 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002331 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002332}
2333
Reid Kleckner0503a872013-12-05 01:23:43 +00002334QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2335 llvm::FoldingSetNodeID ID;
2336 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002337 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002338 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2339 if (AT)
2340 return QualType(AT, 0);
2341
2342 QualType Canonical = getCanonicalType(New);
2343
2344 // Get the new insert position for the node we care about.
2345 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002346 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002347
2348 AT = new (*this, TypeAlignment)
2349 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2350 Types.push_back(AT);
2351 AdjustedTypes.InsertNode(AT, InsertPos);
2352 return QualType(AT, 0);
2353}
2354
Reid Kleckner8a365022013-06-24 17:51:48 +00002355QualType ASTContext::getDecayedType(QualType T) const {
2356 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2357
Reid Kleckner8a365022013-06-24 17:51:48 +00002358 QualType Decayed;
2359
2360 // C99 6.7.5.3p7:
2361 // A declaration of a parameter as "array of type" shall be
2362 // adjusted to "qualified pointer to type", where the type
2363 // qualifiers (if any) are those specified within the [ and ] of
2364 // the array type derivation.
2365 if (T->isArrayType())
2366 Decayed = getArrayDecayedType(T);
2367
2368 // C99 6.7.5.3p8:
2369 // A declaration of a parameter as "function returning type"
2370 // shall be adjusted to "pointer to function returning type", as
2371 // in 6.3.2.1.
2372 if (T->isFunctionType())
2373 Decayed = getPointerType(T);
2374
Reid Kleckner0503a872013-12-05 01:23:43 +00002375 llvm::FoldingSetNodeID ID;
2376 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002377 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002378 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2379 if (AT)
2380 return QualType(AT, 0);
2381
Reid Kleckner8a365022013-06-24 17:51:48 +00002382 QualType Canonical = getCanonicalType(Decayed);
2383
2384 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002385 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002386 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002387
Reid Kleckner0503a872013-12-05 01:23:43 +00002388 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2389 Types.push_back(AT);
2390 AdjustedTypes.InsertNode(AT, InsertPos);
2391 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002392}
2393
Mike Stump11289f42009-09-09 15:08:12 +00002394/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002395/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002396QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002397 assert(T->isFunctionType() && "block of function types only");
2398 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002399 // structure.
2400 llvm::FoldingSetNodeID ID;
2401 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002402
Craig Topper36250ad2014-05-12 05:36:57 +00002403 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002404 if (BlockPointerType *PT =
2405 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2406 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002407
2408 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002409 // type either so fill in the canonical type field.
2410 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002411 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002412 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002413
Steve Naroffec33ed92008-08-27 16:04:49 +00002414 // Get the new insert position for the node we care about.
2415 BlockPointerType *NewIP =
2416 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002417 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002418 }
John McCall90d1c2d2009-09-24 23:30:46 +00002419 BlockPointerType *New
2420 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002421 Types.push_back(New);
2422 BlockPointerTypes.InsertNode(New, InsertPos);
2423 return QualType(New, 0);
2424}
2425
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002426/// getLValueReferenceType - Return the uniqued reference to the type for an
2427/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002428QualType
2429ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002430 assert(getCanonicalType(T) != OverloadTy &&
2431 "Unresolved overloaded function type");
2432
Bill Wendling3708c182007-05-27 10:15:43 +00002433 // Unique pointers, to guarantee there is only one pointer of a particular
2434 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002435 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002436 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002437
Craig Topper36250ad2014-05-12 05:36:57 +00002438 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002439 if (LValueReferenceType *RT =
2440 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002441 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002442
John McCallfc93cf92009-10-22 22:37:11 +00002443 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2444
Bill Wendling3708c182007-05-27 10:15:43 +00002445 // If the referencee type isn't canonical, this won't be a canonical type
2446 // either, so fill in the canonical type field.
2447 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002448 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2449 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2450 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002451
Bill Wendling3708c182007-05-27 10:15:43 +00002452 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002453 LValueReferenceType *NewIP =
2454 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002455 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002456 }
2457
John McCall90d1c2d2009-09-24 23:30:46 +00002458 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002459 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2460 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002461 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002462 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002463
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002464 return QualType(New, 0);
2465}
2466
2467/// getRValueReferenceType - Return the uniqued reference to the type for an
2468/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002469QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002470 // Unique pointers, to guarantee there is only one pointer of a particular
2471 // structure.
2472 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002473 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002474
Craig Topper36250ad2014-05-12 05:36:57 +00002475 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002476 if (RValueReferenceType *RT =
2477 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2478 return QualType(RT, 0);
2479
John McCallfc93cf92009-10-22 22:37:11 +00002480 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2481
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002482 // If the referencee type isn't canonical, this won't be a canonical type
2483 // either, so fill in the canonical type field.
2484 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002485 if (InnerRef || !T.isCanonical()) {
2486 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2487 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002488
2489 // Get the new insert position for the node we care about.
2490 RValueReferenceType *NewIP =
2491 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002492 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002493 }
2494
John McCall90d1c2d2009-09-24 23:30:46 +00002495 RValueReferenceType *New
2496 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002497 Types.push_back(New);
2498 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002499 return QualType(New, 0);
2500}
2501
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002502/// getMemberPointerType - Return the uniqued reference to the type for a
2503/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002504QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002505 // Unique pointers, to guarantee there is only one pointer of a particular
2506 // structure.
2507 llvm::FoldingSetNodeID ID;
2508 MemberPointerType::Profile(ID, T, Cls);
2509
Craig Topper36250ad2014-05-12 05:36:57 +00002510 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002511 if (MemberPointerType *PT =
2512 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2513 return QualType(PT, 0);
2514
2515 // If the pointee or class type isn't canonical, this won't be a canonical
2516 // type either, so fill in the canonical type field.
2517 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002518 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002519 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2520
2521 // Get the new insert position for the node we care about.
2522 MemberPointerType *NewIP =
2523 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002524 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002525 }
John McCall90d1c2d2009-09-24 23:30:46 +00002526 MemberPointerType *New
2527 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002528 Types.push_back(New);
2529 MemberPointerTypes.InsertNode(New, InsertPos);
2530 return QualType(New, 0);
2531}
2532
Mike Stump11289f42009-09-09 15:08:12 +00002533/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002534/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002535QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002536 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002537 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002538 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002539 assert((EltTy->isDependentType() ||
2540 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002541 "Constant array of VLAs is illegal!");
2542
Chris Lattnere2df3f92009-05-13 04:12:56 +00002543 // Convert the array size into a canonical width matching the pointer size for
2544 // the target.
2545 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002546 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002547 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattner23b7eb62007-06-15 23:05:46 +00002549 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002550 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002551
Craig Topper36250ad2014-05-12 05:36:57 +00002552 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002553 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002554 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002555 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002556
John McCall33ddac02011-01-19 10:06:00 +00002557 // If the element type isn't canonical or has qualifiers, this won't
2558 // be a canonical type either, so fill in the canonical type field.
2559 QualType Canon;
2560 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2561 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002562 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002563 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002564 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002565
Chris Lattner36f8e652007-01-27 08:31:04 +00002566 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002567 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002568 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002569 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002570 }
Mike Stump11289f42009-09-09 15:08:12 +00002571
John McCall90d1c2d2009-09-24 23:30:46 +00002572 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002573 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002574 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002575 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002576 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002577}
2578
John McCall06549462011-01-18 08:40:38 +00002579/// getVariableArrayDecayedType - Turns the given type, which may be
2580/// variably-modified, into the corresponding type with all the known
2581/// sizes replaced with [*].
2582QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2583 // Vastly most common case.
2584 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002585
John McCall06549462011-01-18 08:40:38 +00002586 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002587
John McCall06549462011-01-18 08:40:38 +00002588 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002589 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002590 switch (ty->getTypeClass()) {
2591#define TYPE(Class, Base)
2592#define ABSTRACT_TYPE(Class, Base)
2593#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2594#include "clang/AST/TypeNodes.def"
2595 llvm_unreachable("didn't desugar past all non-canonical types?");
2596
2597 // These types should never be variably-modified.
2598 case Type::Builtin:
2599 case Type::Complex:
2600 case Type::Vector:
2601 case Type::ExtVector:
2602 case Type::DependentSizedExtVector:
2603 case Type::ObjCObject:
2604 case Type::ObjCInterface:
2605 case Type::ObjCObjectPointer:
2606 case Type::Record:
2607 case Type::Enum:
2608 case Type::UnresolvedUsing:
2609 case Type::TypeOfExpr:
2610 case Type::TypeOf:
2611 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002612 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002613 case Type::DependentName:
2614 case Type::InjectedClassName:
2615 case Type::TemplateSpecialization:
2616 case Type::DependentTemplateSpecialization:
2617 case Type::TemplateTypeParm:
2618 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002619 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002620 case Type::PackExpansion:
2621 llvm_unreachable("type should never be variably-modified");
2622
2623 // These types can be variably-modified but should never need to
2624 // further decay.
2625 case Type::FunctionNoProto:
2626 case Type::FunctionProto:
2627 case Type::BlockPointer:
2628 case Type::MemberPointer:
2629 return type;
2630
2631 // These types can be variably-modified. All these modifications
2632 // preserve structure except as noted by comments.
2633 // TODO: if we ever care about optimizing VLAs, there are no-op
2634 // optimizations available here.
2635 case Type::Pointer:
2636 result = getPointerType(getVariableArrayDecayedType(
2637 cast<PointerType>(ty)->getPointeeType()));
2638 break;
2639
2640 case Type::LValueReference: {
2641 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2642 result = getLValueReferenceType(
2643 getVariableArrayDecayedType(lv->getPointeeType()),
2644 lv->isSpelledAsLValue());
2645 break;
2646 }
2647
2648 case Type::RValueReference: {
2649 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2650 result = getRValueReferenceType(
2651 getVariableArrayDecayedType(lv->getPointeeType()));
2652 break;
2653 }
2654
Eli Friedman0dfb8892011-10-06 23:00:33 +00002655 case Type::Atomic: {
2656 const AtomicType *at = cast<AtomicType>(ty);
2657 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2658 break;
2659 }
2660
John McCall06549462011-01-18 08:40:38 +00002661 case Type::ConstantArray: {
2662 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2663 result = getConstantArrayType(
2664 getVariableArrayDecayedType(cat->getElementType()),
2665 cat->getSize(),
2666 cat->getSizeModifier(),
2667 cat->getIndexTypeCVRQualifiers());
2668 break;
2669 }
2670
2671 case Type::DependentSizedArray: {
2672 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2673 result = getDependentSizedArrayType(
2674 getVariableArrayDecayedType(dat->getElementType()),
2675 dat->getSizeExpr(),
2676 dat->getSizeModifier(),
2677 dat->getIndexTypeCVRQualifiers(),
2678 dat->getBracketsRange());
2679 break;
2680 }
2681
2682 // Turn incomplete types into [*] types.
2683 case Type::IncompleteArray: {
2684 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2685 result = getVariableArrayType(
2686 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002687 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002688 ArrayType::Normal,
2689 iat->getIndexTypeCVRQualifiers(),
2690 SourceRange());
2691 break;
2692 }
2693
2694 // Turn VLA types into [*] types.
2695 case Type::VariableArray: {
2696 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2697 result = getVariableArrayType(
2698 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002699 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002700 ArrayType::Star,
2701 vat->getIndexTypeCVRQualifiers(),
2702 vat->getBracketsRange());
2703 break;
2704 }
2705 }
2706
2707 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002708 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002709}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002710
Steve Naroffcadebd02007-08-30 18:14:25 +00002711/// getVariableArrayType - Returns a non-unique reference to the type for a
2712/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002713QualType ASTContext::getVariableArrayType(QualType EltTy,
2714 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002715 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002716 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002717 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002718 // Since we don't unique expressions, it isn't possible to unique VLA's
2719 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002720 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002721
John McCall33ddac02011-01-19 10:06:00 +00002722 // Be sure to pull qualifiers off the element type.
2723 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2724 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002725 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002726 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002727 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002728 }
2729
John McCall90d1c2d2009-09-24 23:30:46 +00002730 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002731 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002732
2733 VariableArrayTypes.push_back(New);
2734 Types.push_back(New);
2735 return QualType(New, 0);
2736}
2737
Douglas Gregor4619e432008-12-05 23:32:09 +00002738/// getDependentSizedArrayType - Returns a non-unique reference to
2739/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002740/// type.
John McCall33ddac02011-01-19 10:06:00 +00002741QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2742 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002743 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002744 unsigned elementTypeQuals,
2745 SourceRange brackets) const {
2746 assert((!numElements || numElements->isTypeDependent() ||
2747 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002748 "Size must be type- or value-dependent!");
2749
John McCall33ddac02011-01-19 10:06:00 +00002750 // Dependently-sized array types that do not have a specified number
2751 // of elements will have their sizes deduced from a dependent
2752 // initializer. We do no canonicalization here at all, which is okay
2753 // because they can't be used in most locations.
2754 if (!numElements) {
2755 DependentSizedArrayType *newType
2756 = new (*this, TypeAlignment)
2757 DependentSizedArrayType(*this, elementType, QualType(),
2758 numElements, ASM, elementTypeQuals,
2759 brackets);
2760 Types.push_back(newType);
2761 return QualType(newType, 0);
2762 }
2763
2764 // Otherwise, we actually build a new type every time, but we
2765 // also build a canonical type.
2766
2767 SplitQualType canonElementType = getCanonicalType(elementType).split();
2768
Craig Topper36250ad2014-05-12 05:36:57 +00002769 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002770 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002771 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002772 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002773 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002774
John McCall33ddac02011-01-19 10:06:00 +00002775 // Look for an existing type with these properties.
2776 DependentSizedArrayType *canonTy =
2777 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002778
John McCall33ddac02011-01-19 10:06:00 +00002779 // If we don't have one, build one.
2780 if (!canonTy) {
2781 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002782 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002783 QualType(), numElements, ASM, elementTypeQuals,
2784 brackets);
2785 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2786 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002787 }
2788
John McCall33ddac02011-01-19 10:06:00 +00002789 // Apply qualifiers from the element type to the array.
2790 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002791 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002792
David Majnemer16a74702015-07-24 05:54:19 +00002793 // If we didn't need extra canonicalization for the element type or the size
2794 // expression, then just use that as our result.
2795 if (QualType(canonElementType.Ty, 0) == elementType &&
2796 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002797 return canon;
2798
2799 // Otherwise, we need to build a type which follows the spelling
2800 // of the element type.
2801 DependentSizedArrayType *sugaredType
2802 = new (*this, TypeAlignment)
2803 DependentSizedArrayType(*this, elementType, canon, numElements,
2804 ASM, elementTypeQuals, brackets);
2805 Types.push_back(sugaredType);
2806 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002807}
2808
John McCall33ddac02011-01-19 10:06:00 +00002809QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002810 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002811 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002812 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002813 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002814
Craig Topper36250ad2014-05-12 05:36:57 +00002815 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002816 if (IncompleteArrayType *iat =
2817 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2818 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002819
2820 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002821 // either, so fill in the canonical type field. We also have to pull
2822 // qualifiers off the element type.
2823 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002824
John McCall33ddac02011-01-19 10:06:00 +00002825 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2826 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002827 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002828 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002829 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002830
2831 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002832 IncompleteArrayType *existing =
2833 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2834 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002835 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002836
John McCall33ddac02011-01-19 10:06:00 +00002837 IncompleteArrayType *newType = new (*this, TypeAlignment)
2838 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002839
John McCall33ddac02011-01-19 10:06:00 +00002840 IncompleteArrayTypes.InsertNode(newType, insertPos);
2841 Types.push_back(newType);
2842 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002843}
2844
Steve Naroff91fcddb2007-07-18 18:00:27 +00002845/// getVectorType - Return the unique reference to a vector type of
2846/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002847QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002848 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002849 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002850
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002851 // Check if we've already instantiated a vector of this type.
2852 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002853 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002854
Craig Topper36250ad2014-05-12 05:36:57 +00002855 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002856 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2857 return QualType(VTP, 0);
2858
2859 // If the element type isn't canonical, this won't be a canonical type either,
2860 // so fill in the canonical type field.
2861 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002862 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002863 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002864
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002865 // Get the new insert position for the node we care about.
2866 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002867 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002868 }
John McCall90d1c2d2009-09-24 23:30:46 +00002869 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002870 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002871 VectorTypes.InsertNode(New, InsertPos);
2872 Types.push_back(New);
2873 return QualType(New, 0);
2874}
2875
Nate Begemance4d7fc2008-04-18 23:10:10 +00002876/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002877/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002878QualType
2879ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002880 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002881
Steve Naroff91fcddb2007-07-18 18:00:27 +00002882 // Check if we've already instantiated a vector of this type.
2883 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002884 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002885 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002886 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002887 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2888 return QualType(VTP, 0);
2889
2890 // If the element type isn't canonical, this won't be a canonical type either,
2891 // so fill in the canonical type field.
2892 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002893 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002894 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002895
Steve Naroff91fcddb2007-07-18 18:00:27 +00002896 // Get the new insert position for the node we care about.
2897 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002898 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002899 }
John McCall90d1c2d2009-09-24 23:30:46 +00002900 ExtVectorType *New = new (*this, TypeAlignment)
2901 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002902 VectorTypes.InsertNode(New, InsertPos);
2903 Types.push_back(New);
2904 return QualType(New, 0);
2905}
2906
Jay Foad39c79802011-01-12 09:06:06 +00002907QualType
2908ASTContext::getDependentSizedExtVectorType(QualType vecType,
2909 Expr *SizeExpr,
2910 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002911 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002912 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002913 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002914
Craig Topper36250ad2014-05-12 05:36:57 +00002915 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002916 DependentSizedExtVectorType *Canon
2917 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2918 DependentSizedExtVectorType *New;
2919 if (Canon) {
2920 // We already have a canonical version of this array type; use it as
2921 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002922 New = new (*this, TypeAlignment)
2923 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2924 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002925 } else {
2926 QualType CanonVecTy = getCanonicalType(vecType);
2927 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002928 New = new (*this, TypeAlignment)
2929 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2930 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002931
2932 DependentSizedExtVectorType *CanonCheck
2933 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2934 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2935 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002936 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2937 } else {
2938 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2939 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002940 New = new (*this, TypeAlignment)
2941 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002942 }
2943 }
Mike Stump11289f42009-09-09 15:08:12 +00002944
Douglas Gregor758a8692009-06-17 21:51:59 +00002945 Types.push_back(New);
2946 return QualType(New, 0);
2947}
2948
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002949/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002950///
Jay Foad39c79802011-01-12 09:06:06 +00002951QualType
2952ASTContext::getFunctionNoProtoType(QualType ResultTy,
2953 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002954 const CallingConv CallConv = Info.getCC();
2955
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002956 // Unique functions, to guarantee there is only one function of a particular
2957 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002958 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002959 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002960
Craig Topper36250ad2014-05-12 05:36:57 +00002961 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002962 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002963 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002964 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002965
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002966 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002967 if (!ResultTy.isCanonical()) {
2968 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002969
Chris Lattner47955de2007-01-27 08:37:20 +00002970 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002971 FunctionNoProtoType *NewIP =
2972 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002973 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002974 }
Mike Stump11289f42009-09-09 15:08:12 +00002975
Roman Divacky65b88cd2011-03-01 17:40:53 +00002976 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002977 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002978 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002979 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002980 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002981 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002982}
2983
Douglas Gregorcd780372013-01-17 23:36:45 +00002984/// \brief Determine whether \p T is canonical as the result type of a function.
2985static bool isCanonicalResultType(QualType T) {
2986 return T.isCanonical() &&
2987 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2988 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2989}
2990
Jay Foad39c79802011-01-12 09:06:06 +00002991QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002992ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002993 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002994 size_t NumArgs = ArgArray.size();
2995
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002996 // Unique functions, to guarantee there is only one function of a particular
2997 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002998 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002999 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3000 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003001
Craig Topper36250ad2014-05-12 05:36:57 +00003002 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003003 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003004 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003005 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003006
3007 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003008 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003009 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003010 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003011 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003012 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003013 isCanonical = false;
3014
3015 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003016 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003017 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003018 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003019 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003020 CanonicalArgs.reserve(NumArgs);
3021 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003022 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003023
John McCalldb40c7f2010-12-14 08:05:40 +00003024 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003025 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003026 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003027
Douglas Gregorcd780372013-01-17 23:36:45 +00003028 // Result types do not have ARC lifetime qualifiers.
3029 QualType CanResultTy = getCanonicalType(ResultTy);
3030 if (ResultTy.getQualifiers().hasObjCLifetime()) {
3031 Qualifiers Qs = CanResultTy.getQualifiers();
3032 Qs.removeObjCLifetime();
3033 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
3034 }
3035
Jordan Rose5c382722013-03-08 21:51:21 +00003036 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003037
Chris Lattnerfd4de792007-01-27 01:15:32 +00003038 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003039 FunctionProtoType *NewIP =
3040 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003041 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003042 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003043
John McCall31168b02011-06-15 23:02:42 +00003044 // FunctionProtoType objects are allocated with extra bytes after
3045 // them for three variable size arrays at the end:
3046 // - parameter types
3047 // - exception types
3048 // - consumed-arguments flags
3049 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003050 // expression, or information used to resolve the exception
3051 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003052 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003053 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003054 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3055 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3056 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003057 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003058 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003059 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003060 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003061 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003062 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003063 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003064 Size += NumArgs * sizeof(bool);
3065
John McCalldb40c7f2010-12-14 08:05:40 +00003066 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003067 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003068 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003069 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003070 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003071 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003072}
Chris Lattneref51c202006-11-10 07:17:23 +00003073
John McCalle78aac42010-03-10 03:28:59 +00003074#ifndef NDEBUG
3075static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3076 if (!isa<CXXRecordDecl>(D)) return false;
3077 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3078 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3079 return true;
3080 if (RD->getDescribedClassTemplate() &&
3081 !isa<ClassTemplateSpecializationDecl>(RD))
3082 return true;
3083 return false;
3084}
3085#endif
3086
3087/// getInjectedClassNameType - Return the unique reference to the
3088/// injected class name type for the specified templated declaration.
3089QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003090 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003091 assert(NeedsInjectedClassNameType(Decl));
3092 if (Decl->TypeForDecl) {
3093 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003094 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003095 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3096 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3097 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3098 } else {
John McCall424cec92011-01-19 06:33:43 +00003099 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003100 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003101 Decl->TypeForDecl = newType;
3102 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003103 }
3104 return QualType(Decl->TypeForDecl, 0);
3105}
3106
Douglas Gregor83a586e2008-04-13 21:07:44 +00003107/// getTypeDeclType - Return the unique reference to the type for the
3108/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003109QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003110 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003111 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003112
Richard Smithdda56e42011-04-15 14:24:37 +00003113 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003114 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003115
John McCall96f0b5f2010-03-10 06:48:02 +00003116 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3117 "Template type parameter types are always available.");
3118
John McCall81e38502010-02-16 03:57:14 +00003119 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003120 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003121 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003122 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003123 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003124 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003125 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003126 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003127 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003128 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3129 Decl->TypeForDecl = newType;
3130 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003131 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003132 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003133
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003134 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003135}
3136
Chris Lattner32d920b2007-01-26 02:01:53 +00003137/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003138/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003139QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003140ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3141 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003142 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003143
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003144 if (Canonical.isNull())
3145 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003146 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003147 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003148 Decl->TypeForDecl = newType;
3149 Types.push_back(newType);
3150 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003151}
3152
Jay Foad39c79802011-01-12 09:06:06 +00003153QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003154 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3155
Douglas Gregorec9fd132012-01-14 16:38:05 +00003156 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003157 if (PrevDecl->TypeForDecl)
3158 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3159
John McCall424cec92011-01-19 06:33:43 +00003160 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3161 Decl->TypeForDecl = newType;
3162 Types.push_back(newType);
3163 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003164}
3165
Jay Foad39c79802011-01-12 09:06:06 +00003166QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003167 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3168
Douglas Gregorec9fd132012-01-14 16:38:05 +00003169 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003170 if (PrevDecl->TypeForDecl)
3171 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3172
John McCall424cec92011-01-19 06:33:43 +00003173 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3174 Decl->TypeForDecl = newType;
3175 Types.push_back(newType);
3176 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003177}
3178
John McCall81904512011-01-06 01:58:22 +00003179QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3180 QualType modifiedType,
3181 QualType equivalentType) {
3182 llvm::FoldingSetNodeID id;
3183 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3184
Craig Topper36250ad2014-05-12 05:36:57 +00003185 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003186 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3187 if (type) return QualType(type, 0);
3188
3189 QualType canon = getCanonicalType(equivalentType);
3190 type = new (*this, TypeAlignment)
3191 AttributedType(canon, attrKind, modifiedType, equivalentType);
3192
3193 Types.push_back(type);
3194 AttributedTypes.InsertNode(type, insertPos);
3195
3196 return QualType(type, 0);
3197}
3198
3199
John McCallcebee162009-10-18 09:09:24 +00003200/// \brief Retrieve a substitution-result type.
3201QualType
3202ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003203 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003204 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003205 && "replacement types must always be canonical");
3206
3207 llvm::FoldingSetNodeID ID;
3208 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003209 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003210 SubstTemplateTypeParmType *SubstParm
3211 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3212
3213 if (!SubstParm) {
3214 SubstParm = new (*this, TypeAlignment)
3215 SubstTemplateTypeParmType(Parm, Replacement);
3216 Types.push_back(SubstParm);
3217 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3218 }
3219
3220 return QualType(SubstParm, 0);
3221}
3222
Douglas Gregorada4b792011-01-14 02:55:32 +00003223/// \brief Retrieve a
3224QualType ASTContext::getSubstTemplateTypeParmPackType(
3225 const TemplateTypeParmType *Parm,
3226 const TemplateArgument &ArgPack) {
3227#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003228 for (const auto &P : ArgPack.pack_elements()) {
3229 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3230 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003231 }
3232#endif
3233
3234 llvm::FoldingSetNodeID ID;
3235 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003236 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003237 if (SubstTemplateTypeParmPackType *SubstParm
3238 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3239 return QualType(SubstParm, 0);
3240
3241 QualType Canon;
3242 if (!Parm->isCanonicalUnqualified()) {
3243 Canon = getCanonicalType(QualType(Parm, 0));
3244 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3245 ArgPack);
3246 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3247 }
3248
3249 SubstTemplateTypeParmPackType *SubstParm
3250 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3251 ArgPack);
3252 Types.push_back(SubstParm);
3253 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3254 return QualType(SubstParm, 0);
3255}
3256
Douglas Gregoreff93e02009-02-05 23:33:38 +00003257/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003258/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003259/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003260QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003261 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003262 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003263 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003264 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003265 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003266 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003267 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3268
3269 if (TypeParm)
3270 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003271
Chandler Carruth08836322011-05-01 00:51:33 +00003272 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003273 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003274 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003275
3276 TemplateTypeParmType *TypeCheck
3277 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3278 assert(!TypeCheck && "Template type parameter canonical type broken");
3279 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003280 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003281 TypeParm = new (*this, TypeAlignment)
3282 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003283
3284 Types.push_back(TypeParm);
3285 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3286
3287 return QualType(TypeParm, 0);
3288}
3289
John McCalle78aac42010-03-10 03:28:59 +00003290TypeSourceInfo *
3291ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3292 SourceLocation NameLoc,
3293 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003294 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003295 assert(!Name.getAsDependentTemplateName() &&
3296 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003297 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003298
3299 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003300 TemplateSpecializationTypeLoc TL =
3301 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003302 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003303 TL.setTemplateNameLoc(NameLoc);
3304 TL.setLAngleLoc(Args.getLAngleLoc());
3305 TL.setRAngleLoc(Args.getRAngleLoc());
3306 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3307 TL.setArgLocInfo(i, Args[i].getLocInfo());
3308 return DI;
3309}
3310
Mike Stump11289f42009-09-09 15:08:12 +00003311QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003312ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003313 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003314 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003315 assert(!Template.getAsDependentTemplateName() &&
3316 "No dependent template names here!");
3317
John McCall6b51f282009-11-23 01:53:49 +00003318 unsigned NumArgs = Args.size();
3319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003321 ArgVec.reserve(NumArgs);
3322 for (unsigned i = 0; i != NumArgs; ++i)
3323 ArgVec.push_back(Args[i].getArgument());
3324
John McCall2408e322010-04-27 00:57:59 +00003325 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003326 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003327}
3328
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003329#ifndef NDEBUG
3330static bool hasAnyPackExpansions(const TemplateArgument *Args,
3331 unsigned NumArgs) {
3332 for (unsigned I = 0; I != NumArgs; ++I)
3333 if (Args[I].isPackExpansion())
3334 return true;
3335
3336 return true;
3337}
3338#endif
3339
John McCall0ad16662009-10-29 08:12:44 +00003340QualType
3341ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003342 const TemplateArgument *Args,
3343 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003344 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003345 assert(!Template.getAsDependentTemplateName() &&
3346 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003347 // Look through qualified template names.
3348 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3349 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003350
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003351 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003352 Template.getAsTemplateDecl() &&
3353 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003354 QualType CanonType;
3355 if (!Underlying.isNull())
3356 CanonType = getCanonicalType(Underlying);
3357 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003358 // We can get here with an alias template when the specialization contains
3359 // a pack expansion that does not match up with a parameter pack.
3360 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3361 "Caller must compute aliased type");
3362 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003363 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3364 NumArgs);
3365 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003366
Douglas Gregora8e02e72009-07-28 23:00:59 +00003367 // Allocate the (non-canonical) template specialization type, but don't
3368 // try to unique it: these types typically have location information that
3369 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003370 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3371 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003372 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003373 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003374 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003375 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3376 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003377
Douglas Gregor8bf42052009-02-09 18:46:07 +00003378 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003379 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003380}
3381
Mike Stump11289f42009-09-09 15:08:12 +00003382QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003383ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3384 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003385 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003386 assert(!Template.getAsDependentTemplateName() &&
3387 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003388
Douglas Gregore29139c2011-03-03 17:04:51 +00003389 // Look through qualified template names.
3390 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3391 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003392
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003393 // Build the canonical template specialization type.
3394 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003395 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003396 CanonArgs.reserve(NumArgs);
3397 for (unsigned I = 0; I != NumArgs; ++I)
3398 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3399
3400 // Determine whether this canonical template specialization type already
3401 // exists.
3402 llvm::FoldingSetNodeID ID;
3403 TemplateSpecializationType::Profile(ID, CanonTemplate,
3404 CanonArgs.data(), NumArgs, *this);
3405
Craig Topper36250ad2014-05-12 05:36:57 +00003406 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003407 TemplateSpecializationType *Spec
3408 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3409
3410 if (!Spec) {
3411 // Allocate a new canonical template specialization type.
3412 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3413 sizeof(TemplateArgument) * NumArgs),
3414 TypeAlignment);
3415 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3416 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003417 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003418 Types.push_back(Spec);
3419 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3420 }
3421
3422 assert(Spec->isDependentType() &&
3423 "Non-dependent template-id type must have a canonical type");
3424 return QualType(Spec, 0);
3425}
3426
3427QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003428ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3429 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003430 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003431 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003432 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003433
Craig Topper36250ad2014-05-12 05:36:57 +00003434 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003435 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003436 if (T)
3437 return QualType(T, 0);
3438
Douglas Gregorc42075a2010-02-04 18:10:26 +00003439 QualType Canon = NamedType;
3440 if (!Canon.isCanonical()) {
3441 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003442 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3443 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003444 (void)CheckT;
3445 }
3446
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003447 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003448 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003449 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003450 return QualType(T, 0);
3451}
3452
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003453QualType
Jay Foad39c79802011-01-12 09:06:06 +00003454ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003455 llvm::FoldingSetNodeID ID;
3456 ParenType::Profile(ID, InnerType);
3457
Craig Topper36250ad2014-05-12 05:36:57 +00003458 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003459 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3460 if (T)
3461 return QualType(T, 0);
3462
3463 QualType Canon = InnerType;
3464 if (!Canon.isCanonical()) {
3465 Canon = getCanonicalType(InnerType);
3466 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3467 assert(!CheckT && "Paren canonical type broken");
3468 (void)CheckT;
3469 }
3470
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003471 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003472 Types.push_back(T);
3473 ParenTypes.InsertNode(T, InsertPos);
3474 return QualType(T, 0);
3475}
3476
Douglas Gregor02085352010-03-31 20:19:30 +00003477QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3478 NestedNameSpecifier *NNS,
3479 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003480 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003481 if (Canon.isNull()) {
3482 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003483 ElaboratedTypeKeyword CanonKeyword = Keyword;
3484 if (Keyword == ETK_None)
3485 CanonKeyword = ETK_Typename;
3486
3487 if (CanonNNS != NNS || CanonKeyword != Keyword)
3488 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003489 }
3490
3491 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003492 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003493
Craig Topper36250ad2014-05-12 05:36:57 +00003494 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003495 DependentNameType *T
3496 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003497 if (T)
3498 return QualType(T, 0);
3499
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003500 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003501 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003502 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003503 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003504}
3505
Mike Stump11289f42009-09-09 15:08:12 +00003506QualType
John McCallc392f372010-06-11 00:33:02 +00003507ASTContext::getDependentTemplateSpecializationType(
3508 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003509 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003510 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003511 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003512 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003513 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003514 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3515 ArgCopy.push_back(Args[I].getArgument());
3516 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3517 ArgCopy.size(),
3518 ArgCopy.data());
3519}
3520
3521QualType
3522ASTContext::getDependentTemplateSpecializationType(
3523 ElaboratedTypeKeyword Keyword,
3524 NestedNameSpecifier *NNS,
3525 const IdentifierInfo *Name,
3526 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003527 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003528 assert((!NNS || NNS->isDependent()) &&
3529 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003530
Douglas Gregorc42075a2010-02-04 18:10:26 +00003531 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003532 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3533 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003534
Craig Topper36250ad2014-05-12 05:36:57 +00003535 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003536 DependentTemplateSpecializationType *T
3537 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003538 if (T)
3539 return QualType(T, 0);
3540
John McCallc392f372010-06-11 00:33:02 +00003541 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003542
John McCallc392f372010-06-11 00:33:02 +00003543 ElaboratedTypeKeyword CanonKeyword = Keyword;
3544 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3545
3546 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003547 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003548 for (unsigned I = 0; I != NumArgs; ++I) {
3549 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3550 if (!CanonArgs[I].structurallyEquals(Args[I]))
3551 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003552 }
3553
John McCallc392f372010-06-11 00:33:02 +00003554 QualType Canon;
3555 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3556 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3557 Name, NumArgs,
3558 CanonArgs.data());
3559
3560 // Find the insert position again.
3561 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3562 }
3563
3564 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3565 sizeof(TemplateArgument) * NumArgs),
3566 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003567 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003568 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003569 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003570 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003571 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003572}
3573
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003574QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003575 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003576 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003577 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003578
3579 assert(Pattern->containsUnexpandedParameterPack() &&
3580 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003581 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003582 PackExpansionType *T
3583 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3584 if (T)
3585 return QualType(T, 0);
3586
3587 QualType Canon;
3588 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003589 Canon = getCanonicalType(Pattern);
3590 // The canonical type might not contain an unexpanded parameter pack, if it
3591 // contains an alias template specialization which ignores one of its
3592 // parameters.
3593 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003594 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003595
Richard Smith68eea502012-07-16 00:20:35 +00003596 // Find the insert position again, in case we inserted an element into
3597 // PackExpansionTypes and invalidated our insert position.
3598 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3599 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003600 }
3601
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003602 T = new (*this, TypeAlignment)
3603 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003604 Types.push_back(T);
3605 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003606 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003607}
3608
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003609/// CmpProtocolNames - Comparison predicate for sorting protocols
3610/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003611static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3612 ObjCProtocolDecl *const *RHS) {
3613 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003614}
3615
John McCall8b07ec22010-05-15 11:32:37 +00003616static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003617 unsigned NumProtocols) {
3618 if (NumProtocols == 0) return true;
3619
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003620 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3621 return false;
3622
John McCallfc93cf92009-10-22 22:37:11 +00003623 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003624 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003625 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003626 return false;
3627 return true;
3628}
3629
3630static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003631 unsigned &NumProtocols) {
3632 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003633
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003634 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003635 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003636
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003637 // Canonicalize.
3638 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3639 Protocols[I] = Protocols[I]->getCanonicalDecl();
3640
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003641 // Remove duplicates.
3642 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3643 NumProtocols = ProtocolsEnd-Protocols;
3644}
3645
John McCall8b07ec22010-05-15 11:32:37 +00003646QualType ASTContext::getObjCObjectType(QualType BaseType,
3647 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003648 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003649 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003650 llvm::makeArrayRef(Protocols, NumProtocols),
3651 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003652}
3653
3654QualType ASTContext::getObjCObjectType(
3655 QualType baseType,
3656 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003657 ArrayRef<ObjCProtocolDecl *> protocols,
3658 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003659 // If the base type is an interface and there aren't any protocols or
3660 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003661 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3662 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003663 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003664
3665 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003666 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003667 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003668 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003669 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3670 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003671
Douglas Gregore9d95f12015-07-07 03:57:35 +00003672 // Determine the type arguments to be used for canonicalization,
3673 // which may be explicitly specified here or written on the base
3674 // type.
3675 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3676 if (effectiveTypeArgs.empty()) {
3677 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3678 effectiveTypeArgs = baseObject->getTypeArgs();
3679 }
John McCallfc93cf92009-10-22 22:37:11 +00003680
Douglas Gregore9d95f12015-07-07 03:57:35 +00003681 // Build the canonical type, which has the canonical base type and a
3682 // sorted-and-uniqued list of protocols and the type arguments
3683 // canonicalized.
3684 QualType canonical;
3685 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3686 effectiveTypeArgs.end(),
3687 [&](QualType type) {
3688 return type.isCanonical();
3689 });
3690 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3691 protocols.size());
3692 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3693 // Determine the canonical type arguments.
3694 ArrayRef<QualType> canonTypeArgs;
3695 SmallVector<QualType, 4> canonTypeArgsVec;
3696 if (!typeArgsAreCanonical) {
3697 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3698 for (auto typeArg : effectiveTypeArgs)
3699 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3700 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003701 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003702 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003703 }
3704
Douglas Gregore9d95f12015-07-07 03:57:35 +00003705 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3706 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3707 if (!protocolsSorted) {
3708 canonProtocolsVec.insert(canonProtocolsVec.begin(),
3709 protocols.begin(),
3710 protocols.end());
3711 unsigned uniqueCount = protocols.size();
3712 SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3713 canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3714 } else {
3715 canonProtocols = protocols;
3716 }
3717
3718 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003719 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003720
John McCallfc93cf92009-10-22 22:37:11 +00003721 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003722 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3723 }
3724
Douglas Gregore9d95f12015-07-07 03:57:35 +00003725 unsigned size = sizeof(ObjCObjectTypeImpl);
3726 size += typeArgs.size() * sizeof(QualType);
3727 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3728 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003729 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003730 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3731 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003732
3733 Types.push_back(T);
3734 ObjCObjectTypes.InsertNode(T, InsertPos);
3735 return QualType(T, 0);
3736}
3737
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003738/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3739/// protocol list adopt all protocols in QT's qualified-id protocol
3740/// list.
3741bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3742 ObjCInterfaceDecl *IC) {
3743 if (!QT->isObjCQualifiedIdType())
3744 return false;
3745
3746 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3747 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003748 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003749 if (!IC->ClassImplementsProtocol(Proto, false))
3750 return false;
3751 }
3752 return true;
3753 }
3754 return false;
3755}
3756
3757/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3758/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3759/// of protocols.
3760bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3761 ObjCInterfaceDecl *IDecl) {
3762 if (!QT->isObjCQualifiedIdType())
3763 return false;
3764 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3765 if (!OPT)
3766 return false;
3767 if (!IDecl->hasDefinition())
3768 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003769 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3770 CollectInheritedProtocols(IDecl, InheritedProtocols);
3771 if (InheritedProtocols.empty())
3772 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003773 // Check that if every protocol in list of id<plist> conforms to a protcol
3774 // of IDecl's, then bridge casting is ok.
3775 bool Conforms = false;
3776 for (auto *Proto : OPT->quals()) {
3777 Conforms = false;
3778 for (auto *PI : InheritedProtocols) {
3779 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3780 Conforms = true;
3781 break;
3782 }
3783 }
3784 if (!Conforms)
3785 break;
3786 }
3787 if (Conforms)
3788 return true;
3789
Aaron Ballman83731462014-03-17 16:14:00 +00003790 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003791 // If both the right and left sides have qualifiers.
3792 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003793 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003794 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003795 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003796 break;
3797 }
3798 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003799 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003800 }
3801 return true;
3802}
3803
John McCall8b07ec22010-05-15 11:32:37 +00003804/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3805/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003806QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003807 llvm::FoldingSetNodeID ID;
3808 ObjCObjectPointerType::Profile(ID, ObjectT);
3809
Craig Topper36250ad2014-05-12 05:36:57 +00003810 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003811 if (ObjCObjectPointerType *QT =
3812 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3813 return QualType(QT, 0);
3814
3815 // Find the canonical object type.
3816 QualType Canonical;
3817 if (!ObjectT.isCanonical()) {
3818 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3819
3820 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003821 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3822 }
3823
Douglas Gregorf85bee62010-02-08 22:59:26 +00003824 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003825 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3826 ObjCObjectPointerType *QType =
3827 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003828
Steve Narofffb4330f2009-06-17 22:40:22 +00003829 Types.push_back(QType);
3830 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003831 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003832}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003833
Douglas Gregor1c283312010-08-11 12:19:30 +00003834/// getObjCInterfaceType - Return the unique reference to the type for the
3835/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003836QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3837 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003838 if (Decl->TypeForDecl)
3839 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003840
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003841 if (PrevDecl) {
3842 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3843 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3844 return QualType(PrevDecl->TypeForDecl, 0);
3845 }
3846
Douglas Gregor7671e532011-12-16 16:34:57 +00003847 // Prefer the definition, if there is one.
3848 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3849 Decl = Def;
3850
Douglas Gregor1c283312010-08-11 12:19:30 +00003851 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3852 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3853 Decl->TypeForDecl = T;
3854 Types.push_back(T);
3855 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003856}
3857
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003858/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3859/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003860/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003861/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003862/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003863QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003864 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003865 if (tofExpr->isTypeDependent()) {
3866 llvm::FoldingSetNodeID ID;
3867 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003868
Craig Topper36250ad2014-05-12 05:36:57 +00003869 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003870 DependentTypeOfExprType *Canon
3871 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3872 if (Canon) {
3873 // We already have a "canonical" version of an identical, dependent
3874 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003875 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003876 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003877 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003878 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003879 Canon
3880 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003881 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3882 toe = Canon;
3883 }
3884 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003885 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003886 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003887 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003888 Types.push_back(toe);
3889 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003890}
3891
Steve Naroffa773cd52007-08-01 18:02:17 +00003892/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003893/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003894/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003895/// an issue. This doesn't affect the type checker, since it operates
3896/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003897QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003898 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003899 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003900 Types.push_back(tot);
3901 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003902}
3903
Anders Carlssonad6bd352009-06-24 21:24:56 +00003904
Richard Smith8eb1d322014-06-05 20:13:13 +00003905/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3906/// nodes. This would never be helpful, since each such type has its own
3907/// expression, and would not give a significant memory saving, since there
3908/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003909QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003910 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003911
3912 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003913 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003914 // unique dependent type. Two such decltype-specifiers refer to the same
3915 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003916 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003917 llvm::FoldingSetNodeID ID;
3918 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003919
Craig Topper36250ad2014-05-12 05:36:57 +00003920 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003921 DependentDecltypeType *Canon
3922 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003923 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003924 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003925 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003926 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003927 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003928 dt = new (*this, TypeAlignment)
3929 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003930 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003931 dt = new (*this, TypeAlignment)
3932 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003933 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003934 Types.push_back(dt);
3935 return QualType(dt, 0);
3936}
3937
Alexis Hunte852b102011-05-24 22:41:36 +00003938/// getUnaryTransformationType - We don't unique these, since the memory
3939/// savings are minimal and these are rare.
3940QualType ASTContext::getUnaryTransformType(QualType BaseType,
3941 QualType UnderlyingType,
3942 UnaryTransformType::UTTKind Kind)
3943 const {
3944 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003945 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3946 Kind,
3947 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003948 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003949 Types.push_back(Ty);
3950 return QualType(Ty, 0);
3951}
3952
Richard Smith2a7d4812013-05-04 07:00:32 +00003953/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3954/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3955/// canonical deduced-but-dependent 'auto' type.
3956QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003957 bool IsDependent) const {
3958 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003959 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003960
Richard Smith2a7d4812013-05-04 07:00:32 +00003961 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003962 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003963 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003964 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003965 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3966 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003967
Richard Smith74aeef52013-04-26 16:15:35 +00003968 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003969 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003970 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003971 Types.push_back(AT);
3972 if (InsertPos)
3973 AutoTypes.InsertNode(AT, InsertPos);
3974 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003975}
3976
Eli Friedman0dfb8892011-10-06 23:00:33 +00003977/// getAtomicType - Return the uniqued reference to the atomic type for
3978/// the given value type.
3979QualType ASTContext::getAtomicType(QualType T) const {
3980 // Unique pointers, to guarantee there is only one pointer of a particular
3981 // structure.
3982 llvm::FoldingSetNodeID ID;
3983 AtomicType::Profile(ID, T);
3984
Craig Topper36250ad2014-05-12 05:36:57 +00003985 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003986 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3987 return QualType(AT, 0);
3988
3989 // If the atomic value type isn't canonical, this won't be a canonical type
3990 // either, so fill in the canonical type field.
3991 QualType Canonical;
3992 if (!T.isCanonical()) {
3993 Canonical = getAtomicType(getCanonicalType(T));
3994
3995 // Get the new insert position for the node we care about.
3996 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003997 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003998 }
3999 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4000 Types.push_back(New);
4001 AtomicTypes.InsertNode(New, InsertPos);
4002 return QualType(New, 0);
4003}
4004
Richard Smith02e85f32011-04-14 22:09:26 +00004005/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4006QualType ASTContext::getAutoDeductType() const {
4007 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004008 AutoDeductTy = QualType(
4009 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004010 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004011 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004012 return AutoDeductTy;
4013}
4014
4015/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4016QualType ASTContext::getAutoRRefDeductType() const {
4017 if (AutoRRefDeductTy.isNull())
4018 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4019 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4020 return AutoRRefDeductTy;
4021}
4022
Chris Lattnerfb072462007-01-23 05:45:31 +00004023/// getTagDeclType - Return the unique reference to the type for the
4024/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004025QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004026 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004027 // FIXME: What is the design on getTagDeclType when it requires casting
4028 // away const? mutable?
4029 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004030}
4031
Mike Stump11289f42009-09-09 15:08:12 +00004032/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4033/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4034/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004035CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004036 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004037}
Chris Lattnerfb072462007-01-23 05:45:31 +00004038
Hans Wennborg27541db2011-10-27 08:29:09 +00004039/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4040CanQualType ASTContext::getIntMaxType() const {
4041 return getFromTargetType(Target->getIntMaxType());
4042}
4043
4044/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4045CanQualType ASTContext::getUIntMaxType() const {
4046 return getFromTargetType(Target->getUIntMaxType());
4047}
4048
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004049/// getSignedWCharType - Return the type of "signed wchar_t".
4050/// Used when in C++, as a GCC extension.
4051QualType ASTContext::getSignedWCharType() const {
4052 // FIXME: derive from "Target" ?
4053 return WCharTy;
4054}
4055
4056/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4057/// Used when in C++, as a GCC extension.
4058QualType ASTContext::getUnsignedWCharType() const {
4059 // FIXME: derive from "Target" ?
4060 return UnsignedIntTy;
4061}
4062
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004063QualType ASTContext::getIntPtrType() const {
4064 return getFromTargetType(Target->getIntPtrType());
4065}
4066
4067QualType ASTContext::getUIntPtrType() const {
4068 return getCorrespondingUnsignedType(getIntPtrType());
4069}
4070
Hans Wennborg27541db2011-10-27 08:29:09 +00004071/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004072/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4073QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004074 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004075}
4076
Eli Friedman4e91899e2012-11-27 02:58:24 +00004077/// \brief Return the unique type for "pid_t" defined in
4078/// <sys/types.h>. We need this to compute the correct type for vfork().
4079QualType ASTContext::getProcessIDType() const {
4080 return getFromTargetType(Target->getProcessIDType());
4081}
4082
Chris Lattnera21ad802008-04-02 05:18:44 +00004083//===----------------------------------------------------------------------===//
4084// Type Operators
4085//===----------------------------------------------------------------------===//
4086
Jay Foad39c79802011-01-12 09:06:06 +00004087CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004088 // Push qualifiers into arrays, and then discard any remaining
4089 // qualifiers.
4090 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004091 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004092 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004093 QualType Result;
4094 if (isa<ArrayType>(Ty)) {
4095 Result = getArrayDecayedType(QualType(Ty,0));
4096 } else if (isa<FunctionType>(Ty)) {
4097 Result = getPointerType(QualType(Ty, 0));
4098 } else {
4099 Result = QualType(Ty, 0);
4100 }
4101
4102 return CanQualType::CreateUnsafe(Result);
4103}
4104
John McCall6c9dd522011-01-18 07:41:22 +00004105QualType ASTContext::getUnqualifiedArrayType(QualType type,
4106 Qualifiers &quals) {
4107 SplitQualType splitType = type.getSplitUnqualifiedType();
4108
4109 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4110 // the unqualified desugared type and then drops it on the floor.
4111 // We then have to strip that sugar back off with
4112 // getUnqualifiedDesugaredType(), which is silly.
4113 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004114 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004115
4116 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004117 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004118 quals = splitType.Quals;
4119 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004120 }
4121
John McCall6c9dd522011-01-18 07:41:22 +00004122 // Otherwise, recurse on the array's element type.
4123 QualType elementType = AT->getElementType();
4124 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4125
4126 // If that didn't change the element type, AT has no qualifiers, so we
4127 // can just use the results in splitType.
4128 if (elementType == unqualElementType) {
4129 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004130 quals = splitType.Quals;
4131 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004132 }
4133
4134 // Otherwise, add in the qualifiers from the outermost type, then
4135 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004136 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004137
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004138 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004139 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004140 CAT->getSizeModifier(), 0);
4141 }
4142
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004143 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004144 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004145 }
4146
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004147 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004148 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004149 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004150 VAT->getSizeModifier(),
4151 VAT->getIndexTypeCVRQualifiers(),
4152 VAT->getBracketsRange());
4153 }
4154
4155 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004156 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004157 DSAT->getSizeModifier(), 0,
4158 SourceRange());
4159}
4160
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004161/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4162/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4163/// they point to and return true. If T1 and T2 aren't pointer types
4164/// or pointer-to-member types, or if they are not similar at this
4165/// level, returns false and leaves T1 and T2 unchanged. Top-level
4166/// qualifiers on T1 and T2 are ignored. This function will typically
4167/// be called in a loop that successively "unwraps" pointer and
4168/// pointer-to-member types to compare them at each level.
4169bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4170 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4171 *T2PtrType = T2->getAs<PointerType>();
4172 if (T1PtrType && T2PtrType) {
4173 T1 = T1PtrType->getPointeeType();
4174 T2 = T2PtrType->getPointeeType();
4175 return true;
4176 }
4177
4178 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4179 *T2MPType = T2->getAs<MemberPointerType>();
4180 if (T1MPType && T2MPType &&
4181 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4182 QualType(T2MPType->getClass(), 0))) {
4183 T1 = T1MPType->getPointeeType();
4184 T2 = T2MPType->getPointeeType();
4185 return true;
4186 }
4187
David Blaikiebbafb8a2012-03-11 07:00:24 +00004188 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004189 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4190 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4191 if (T1OPType && T2OPType) {
4192 T1 = T1OPType->getPointeeType();
4193 T2 = T2OPType->getPointeeType();
4194 return true;
4195 }
4196 }
4197
4198 // FIXME: Block pointers, too?
4199
4200 return false;
4201}
4202
Jay Foad39c79802011-01-12 09:06:06 +00004203DeclarationNameInfo
4204ASTContext::getNameForTemplate(TemplateName Name,
4205 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004206 switch (Name.getKind()) {
4207 case TemplateName::QualifiedTemplate:
4208 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004209 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004210 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4211 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004212
John McCalld9dfe3a2011-06-30 08:33:18 +00004213 case TemplateName::OverloadedTemplate: {
4214 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4215 // DNInfo work in progress: CHECKME: what about DNLoc?
4216 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4217 }
4218
4219 case TemplateName::DependentTemplate: {
4220 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004221 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004222 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004223 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4224 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004225 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004226 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4227 // DNInfo work in progress: FIXME: source locations?
4228 DeclarationNameLoc DNLoc;
4229 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4230 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4231 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004232 }
4233 }
4234
John McCalld9dfe3a2011-06-30 08:33:18 +00004235 case TemplateName::SubstTemplateTemplateParm: {
4236 SubstTemplateTemplateParmStorage *subst
4237 = Name.getAsSubstTemplateTemplateParm();
4238 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4239 NameLoc);
4240 }
4241
4242 case TemplateName::SubstTemplateTemplateParmPack: {
4243 SubstTemplateTemplateParmPackStorage *subst
4244 = Name.getAsSubstTemplateTemplateParmPack();
4245 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4246 NameLoc);
4247 }
4248 }
4249
4250 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004251}
4252
Jay Foad39c79802011-01-12 09:06:06 +00004253TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004254 switch (Name.getKind()) {
4255 case TemplateName::QualifiedTemplate:
4256 case TemplateName::Template: {
4257 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004258 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004259 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004260 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4261
4262 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004263 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004264 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004265
John McCalld9dfe3a2011-06-30 08:33:18 +00004266 case TemplateName::OverloadedTemplate:
4267 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004268
John McCalld9dfe3a2011-06-30 08:33:18 +00004269 case TemplateName::DependentTemplate: {
4270 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4271 assert(DTN && "Non-dependent template names must refer to template decls.");
4272 return DTN->CanonicalTemplateName;
4273 }
4274
4275 case TemplateName::SubstTemplateTemplateParm: {
4276 SubstTemplateTemplateParmStorage *subst
4277 = Name.getAsSubstTemplateTemplateParm();
4278 return getCanonicalTemplateName(subst->getReplacement());
4279 }
4280
4281 case TemplateName::SubstTemplateTemplateParmPack: {
4282 SubstTemplateTemplateParmPackStorage *subst
4283 = Name.getAsSubstTemplateTemplateParmPack();
4284 TemplateTemplateParmDecl *canonParameter
4285 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4286 TemplateArgument canonArgPack
4287 = getCanonicalTemplateArgument(subst->getArgumentPack());
4288 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4289 }
4290 }
4291
4292 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004293}
4294
Douglas Gregoradee3e32009-11-11 23:06:43 +00004295bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4296 X = getCanonicalTemplateName(X);
4297 Y = getCanonicalTemplateName(Y);
4298 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4299}
4300
Mike Stump11289f42009-09-09 15:08:12 +00004301TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004302ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004303 switch (Arg.getKind()) {
4304 case TemplateArgument::Null:
4305 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004306
Douglas Gregora8e02e72009-07-28 23:00:59 +00004307 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004308 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004309
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004310 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004311 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004312 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004313 }
Mike Stump11289f42009-09-09 15:08:12 +00004314
Eli Friedmanb826a002012-09-26 02:36:12 +00004315 case TemplateArgument::NullPtr:
4316 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4317 /*isNullPtr*/true);
4318
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004319 case TemplateArgument::Template:
4320 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004321
4322 case TemplateArgument::TemplateExpansion:
4323 return TemplateArgument(getCanonicalTemplateName(
4324 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004325 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004326
Douglas Gregora8e02e72009-07-28 23:00:59 +00004327 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004328 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004329
Douglas Gregora8e02e72009-07-28 23:00:59 +00004330 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004331 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004332
Douglas Gregora8e02e72009-07-28 23:00:59 +00004333 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004334 if (Arg.pack_size() == 0)
4335 return Arg;
4336
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004337 TemplateArgument *CanonArgs
4338 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004339 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004340 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004341 AEnd = Arg.pack_end();
4342 A != AEnd; (void)++A, ++Idx)
4343 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004344
Benjamin Kramercce63472015-08-05 09:40:22 +00004345 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004346 }
4347 }
4348
4349 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004350 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004351}
4352
Douglas Gregor333489b2009-03-27 23:10:48 +00004353NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004354ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004355 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004356 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004357
4358 switch (NNS->getKind()) {
4359 case NestedNameSpecifier::Identifier:
4360 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004361 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004362 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4363 NNS->getAsIdentifier());
4364
4365 case NestedNameSpecifier::Namespace:
4366 // A namespace is canonical; build a nested-name-specifier with
4367 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004368 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004369 NNS->getAsNamespace()->getOriginalNamespace());
4370
4371 case NestedNameSpecifier::NamespaceAlias:
4372 // A namespace is canonical; build a nested-name-specifier with
4373 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004374 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004375 NNS->getAsNamespaceAlias()->getNamespace()
4376 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004377
4378 case NestedNameSpecifier::TypeSpec:
4379 case NestedNameSpecifier::TypeSpecWithTemplate: {
4380 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004381
4382 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4383 // break it apart into its prefix and identifier, then reconsititute those
4384 // as the canonical nested-name-specifier. This is required to canonicalize
4385 // a dependent nested-name-specifier involving typedefs of dependent-name
4386 // types, e.g.,
4387 // typedef typename T::type T1;
4388 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004389 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4390 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004391 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004392
Eli Friedman5358a0a2012-03-03 04:09:56 +00004393 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4394 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4395 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004396 return NestedNameSpecifier::Create(*this, nullptr, false,
4397 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004398 }
4399
4400 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004401 case NestedNameSpecifier::Super:
4402 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004403 return NNS;
4404 }
4405
David Blaikie8a40f702012-01-17 06:56:22 +00004406 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004407}
4408
Chris Lattner7adf0762008-08-04 07:31:14 +00004409
Jay Foad39c79802011-01-12 09:06:06 +00004410const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004411 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004412 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004413 // Handle the common positive case fast.
4414 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4415 return AT;
4416 }
Mike Stump11289f42009-09-09 15:08:12 +00004417
John McCall8ccfcb52009-09-24 19:53:00 +00004418 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004419 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004420 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004421
John McCall8ccfcb52009-09-24 19:53:00 +00004422 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004423 // implements C99 6.7.3p8: "If the specification of an array type includes
4424 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004425
Chris Lattner7adf0762008-08-04 07:31:14 +00004426 // If we get here, we either have type qualifiers on the type, or we have
4427 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004428 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004429
John McCall33ddac02011-01-19 10:06:00 +00004430 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004431 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004432
Chris Lattner7adf0762008-08-04 07:31:14 +00004433 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004434 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004435 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004436 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004437
Chris Lattner7adf0762008-08-04 07:31:14 +00004438 // Otherwise, we have an array and we have qualifiers on it. Push the
4439 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004440 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004441
Chris Lattner7adf0762008-08-04 07:31:14 +00004442 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4443 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4444 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004445 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004446 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4447 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4448 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004449 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004450
Mike Stump11289f42009-09-09 15:08:12 +00004451 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004452 = dyn_cast<DependentSizedArrayType>(ATy))
4453 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004454 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004455 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004456 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004457 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004458 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004459
Chris Lattner7adf0762008-08-04 07:31:14 +00004460 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004461 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004462 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004463 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004464 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004465 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004466}
4467
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004468QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004469 if (T->isArrayType() || T->isFunctionType())
4470 return getDecayedType(T);
4471 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004472}
4473
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004474QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004475 T = getVariableArrayDecayedType(T);
4476 T = getAdjustedParameterType(T);
4477 return T.getUnqualifiedType();
4478}
4479
David Majnemerd09a51c2015-03-03 01:50:05 +00004480QualType ASTContext::getExceptionObjectType(QualType T) const {
4481 // C++ [except.throw]p3:
4482 // A throw-expression initializes a temporary object, called the exception
4483 // object, the type of which is determined by removing any top-level
4484 // cv-qualifiers from the static type of the operand of throw and adjusting
4485 // the type from "array of T" or "function returning T" to "pointer to T"
4486 // or "pointer to function returning T", [...]
4487 T = getVariableArrayDecayedType(T);
4488 if (T->isArrayType() || T->isFunctionType())
4489 T = getDecayedType(T);
4490 return T.getUnqualifiedType();
4491}
4492
Chris Lattnera21ad802008-04-02 05:18:44 +00004493/// getArrayDecayedType - Return the properly qualified result of decaying the
4494/// specified array type to a pointer. This operation is non-trivial when
4495/// handling typedefs etc. The canonical type of "T" must be an array type,
4496/// this returns a pointer to a properly qualified element of the array.
4497///
4498/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004499QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004500 // Get the element type with 'getAsArrayType' so that we don't lose any
4501 // typedefs in the element type of the array. This also handles propagation
4502 // of type qualifiers from the array type into the element type if present
4503 // (C99 6.7.3p8).
4504 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4505 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004506
Chris Lattner7adf0762008-08-04 07:31:14 +00004507 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004508
4509 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004510 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004511}
4512
John McCall33ddac02011-01-19 10:06:00 +00004513QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4514 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004515}
4516
John McCall33ddac02011-01-19 10:06:00 +00004517QualType ASTContext::getBaseElementType(QualType type) const {
4518 Qualifiers qs;
4519 while (true) {
4520 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004521 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004522 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004523
John McCall33ddac02011-01-19 10:06:00 +00004524 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004525 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004526 }
Mike Stump11289f42009-09-09 15:08:12 +00004527
John McCall33ddac02011-01-19 10:06:00 +00004528 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004529}
4530
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004531/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004532uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004533ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4534 uint64_t ElementCount = 1;
4535 do {
4536 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004537 CA = dyn_cast_or_null<ConstantArrayType>(
4538 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004539 } while (CA);
4540 return ElementCount;
4541}
4542
Steve Naroff0af91202007-04-27 21:51:21 +00004543/// getFloatingRank - Return a relative rank for floating point types.
4544/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004545static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004546 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004547 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004548
John McCall9dd450b2009-09-21 23:43:11 +00004549 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4550 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004551 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004552 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004553 case BuiltinType::Float: return FloatRank;
4554 case BuiltinType::Double: return DoubleRank;
4555 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004556 }
4557}
4558
Mike Stump11289f42009-09-09 15:08:12 +00004559/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4560/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004561/// 'typeDomain' is a real floating point or complex type.
4562/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004563QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4564 QualType Domain) const {
4565 FloatingRank EltRank = getFloatingRank(Size);
4566 if (Domain->isComplexType()) {
4567 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004568 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004569 case FloatRank: return FloatComplexTy;
4570 case DoubleRank: return DoubleComplexTy;
4571 case LongDoubleRank: return LongDoubleComplexTy;
4572 }
Steve Naroff0af91202007-04-27 21:51:21 +00004573 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004574
4575 assert(Domain->isRealFloatingType() && "Unknown domain!");
4576 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004577 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004578 case FloatRank: return FloatTy;
4579 case DoubleRank: return DoubleTy;
4580 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004581 }
David Blaikief47fa302012-01-17 02:30:50 +00004582 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004583}
4584
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004585/// getFloatingTypeOrder - Compare the rank of the two specified floating
4586/// point types, ignoring the domain of the type (i.e. 'double' ==
4587/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004588/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004589int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004590 FloatingRank LHSR = getFloatingRank(LHS);
4591 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004592
Chris Lattnerb90739d2008-04-06 23:38:49 +00004593 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004594 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004595 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004596 return 1;
4597 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004598}
4599
Chris Lattner76a00cf2008-04-06 22:59:24 +00004600/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4601/// routine will assert if passed a built-in type that isn't an integer or enum,
4602/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004603unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004604 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004605
Chris Lattner76a00cf2008-04-06 22:59:24 +00004606 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004607 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004608 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004609 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004610 case BuiltinType::Char_S:
4611 case BuiltinType::Char_U:
4612 case BuiltinType::SChar:
4613 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004614 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004615 case BuiltinType::Short:
4616 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004617 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004618 case BuiltinType::Int:
4619 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004620 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004621 case BuiltinType::Long:
4622 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004623 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004624 case BuiltinType::LongLong:
4625 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004626 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004627 case BuiltinType::Int128:
4628 case BuiltinType::UInt128:
4629 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004630 }
4631}
4632
Eli Friedman629ffb92009-08-20 04:21:42 +00004633/// \brief Whether this is a promotable bitfield reference according
4634/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4635///
4636/// \returns the type this bit-field will promote to, or NULL if no
4637/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004638QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004639 if (E->isTypeDependent() || E->isValueDependent())
4640 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004641
4642 // FIXME: We should not do this unless E->refersToBitField() is true. This
4643 // matters in C where getSourceBitField() will find bit-fields for various
4644 // cases where the source expression is not a bit-field designator.
4645
John McCalld25db7e2013-05-06 21:39:12 +00004646 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004647 if (!Field)
4648 return QualType();
4649
4650 QualType FT = Field->getType();
4651
Richard Smithcaf33902011-10-10 18:28:20 +00004652 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004653 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004654 // C++ [conv.prom]p5:
4655 // A prvalue for an integral bit-field can be converted to a prvalue of type
4656 // int if int can represent all the values of the bit-field; otherwise, it
4657 // can be converted to unsigned int if unsigned int can represent all the
4658 // values of the bit-field. If the bit-field is larger yet, no integral
4659 // promotion applies to it.
4660 // C11 6.3.1.1/2:
4661 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4662 // If an int can represent all values of the original type (as restricted by
4663 // the width, for a bit-field), the value is converted to an int; otherwise,
4664 // it is converted to an unsigned int.
4665 //
4666 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4667 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004668 if (BitWidth < IntSize)
4669 return IntTy;
4670
4671 if (BitWidth == IntSize)
4672 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4673
4674 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004675 // like the base type. GCC has some weird bugs in this area that we
4676 // deliberately do not follow (GCC follows a pre-standard resolution to
4677 // C's DR315 which treats bit-width as being part of the type, and this leaks
4678 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004679 return QualType();
4680}
4681
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004682/// getPromotedIntegerType - Returns the type that Promotable will
4683/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4684/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004685QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004686 assert(!Promotable.isNull());
4687 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004688 if (const EnumType *ET = Promotable->getAs<EnumType>())
4689 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004690
4691 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4692 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4693 // (3.9.1) can be converted to a prvalue of the first of the following
4694 // types that can represent all the values of its underlying type:
4695 // int, unsigned int, long int, unsigned long int, long long int, or
4696 // unsigned long long int [...]
4697 // FIXME: Is there some better way to compute this?
4698 if (BT->getKind() == BuiltinType::WChar_S ||
4699 BT->getKind() == BuiltinType::WChar_U ||
4700 BT->getKind() == BuiltinType::Char16 ||
4701 BT->getKind() == BuiltinType::Char32) {
4702 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4703 uint64_t FromSize = getTypeSize(BT);
4704 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4705 LongLongTy, UnsignedLongLongTy };
4706 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4707 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4708 if (FromSize < ToSize ||
4709 (FromSize == ToSize &&
4710 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4711 return PromoteTypes[Idx];
4712 }
4713 llvm_unreachable("char type should fit into long long");
4714 }
4715 }
4716
4717 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004718 if (Promotable->isSignedIntegerType())
4719 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004720 uint64_t PromotableSize = getIntWidth(Promotable);
4721 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004722 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4723 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4724}
4725
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004726/// \brief Recurses in pointer/array types until it finds an objc retainable
4727/// type and returns its ownership.
4728Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4729 while (!T.isNull()) {
4730 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4731 return T.getObjCLifetime();
4732 if (T->isArrayType())
4733 T = getBaseElementType(T);
4734 else if (const PointerType *PT = T->getAs<PointerType>())
4735 T = PT->getPointeeType();
4736 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004737 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004738 else
4739 break;
4740 }
4741
4742 return Qualifiers::OCL_None;
4743}
4744
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004745static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4746 // Incomplete enum types are not treated as integer types.
4747 // FIXME: In C++, enum types are never integer types.
4748 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4749 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004750 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004751}
4752
Mike Stump11289f42009-09-09 15:08:12 +00004753/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004754/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004755/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004756int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004757 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4758 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004759
4760 // Unwrap enums to their underlying type.
4761 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4762 LHSC = getIntegerTypeForEnum(ET);
4763 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4764 RHSC = getIntegerTypeForEnum(ET);
4765
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004766 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004767
Chris Lattner76a00cf2008-04-06 22:59:24 +00004768 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4769 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004770
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004771 unsigned LHSRank = getIntegerRank(LHSC);
4772 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004773
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004774 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4775 if (LHSRank == RHSRank) return 0;
4776 return LHSRank > RHSRank ? 1 : -1;
4777 }
Mike Stump11289f42009-09-09 15:08:12 +00004778
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004779 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4780 if (LHSUnsigned) {
4781 // If the unsigned [LHS] type is larger, return it.
4782 if (LHSRank >= RHSRank)
4783 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004784
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004785 // If the signed type can represent all values of the unsigned type, it
4786 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004787 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004788 return -1;
4789 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004790
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004791 // If the unsigned [RHS] type is larger, return it.
4792 if (RHSRank >= LHSRank)
4793 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004794
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004795 // If the signed type can represent all values of the unsigned type, it
4796 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004797 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004798 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004799}
Anders Carlsson98f07902007-08-17 05:31:46 +00004800
Mike Stump11289f42009-09-09 15:08:12 +00004801// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004802QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004803 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004804 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004805 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004806
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004807 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004808
Anders Carlsson98f07902007-08-17 05:31:46 +00004809 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004810 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004811 // int flags;
4812 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004813 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004814 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004815 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004816 FieldTypes[3] = LongTy;
4817
Anders Carlsson98f07902007-08-17 05:31:46 +00004818 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004819 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004820 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004821 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004822 SourceLocation(), nullptr,
4823 FieldTypes[i], /*TInfo=*/nullptr,
4824 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004825 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004826 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004827 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004828 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004829 }
4830
Douglas Gregord5058122010-02-11 01:19:42 +00004831 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004832 }
Mike Stump11289f42009-09-09 15:08:12 +00004833
Anders Carlsson98f07902007-08-17 05:31:46 +00004834 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004835}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004836
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004837QualType ASTContext::getObjCSuperType() const {
4838 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004839 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004840 TUDecl->addDecl(ObjCSuperTypeDecl);
4841 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4842 }
4843 return ObjCSuperType;
4844}
4845
Douglas Gregor512b0772009-04-23 22:29:11 +00004846void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004847 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004848 assert(Rec && "Invalid CFConstantStringType");
4849 CFConstantStringTypeDecl = Rec->getDecl();
4850}
4851
Jay Foad39c79802011-01-12 09:06:06 +00004852QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004853 if (BlockDescriptorType)
4854 return getTagDeclType(BlockDescriptorType);
4855
Alp Toker2dea15b2013-12-17 01:22:38 +00004856 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004857 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004858 RD = buildImplicitRecord("__block_descriptor");
4859 RD->startDefinition();
4860
Mike Stumpd0153282009-10-20 02:12:22 +00004861 QualType FieldTypes[] = {
4862 UnsignedLongTy,
4863 UnsignedLongTy,
4864 };
4865
Craig Topperd6d31ac2013-07-15 08:24:27 +00004866 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004867 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004868 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004869 };
4870
4871 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004872 FieldDecl *Field = FieldDecl::Create(
4873 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004874 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4875 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004876 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004877 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004878 }
4879
Alp Toker2dea15b2013-12-17 01:22:38 +00004880 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004881
Alp Toker2dea15b2013-12-17 01:22:38 +00004882 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004883
4884 return getTagDeclType(BlockDescriptorType);
4885}
4886
Jay Foad39c79802011-01-12 09:06:06 +00004887QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004888 if (BlockDescriptorExtendedType)
4889 return getTagDeclType(BlockDescriptorExtendedType);
4890
Alp Toker2dea15b2013-12-17 01:22:38 +00004891 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004892 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004893 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4894 RD->startDefinition();
4895
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004896 QualType FieldTypes[] = {
4897 UnsignedLongTy,
4898 UnsignedLongTy,
4899 getPointerType(VoidPtrTy),
4900 getPointerType(VoidPtrTy)
4901 };
4902
Craig Topperd6d31ac2013-07-15 08:24:27 +00004903 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004904 "reserved",
4905 "Size",
4906 "CopyFuncPtr",
4907 "DestroyFuncPtr"
4908 };
4909
4910 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004911 FieldDecl *Field = FieldDecl::Create(
4912 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004913 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4914 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004915 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004916 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004917 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004918 }
4919
Alp Toker2dea15b2013-12-17 01:22:38 +00004920 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004921
Alp Toker2dea15b2013-12-17 01:22:38 +00004922 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004923 return getTagDeclType(BlockDescriptorExtendedType);
4924}
4925
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004926/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4927/// requires copy/dispose. Note that this must match the logic
4928/// in buildByrefHelpers.
4929bool ASTContext::BlockRequiresCopying(QualType Ty,
4930 const VarDecl *D) {
4931 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4932 const Expr *copyExpr = getBlockVarCopyInits(D);
4933 if (!copyExpr && record->hasTrivialDestructor()) return false;
4934
Mike Stump94967902009-10-21 18:16:27 +00004935 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004936 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004937
4938 if (!Ty->isObjCRetainableType()) return false;
4939
4940 Qualifiers qs = Ty.getQualifiers();
4941
4942 // If we have lifetime, that dominates.
4943 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4944 assert(getLangOpts().ObjCAutoRefCount);
4945
4946 switch (lifetime) {
4947 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4948
4949 // These are just bits as far as the runtime is concerned.
4950 case Qualifiers::OCL_ExplicitNone:
4951 case Qualifiers::OCL_Autoreleasing:
4952 return false;
4953
4954 // Tell the runtime that this is ARC __weak, called by the
4955 // byref routines.
4956 case Qualifiers::OCL_Weak:
4957 // ARC __strong __block variables need to be retained.
4958 case Qualifiers::OCL_Strong:
4959 return true;
4960 }
4961 llvm_unreachable("fell out of lifetime switch!");
4962 }
4963 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4964 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004965}
4966
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004967bool ASTContext::getByrefLifetime(QualType Ty,
4968 Qualifiers::ObjCLifetime &LifeTime,
4969 bool &HasByrefExtendedLayout) const {
4970
4971 if (!getLangOpts().ObjC1 ||
4972 getLangOpts().getGC() != LangOptions::NonGC)
4973 return false;
4974
4975 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004976 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004977 HasByrefExtendedLayout = true;
4978 LifeTime = Qualifiers::OCL_None;
4979 }
4980 else if (getLangOpts().ObjCAutoRefCount)
4981 LifeTime = Ty.getObjCLifetime();
4982 // MRR.
4983 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4984 LifeTime = Qualifiers::OCL_ExplicitNone;
4985 else
4986 LifeTime = Qualifiers::OCL_None;
4987 return true;
4988}
4989
Douglas Gregorbab8a962011-09-08 01:46:34 +00004990TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4991 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004992 ObjCInstanceTypeDecl =
4993 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004994 return ObjCInstanceTypeDecl;
4995}
4996
Anders Carlsson18acd442007-10-29 06:33:42 +00004997// This returns true if a type has been typedefed to BOOL:
4998// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004999static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005000 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005001 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5002 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005003
Anders Carlssond8499822007-10-29 05:01:08 +00005004 return false;
5005}
5006
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005007/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005008/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005009CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005010 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5011 return CharUnits::Zero();
5012
Ken Dyck40775002010-01-11 17:06:35 +00005013 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005014
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005015 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005016 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005017 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005018 // Treat arrays as pointers, since that's how they're passed in.
5019 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005020 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005021 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005022}
5023
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005024bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5025 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
5026 VD->getType()->isIntegralOrEnumerationType() &&
Alexey Bataev15413ea2015-05-20 11:57:02 +00005027 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005028}
5029
Ken Dyck40775002010-01-11 17:06:35 +00005030static inline
5031std::string charUnitsToString(const CharUnits &CU) {
5032 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005033}
5034
John McCall351762c2011-02-07 10:33:21 +00005035/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005036/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005037std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5038 std::string S;
5039
David Chisnall950a9512009-11-17 19:33:30 +00005040 const BlockDecl *Decl = Expr->getBlockDecl();
5041 QualType BlockTy =
5042 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5043 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005044 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005045 getObjCEncodingForMethodParameter(
5046 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5047 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005048 else
Alp Toker314cc812014-01-25 16:55:45 +00005049 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005050 // Compute size of all parameters.
5051 // Start with computing size of a pointer in number of bytes.
5052 // FIXME: There might(should) be a better way of doing this computation!
5053 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005054 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5055 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005056 for (auto PI : Decl->params()) {
5057 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005058 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005059 if (sz.isZero())
5060 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005061 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005062 ParmOffset += sz;
5063 }
5064 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005065 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005066 // Block pointer and offset.
5067 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005068
5069 // Argument types.
5070 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005071 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005072 QualType PType = PVDecl->getOriginalType();
5073 if (const ArrayType *AT =
5074 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5075 // Use array's original type only if it has known number of
5076 // elements.
5077 if (!isa<ConstantArrayType>(AT))
5078 PType = PVDecl->getType();
5079 } else if (PType->isFunctionType())
5080 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005081 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005082 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5083 S, true /*Extended*/);
5084 else
5085 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005086 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005087 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005088 }
John McCall351762c2011-02-07 10:33:21 +00005089
5090 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005091}
5092
Douglas Gregora9d84932011-05-27 01:19:52 +00005093bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005094 std::string& S) {
5095 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005096 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005097 CharUnits ParmOffset;
5098 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005099 for (auto PI : Decl->params()) {
5100 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005101 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005102 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005103 continue;
5104
David Chisnall50e4eba2010-12-30 14:05:53 +00005105 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005106 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005107 ParmOffset += sz;
5108 }
5109 S += charUnitsToString(ParmOffset);
5110 ParmOffset = CharUnits::Zero();
5111
5112 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005113 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005114 QualType PType = PVDecl->getOriginalType();
5115 if (const ArrayType *AT =
5116 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5117 // Use array's original type only if it has known number of
5118 // elements.
5119 if (!isa<ConstantArrayType>(AT))
5120 PType = PVDecl->getType();
5121 } else if (PType->isFunctionType())
5122 PType = PVDecl->getType();
5123 getObjCEncodingForType(PType, S);
5124 S += charUnitsToString(ParmOffset);
5125 ParmOffset += getObjCEncodingTypeSize(PType);
5126 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005127
5128 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005129}
5130
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005131/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5132/// method parameter or return type. If Extended, include class names and
5133/// block object types.
5134void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5135 QualType T, std::string& S,
5136 bool Extended) const {
5137 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5138 getObjCEncodingForTypeQualifier(QT, S);
5139 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005140 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005141 true /*OutermostType*/,
5142 false /*EncodingProperty*/,
5143 false /*StructField*/,
5144 Extended /*EncodeBlockParameters*/,
5145 Extended /*EncodeClassNames*/);
5146}
5147
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005148/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005149/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005150bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005151 std::string& S,
5152 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005153 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005154 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005155 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5156 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005157 // Compute size of all parameters.
5158 // Start with computing size of a pointer in number of bytes.
5159 // FIXME: There might(should) be a better way of doing this computation!
5160 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005161 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005162 // The first two arguments (self and _cmd) are pointers; account for
5163 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005164 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005165 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005166 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005167 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005168 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005169 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005170 continue;
5171
Ken Dyck40775002010-01-11 17:06:35 +00005172 assert (sz.isPositive() &&
5173 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005174 ParmOffset += sz;
5175 }
Ken Dyck40775002010-01-11 17:06:35 +00005176 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005177 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005178 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005179
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005180 // Argument types.
5181 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005182 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005183 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005184 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005185 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005186 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005187 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5188 // Use array's original type only if it has known number of
5189 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005190 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005191 PType = PVDecl->getType();
5192 } else if (PType->isFunctionType())
5193 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005194 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5195 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005196 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005197 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005198 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005199
5200 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005201}
5202
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005203ObjCPropertyImplDecl *
5204ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5205 const ObjCPropertyDecl *PD,
5206 const Decl *Container) const {
5207 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005208 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005209 if (const ObjCCategoryImplDecl *CID =
5210 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005211 for (auto *PID : CID->property_impls())
5212 if (PID->getPropertyDecl() == PD)
5213 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005214 } else {
5215 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5216 for (auto *PID : OID->property_impls())
5217 if (PID->getPropertyDecl() == PD)
5218 return PID;
5219 }
5220 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005221}
5222
Daniel Dunbar4932b362008-08-28 04:38:10 +00005223/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005224/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005225/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5226/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005227/// Property attributes are stored as a comma-delimited C string. The simple
5228/// attributes readonly and bycopy are encoded as single characters. The
5229/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5230/// encoded as single characters, followed by an identifier. Property types
5231/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005232/// these attributes are defined by the following enumeration:
5233/// @code
5234/// enum PropertyAttributes {
5235/// kPropertyReadOnly = 'R', // property is read-only.
5236/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5237/// kPropertyByref = '&', // property is a reference to the value last assigned
5238/// kPropertyDynamic = 'D', // property is dynamic
5239/// kPropertyGetter = 'G', // followed by getter selector name
5240/// kPropertySetter = 'S', // followed by setter selector name
5241/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005242/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005243/// kPropertyWeak = 'W' // 'weak' property
5244/// kPropertyStrong = 'P' // property GC'able
5245/// kPropertyNonAtomic = 'N' // property non-atomic
5246/// };
5247/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005248void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005249 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005250 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005251 // Collect information from the property implementation decl(s).
5252 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005253 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005254
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005255 if (ObjCPropertyImplDecl *PropertyImpDecl =
5256 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5257 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5258 Dynamic = true;
5259 else
5260 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005261 }
5262
5263 // FIXME: This is not very efficient.
5264 S = "T";
5265
5266 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005267 // GCC has some special rules regarding encoding of properties which
5268 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005269 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005270
5271 if (PD->isReadOnly()) {
5272 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005273 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5274 S += ",C";
5275 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5276 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005277 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5278 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005279 } else {
5280 switch (PD->getSetterKind()) {
5281 case ObjCPropertyDecl::Assign: break;
5282 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005283 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005284 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005285 }
5286 }
5287
5288 // It really isn't clear at all what this means, since properties
5289 // are "dynamic by default".
5290 if (Dynamic)
5291 S += ",D";
5292
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005293 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5294 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005295
Daniel Dunbar4932b362008-08-28 04:38:10 +00005296 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5297 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005298 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005299 }
5300
5301 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5302 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005303 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005304 }
5305
5306 if (SynthesizePID) {
5307 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5308 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005309 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005310 }
5311
5312 // FIXME: OBJCGC: weak & strong
5313}
5314
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005315/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005316/// Another legacy compatibility encoding: 32-bit longs are encoded as
5317/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005318/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5319///
5320void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005321 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005322 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005323 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005324 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005325 else
Jay Foad39c79802011-01-12 09:06:06 +00005326 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005327 PointeeTy = IntTy;
5328 }
5329 }
5330}
5331
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005332void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005333 const FieldDecl *Field,
5334 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005335 // We follow the behavior of gcc, expanding structures which are
5336 // directly pointed to, and expanding embedded structures. Note that
5337 // these rules are sufficient to prevent recursive encoding of the
5338 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005339 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005340 true /* outermost type */, false, false,
5341 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005342}
5343
Joe Groff98ac7d22014-07-07 22:25:15 +00005344void ASTContext::getObjCEncodingForPropertyType(QualType T,
5345 std::string& S) const {
5346 // Encode result type.
5347 // GCC has some special rules regarding encoding of properties which
5348 // closely resembles encoding of ivars.
5349 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5350 true /* outermost type */,
5351 true /* encoding property */);
5352}
5353
John McCall393a78d2012-12-20 02:45:14 +00005354static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5355 BuiltinType::Kind kind) {
5356 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005357 case BuiltinType::Void: return 'v';
5358 case BuiltinType::Bool: return 'B';
5359 case BuiltinType::Char_U:
5360 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005361 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005362 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005363 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005364 case BuiltinType::UInt: return 'I';
5365 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005366 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005367 case BuiltinType::UInt128: return 'T';
5368 case BuiltinType::ULongLong: return 'Q';
5369 case BuiltinType::Char_S:
5370 case BuiltinType::SChar: return 'c';
5371 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005372 case BuiltinType::WChar_S:
5373 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005374 case BuiltinType::Int: return 'i';
5375 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005376 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005377 case BuiltinType::LongLong: return 'q';
5378 case BuiltinType::Int128: return 't';
5379 case BuiltinType::Float: return 'f';
5380 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005381 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005382 case BuiltinType::NullPtr: return '*'; // like char*
5383
5384 case BuiltinType::Half:
5385 // FIXME: potentially need @encodes for these!
5386 return ' ';
5387
5388 case BuiltinType::ObjCId:
5389 case BuiltinType::ObjCClass:
5390 case BuiltinType::ObjCSel:
5391 llvm_unreachable("@encoding ObjC primitive type");
5392
5393 // OpenCL and placeholder types don't need @encodings.
5394 case BuiltinType::OCLImage1d:
5395 case BuiltinType::OCLImage1dArray:
5396 case BuiltinType::OCLImage1dBuffer:
5397 case BuiltinType::OCLImage2d:
5398 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005399 case BuiltinType::OCLImage2dDepth:
5400 case BuiltinType::OCLImage2dArrayDepth:
5401 case BuiltinType::OCLImage2dMSAA:
5402 case BuiltinType::OCLImage2dArrayMSAA:
5403 case BuiltinType::OCLImage2dMSAADepth:
5404 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005405 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005406 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005407 case BuiltinType::OCLClkEvent:
5408 case BuiltinType::OCLQueue:
5409 case BuiltinType::OCLNDRange:
5410 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005411 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005412 case BuiltinType::Dependent:
5413#define BUILTIN_TYPE(KIND, ID)
5414#define PLACEHOLDER_TYPE(KIND, ID) \
5415 case BuiltinType::KIND:
5416#include "clang/AST/BuiltinTypes.def"
5417 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005418 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005419 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005420}
5421
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005422static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5423 EnumDecl *Enum = ET->getDecl();
5424
5425 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5426 if (!Enum->isFixed())
5427 return 'i';
5428
5429 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005430 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5431 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005432}
5433
Jay Foad39c79802011-01-12 09:06:06 +00005434static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005435 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005436 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005437 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005438 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5439 // The GNU runtime requires more information; bitfields are encoded as b,
5440 // then the offset (in bits) of the first element, then the type of the
5441 // bitfield, then the size in bits. For example, in this structure:
5442 //
5443 // struct
5444 // {
5445 // int integer;
5446 // int flags:2;
5447 // };
5448 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5449 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5450 // information is not especially sensible, but we're stuck with it for
5451 // compatibility with GCC, although providing it breaks anything that
5452 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005453 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005454 const RecordDecl *RD = FD->getParent();
5455 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005456 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005457 if (const EnumType *ET = T->getAs<EnumType>())
5458 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005459 else {
5460 const BuiltinType *BT = T->castAs<BuiltinType>();
5461 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5462 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005463 }
Richard Smithcaf33902011-10-10 18:28:20 +00005464 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005465}
5466
Daniel Dunbar07d07852009-10-18 21:17:35 +00005467// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005468void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5469 bool ExpandPointedToStructures,
5470 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005471 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005472 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005473 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005474 bool StructField,
5475 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005476 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005477 bool EncodePointerToObjCTypedef,
5478 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005479 CanQualType CT = getCanonicalType(T);
5480 switch (CT->getTypeClass()) {
5481 case Type::Builtin:
5482 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005483 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005484 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005485 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5486 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5487 else
5488 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005489 return;
Mike Stump11289f42009-09-09 15:08:12 +00005490
John McCall393a78d2012-12-20 02:45:14 +00005491 case Type::Complex: {
5492 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005493 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005494 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005495 return;
5496 }
John McCall393a78d2012-12-20 02:45:14 +00005497
5498 case Type::Atomic: {
5499 const AtomicType *AT = T->castAs<AtomicType>();
5500 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005501 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005502 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005503 }
John McCall393a78d2012-12-20 02:45:14 +00005504
5505 // encoding for pointer or reference types.
5506 case Type::Pointer:
5507 case Type::LValueReference:
5508 case Type::RValueReference: {
5509 QualType PointeeTy;
5510 if (isa<PointerType>(CT)) {
5511 const PointerType *PT = T->castAs<PointerType>();
5512 if (PT->isObjCSelType()) {
5513 S += ':';
5514 return;
5515 }
5516 PointeeTy = PT->getPointeeType();
5517 } else {
5518 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5519 }
5520
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005521 bool isReadOnly = false;
5522 // For historical/compatibility reasons, the read-only qualifier of the
5523 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5524 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005525 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005526 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005527 if (OutermostType && T.isConstQualified()) {
5528 isReadOnly = true;
5529 S += 'r';
5530 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005531 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005532 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005533 while (P->getAs<PointerType>())
5534 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005535 if (P.isConstQualified()) {
5536 isReadOnly = true;
5537 S += 'r';
5538 }
5539 }
5540 if (isReadOnly) {
5541 // Another legacy compatibility encoding. Some ObjC qualifier and type
5542 // combinations need to be rearranged.
5543 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005544 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005545 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005546 }
Mike Stump11289f42009-09-09 15:08:12 +00005547
Anders Carlssond8499822007-10-29 05:01:08 +00005548 if (PointeeTy->isCharType()) {
5549 // char pointer types should be encoded as '*' unless it is a
5550 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005551 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005552 S += '*';
5553 return;
5554 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005555 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005556 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5557 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5558 S += '#';
5559 return;
5560 }
5561 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5562 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5563 S += '@';
5564 return;
5565 }
5566 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005567 }
Anders Carlssond8499822007-10-29 05:01:08 +00005568 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005569 getLegacyIntegralTypeEncoding(PointeeTy);
5570
Mike Stump11289f42009-09-09 15:08:12 +00005571 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005572 nullptr, false, false, false, false, false, false,
5573 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005574 return;
5575 }
John McCall393a78d2012-12-20 02:45:14 +00005576
5577 case Type::ConstantArray:
5578 case Type::IncompleteArray:
5579 case Type::VariableArray: {
5580 const ArrayType *AT = cast<ArrayType>(CT);
5581
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005582 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005583 // Incomplete arrays are encoded as a pointer to the array element.
5584 S += '^';
5585
Mike Stump11289f42009-09-09 15:08:12 +00005586 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005587 false, ExpandStructures, FD);
5588 } else {
5589 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005590
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005591 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5592 S += llvm::utostr(CAT->getSize().getZExtValue());
5593 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005594 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005595 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5596 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005597 S += '0';
5598 }
Mike Stump11289f42009-09-09 15:08:12 +00005599
5600 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005601 false, ExpandStructures, FD,
5602 false, false, false, false, false, false,
5603 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005604 S += ']';
5605 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005606 return;
5607 }
Mike Stump11289f42009-09-09 15:08:12 +00005608
John McCall393a78d2012-12-20 02:45:14 +00005609 case Type::FunctionNoProto:
5610 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005611 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005612 return;
Mike Stump11289f42009-09-09 15:08:12 +00005613
John McCall393a78d2012-12-20 02:45:14 +00005614 case Type::Record: {
5615 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005616 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005617 // Anonymous structures print as '?'
5618 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5619 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005620 if (ClassTemplateSpecializationDecl *Spec
5621 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5622 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005623 llvm::raw_string_ostream OS(S);
5624 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005625 TemplateArgs.data(),
5626 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005627 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005628 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005629 } else {
5630 S += '?';
5631 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005632 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005633 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005634 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005635 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005636 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005637 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005638 if (FD) {
5639 S += '"';
5640 S += Field->getNameAsString();
5641 S += '"';
5642 }
Mike Stump11289f42009-09-09 15:08:12 +00005643
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005644 // Special case bit-fields.
5645 if (Field->isBitField()) {
5646 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005647 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005648 } else {
5649 QualType qt = Field->getType();
5650 getLegacyIntegralTypeEncoding(qt);
5651 getObjCEncodingForTypeImpl(qt, S, false, true,
5652 FD, /*OutermostType*/false,
5653 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005654 /*StructField*/true,
5655 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005656 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005657 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005658 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005659 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005660 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005661 return;
5662 }
Mike Stump11289f42009-09-09 15:08:12 +00005663
John McCall393a78d2012-12-20 02:45:14 +00005664 case Type::BlockPointer: {
5665 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005666 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005667 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005668 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005669
5670 S += '<';
5671 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005672 getObjCEncodingForTypeImpl(
5673 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5674 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005675 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5676 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005677 // Block self
5678 S += "@?";
5679 // Block parameters
5680 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005681 for (const auto &I : FPT->param_types())
5682 getObjCEncodingForTypeImpl(
5683 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5684 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005685 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5686 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005687 }
5688 S += '>';
5689 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005690 return;
5691 }
Mike Stump11289f42009-09-09 15:08:12 +00005692
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005693 case Type::ObjCObject: {
5694 // hack to match legacy encoding of *id and *Class
5695 QualType Ty = getObjCObjectPointerType(CT);
5696 if (Ty->isObjCIdType()) {
5697 S += "{objc_object=}";
5698 return;
5699 }
5700 else if (Ty->isObjCClassType()) {
5701 S += "{objc_class=}";
5702 return;
5703 }
5704 }
5705
John McCall393a78d2012-12-20 02:45:14 +00005706 case Type::ObjCInterface: {
5707 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005708 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005709 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005710 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005711 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005712 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005713 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005714 DeepCollectObjCIvars(OI, true, Ivars);
5715 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005716 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005717 if (Field->isBitField())
5718 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005719 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005720 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5721 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005722 EncodePointerToObjCTypedef,
5723 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005724 }
5725 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005726 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005727 }
Mike Stump11289f42009-09-09 15:08:12 +00005728
John McCall393a78d2012-12-20 02:45:14 +00005729 case Type::ObjCObjectPointer: {
5730 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005731 if (OPT->isObjCIdType()) {
5732 S += '@';
5733 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005734 }
Mike Stump11289f42009-09-09 15:08:12 +00005735
Steve Narofff0c86112009-10-28 22:03:49 +00005736 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5737 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5738 // Since this is a binary compatibility issue, need to consult with runtime
5739 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005740 S += '#';
5741 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005742 }
Mike Stump11289f42009-09-09 15:08:12 +00005743
Chris Lattnere7cabb92009-07-13 00:10:46 +00005744 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005745 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005746 ExpandPointedToStructures,
5747 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005748 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005749 // Note that we do extended encoding of protocol qualifer list
5750 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005751 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005752 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005753 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005754 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005755 S += '>';
5756 }
5757 S += '"';
5758 }
5759 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005760 }
Mike Stump11289f42009-09-09 15:08:12 +00005761
Chris Lattnere7cabb92009-07-13 00:10:46 +00005762 QualType PointeeTy = OPT->getPointeeType();
5763 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005764 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5765 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005766 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005767 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005768 // {...};
5769 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005770 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005771 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005772 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5773 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5774 DeepCollectObjCIvars(OI, true, Ivars);
5775 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5776 if (cast<FieldDecl>(Ivars[i]) == FD) {
5777 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005778 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005779 S += '}';
5780 return;
5781 }
5782 }
5783 }
Mike Stump11289f42009-09-09 15:08:12 +00005784 getObjCEncodingForTypeImpl(PointeeTy, S,
5785 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005786 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005787 false, false, false, false, false,
5788 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005789 return;
5790 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005791
5792 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005793 if (OPT->getInterfaceDecl() &&
5794 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005795 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005796 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005797 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005798 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005799 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005800 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005801 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005802 S += '"';
5803 }
5804 return;
5805 }
Mike Stump11289f42009-09-09 15:08:12 +00005806
John McCalla9e6e8d2010-05-17 23:56:34 +00005807 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005808 // FIXME: we shoul do better than that. 'M' is available.
5809 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005810 // This matches gcc's encoding, even though technically it is insufficient.
5811 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005812 case Type::Vector:
5813 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005814 // Until we have a coherent encoding of these three types, issue warning.
5815 { if (NotEncodedT)
5816 *NotEncodedT = T;
5817 return;
5818 }
5819
5820 // We could see an undeduced auto type here during error recovery.
5821 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005822 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005823 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005824
Richard Smith27d807c2013-04-30 13:56:41 +00005825
John McCall393a78d2012-12-20 02:45:14 +00005826#define ABSTRACT_TYPE(KIND, BASE)
5827#define TYPE(KIND, BASE)
5828#define DEPENDENT_TYPE(KIND, BASE) \
5829 case Type::KIND:
5830#define NON_CANONICAL_TYPE(KIND, BASE) \
5831 case Type::KIND:
5832#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5833 case Type::KIND:
5834#include "clang/AST/TypeNodes.def"
5835 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005836 }
John McCall393a78d2012-12-20 02:45:14 +00005837 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005838}
5839
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005840void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5841 std::string &S,
5842 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005843 bool includeVBases,
5844 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005845 assert(RDecl && "Expected non-null RecordDecl");
5846 assert(!RDecl->isUnion() && "Should not be called for unions");
5847 if (!RDecl->getDefinition())
5848 return;
5849
5850 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5851 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5852 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5853
5854 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005855 for (const auto &BI : CXXRec->bases()) {
5856 if (!BI.isVirtual()) {
5857 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005858 if (base->isEmpty())
5859 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005860 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005861 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5862 std::make_pair(offs, base));
5863 }
5864 }
5865 }
5866
5867 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005868 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005869 uint64_t offs = layout.getFieldOffset(i);
5870 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005871 std::make_pair(offs, Field));
5872 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005873 }
5874
5875 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005876 for (const auto &BI : CXXRec->vbases()) {
5877 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005878 if (base->isEmpty())
5879 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005880 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005881 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5882 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005883 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5884 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005885 }
5886 }
5887
5888 CharUnits size;
5889 if (CXXRec) {
5890 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5891 } else {
5892 size = layout.getSize();
5893 }
5894
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005895#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005896 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005897#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005898 std::multimap<uint64_t, NamedDecl *>::iterator
5899 CurLayObj = FieldOrBaseOffsets.begin();
5900
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005901 if (CXXRec && CXXRec->isDynamicClass() &&
5902 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005903 if (FD) {
5904 S += "\"_vptr$";
5905 std::string recname = CXXRec->getNameAsString();
5906 if (recname.empty()) recname = "?";
5907 S += recname;
5908 S += '"';
5909 }
5910 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005911#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005912 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005913#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005914 }
5915
5916 if (!RDecl->hasFlexibleArrayMember()) {
5917 // Mark the end of the structure.
5918 uint64_t offs = toBits(size);
5919 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005920 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005921 }
5922
5923 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005924#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005925 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005926 if (CurOffs < CurLayObj->first) {
5927 uint64_t padding = CurLayObj->first - CurOffs;
5928 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5929 // packing/alignment of members is different that normal, in which case
5930 // the encoding will be out-of-sync with the real layout.
5931 // If the runtime switches to just consider the size of types without
5932 // taking into account alignment, we could make padding explicit in the
5933 // encoding (e.g. using arrays of chars). The encoding strings would be
5934 // longer then though.
5935 CurOffs += padding;
5936 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005937#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005938
5939 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005940 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005941 break; // reached end of structure.
5942
5943 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5944 // We expand the bases without their virtual bases since those are going
5945 // in the initial structure. Note that this differs from gcc which
5946 // expands virtual bases each time one is encountered in the hierarchy,
5947 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005948 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5949 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005950 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005951#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005952 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005953#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005954 } else {
5955 FieldDecl *field = cast<FieldDecl>(dcl);
5956 if (FD) {
5957 S += '"';
5958 S += field->getNameAsString();
5959 S += '"';
5960 }
5961
5962 if (field->isBitField()) {
5963 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005964#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005965 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005966#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005967 } else {
5968 QualType qt = field->getType();
5969 getLegacyIntegralTypeEncoding(qt);
5970 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5971 /*OutermostType*/false,
5972 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005973 /*StructField*/true,
5974 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005975#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005976 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005977#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005978 }
5979 }
5980 }
5981}
5982
Mike Stump11289f42009-09-09 15:08:12 +00005983void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005984 std::string& S) const {
5985 if (QT & Decl::OBJC_TQ_In)
5986 S += 'n';
5987 if (QT & Decl::OBJC_TQ_Inout)
5988 S += 'N';
5989 if (QT & Decl::OBJC_TQ_Out)
5990 S += 'o';
5991 if (QT & Decl::OBJC_TQ_Bycopy)
5992 S += 'O';
5993 if (QT & Decl::OBJC_TQ_Byref)
5994 S += 'R';
5995 if (QT & Decl::OBJC_TQ_Oneway)
5996 S += 'V';
5997}
5998
Douglas Gregor3ea72692011-08-12 05:46:01 +00005999TypedefDecl *ASTContext::getObjCIdDecl() const {
6000 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006001 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006002 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006003 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006004 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006005 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006006}
6007
Douglas Gregor52e02802011-08-12 06:17:30 +00006008TypedefDecl *ASTContext::getObjCSelDecl() const {
6009 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006010 QualType T = getPointerType(ObjCBuiltinSelTy);
6011 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006012 }
6013 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006014}
6015
Douglas Gregor0a586182011-08-12 05:59:41 +00006016TypedefDecl *ASTContext::getObjCClassDecl() const {
6017 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006018 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006019 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006020 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006021 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006022 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006023}
6024
Douglas Gregord53ae832012-01-17 18:09:05 +00006025ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6026 if (!ObjCProtocolClassDecl) {
6027 ObjCProtocolClassDecl
6028 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6029 SourceLocation(),
6030 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006031 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006032 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006033 SourceLocation(), true);
6034 }
6035
6036 return ObjCProtocolClassDecl;
6037}
6038
Meador Inge5d3fb222012-06-16 03:34:49 +00006039//===----------------------------------------------------------------------===//
6040// __builtin_va_list Construction Functions
6041//===----------------------------------------------------------------------===//
6042
Charles Davisc7d5c942015-09-17 20:55:33 +00006043static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6044 StringRef Name) {
6045 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006046 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006047 return Context->buildImplicitTypedef(T, Name);
6048}
6049
6050static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6051 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6052}
6053
6054static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6055 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006056}
6057
6058static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6059 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006060 QualType T = Context->getPointerType(Context->VoidTy);
6061 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006062}
6063
Tim Northover9bb857a2013-01-31 12:13:10 +00006064static TypedefDecl *
6065CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006066 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006067 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006068 if (Context->getLangOpts().CPlusPlus) {
6069 // namespace std { struct __va_list {
6070 NamespaceDecl *NS;
6071 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6072 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006073 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006074 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006075 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006076 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006077 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006078 }
6079
6080 VaListTagDecl->startDefinition();
6081
6082 const size_t NumFields = 5;
6083 QualType FieldTypes[NumFields];
6084 const char *FieldNames[NumFields];
6085
6086 // void *__stack;
6087 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6088 FieldNames[0] = "__stack";
6089
6090 // void *__gr_top;
6091 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6092 FieldNames[1] = "__gr_top";
6093
6094 // void *__vr_top;
6095 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6096 FieldNames[2] = "__vr_top";
6097
6098 // int __gr_offs;
6099 FieldTypes[3] = Context->IntTy;
6100 FieldNames[3] = "__gr_offs";
6101
6102 // int __vr_offs;
6103 FieldTypes[4] = Context->IntTy;
6104 FieldNames[4] = "__vr_offs";
6105
6106 // Create fields
6107 for (unsigned i = 0; i < NumFields; ++i) {
6108 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6109 VaListTagDecl,
6110 SourceLocation(),
6111 SourceLocation(),
6112 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006113 FieldTypes[i], /*TInfo=*/nullptr,
6114 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006115 /*Mutable=*/false,
6116 ICIS_NoInit);
6117 Field->setAccess(AS_public);
6118 VaListTagDecl->addDecl(Field);
6119 }
6120 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006121 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006122 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006123
6124 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006125 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006126}
6127
Meador Inge5d3fb222012-06-16 03:34:49 +00006128static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6129 // typedef struct __va_list_tag {
6130 RecordDecl *VaListTagDecl;
6131
Alp Toker2dea15b2013-12-17 01:22:38 +00006132 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006133 VaListTagDecl->startDefinition();
6134
6135 const size_t NumFields = 5;
6136 QualType FieldTypes[NumFields];
6137 const char *FieldNames[NumFields];
6138
6139 // unsigned char gpr;
6140 FieldTypes[0] = Context->UnsignedCharTy;
6141 FieldNames[0] = "gpr";
6142
6143 // unsigned char fpr;
6144 FieldTypes[1] = Context->UnsignedCharTy;
6145 FieldNames[1] = "fpr";
6146
6147 // unsigned short reserved;
6148 FieldTypes[2] = Context->UnsignedShortTy;
6149 FieldNames[2] = "reserved";
6150
6151 // void* overflow_arg_area;
6152 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6153 FieldNames[3] = "overflow_arg_area";
6154
6155 // void* reg_save_area;
6156 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6157 FieldNames[4] = "reg_save_area";
6158
6159 // Create fields
6160 for (unsigned i = 0; i < NumFields; ++i) {
6161 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6162 SourceLocation(),
6163 SourceLocation(),
6164 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006165 FieldTypes[i], /*TInfo=*/nullptr,
6166 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006167 /*Mutable=*/false,
6168 ICIS_NoInit);
6169 Field->setAccess(AS_public);
6170 VaListTagDecl->addDecl(Field);
6171 }
6172 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006173 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006174 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6175
6176 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006177 TypedefDecl *VaListTagTypedefDecl =
6178 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6179
Meador Inge5d3fb222012-06-16 03:34:49 +00006180 QualType VaListTagTypedefType =
6181 Context->getTypedefType(VaListTagTypedefDecl);
6182
6183 // typedef __va_list_tag __builtin_va_list[1];
6184 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6185 QualType VaListTagArrayType
6186 = Context->getConstantArrayType(VaListTagTypedefType,
6187 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006188 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006189}
6190
6191static TypedefDecl *
6192CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006193 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006194 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006195 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006196 VaListTagDecl->startDefinition();
6197
6198 const size_t NumFields = 4;
6199 QualType FieldTypes[NumFields];
6200 const char *FieldNames[NumFields];
6201
6202 // unsigned gp_offset;
6203 FieldTypes[0] = Context->UnsignedIntTy;
6204 FieldNames[0] = "gp_offset";
6205
6206 // unsigned fp_offset;
6207 FieldTypes[1] = Context->UnsignedIntTy;
6208 FieldNames[1] = "fp_offset";
6209
6210 // void* overflow_arg_area;
6211 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6212 FieldNames[2] = "overflow_arg_area";
6213
6214 // void* reg_save_area;
6215 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6216 FieldNames[3] = "reg_save_area";
6217
6218 // Create fields
6219 for (unsigned i = 0; i < NumFields; ++i) {
6220 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6221 VaListTagDecl,
6222 SourceLocation(),
6223 SourceLocation(),
6224 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006225 FieldTypes[i], /*TInfo=*/nullptr,
6226 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006227 /*Mutable=*/false,
6228 ICIS_NoInit);
6229 Field->setAccess(AS_public);
6230 VaListTagDecl->addDecl(Field);
6231 }
6232 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006233 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006234 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6235
Richard Smith9b88a4c2015-07-27 05:40:23 +00006236 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006237
Richard Smith9b88a4c2015-07-27 05:40:23 +00006238 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006239 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006240 QualType VaListTagArrayType =
6241 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006242 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006243}
6244
6245static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6246 // typedef int __builtin_va_list[4];
6247 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6248 QualType IntArrayType
6249 = Context->getConstantArrayType(Context->IntTy,
6250 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006251 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006252}
6253
Logan Chien57086ce2012-10-10 06:56:20 +00006254static TypedefDecl *
6255CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006256 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006257 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006258 if (Context->getLangOpts().CPlusPlus) {
6259 // namespace std { struct __va_list {
6260 NamespaceDecl *NS;
6261 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6262 Context->getTranslationUnitDecl(),
6263 /*Inline*/false, SourceLocation(),
6264 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006265 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006266 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006267 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006268 }
6269
6270 VaListDecl->startDefinition();
6271
6272 // void * __ap;
6273 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6274 VaListDecl,
6275 SourceLocation(),
6276 SourceLocation(),
6277 &Context->Idents.get("__ap"),
6278 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006279 /*TInfo=*/nullptr,
6280 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006281 /*Mutable=*/false,
6282 ICIS_NoInit);
6283 Field->setAccess(AS_public);
6284 VaListDecl->addDecl(Field);
6285
6286 // };
6287 VaListDecl->completeDefinition();
6288
6289 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006290 QualType T = Context->getRecordType(VaListDecl);
6291 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006292}
6293
Ulrich Weigand47445072013-05-06 16:26:41 +00006294static TypedefDecl *
6295CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006296 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006297 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006298 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006299 VaListTagDecl->startDefinition();
6300
6301 const size_t NumFields = 4;
6302 QualType FieldTypes[NumFields];
6303 const char *FieldNames[NumFields];
6304
6305 // long __gpr;
6306 FieldTypes[0] = Context->LongTy;
6307 FieldNames[0] = "__gpr";
6308
6309 // long __fpr;
6310 FieldTypes[1] = Context->LongTy;
6311 FieldNames[1] = "__fpr";
6312
6313 // void *__overflow_arg_area;
6314 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6315 FieldNames[2] = "__overflow_arg_area";
6316
6317 // void *__reg_save_area;
6318 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6319 FieldNames[3] = "__reg_save_area";
6320
6321 // Create fields
6322 for (unsigned i = 0; i < NumFields; ++i) {
6323 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6324 VaListTagDecl,
6325 SourceLocation(),
6326 SourceLocation(),
6327 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006328 FieldTypes[i], /*TInfo=*/nullptr,
6329 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006330 /*Mutable=*/false,
6331 ICIS_NoInit);
6332 Field->setAccess(AS_public);
6333 VaListTagDecl->addDecl(Field);
6334 }
6335 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006336 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006337 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006338
Richard Smith9b88a4c2015-07-27 05:40:23 +00006339 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006340
6341 // typedef __va_list_tag __builtin_va_list[1];
6342 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006343 QualType VaListTagArrayType =
6344 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006345
Alp Toker56b5cc92013-12-15 10:36:26 +00006346 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006347}
6348
Meador Inge5d3fb222012-06-16 03:34:49 +00006349static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6350 TargetInfo::BuiltinVaListKind Kind) {
6351 switch (Kind) {
6352 case TargetInfo::CharPtrBuiltinVaList:
6353 return CreateCharPtrBuiltinVaListDecl(Context);
6354 case TargetInfo::VoidPtrBuiltinVaList:
6355 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006356 case TargetInfo::AArch64ABIBuiltinVaList:
6357 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006358 case TargetInfo::PowerABIBuiltinVaList:
6359 return CreatePowerABIBuiltinVaListDecl(Context);
6360 case TargetInfo::X86_64ABIBuiltinVaList:
6361 return CreateX86_64ABIBuiltinVaListDecl(Context);
6362 case TargetInfo::PNaClABIBuiltinVaList:
6363 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006364 case TargetInfo::AAPCSABIBuiltinVaList:
6365 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006366 case TargetInfo::SystemZBuiltinVaList:
6367 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006368 }
6369
6370 llvm_unreachable("Unhandled __builtin_va_list type kind");
6371}
6372
6373TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006374 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006375 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006376 assert(BuiltinVaListDecl->isImplicit());
6377 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006378
6379 return BuiltinVaListDecl;
6380}
6381
Richard Smith9b88a4c2015-07-27 05:40:23 +00006382Decl *ASTContext::getVaListTagDecl() const {
6383 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006384 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006385 if (!VaListTagDecl)
6386 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006387
Richard Smith9b88a4c2015-07-27 05:40:23 +00006388 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006389}
6390
Charles Davisc7d5c942015-09-17 20:55:33 +00006391TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6392 if (!BuiltinMSVaListDecl)
6393 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6394
6395 return BuiltinMSVaListDecl;
6396}
6397
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006398void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006399 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006400 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006401
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006402 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006403}
6404
John McCalld28ae272009-12-02 08:04:21 +00006405/// \brief Retrieve the template name that corresponds to a non-empty
6406/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006407TemplateName
6408ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6409 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006410 unsigned size = End - Begin;
6411 assert(size > 1 && "set is not overloaded!");
6412
6413 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6414 size * sizeof(FunctionTemplateDecl*));
6415 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6416
6417 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006418 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006419 NamedDecl *D = *I;
6420 assert(isa<FunctionTemplateDecl>(D) ||
6421 (isa<UsingShadowDecl>(D) &&
6422 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6423 *Storage++ = D;
6424 }
6425
6426 return TemplateName(OT);
6427}
6428
Douglas Gregordc572a32009-03-30 22:58:21 +00006429/// \brief Retrieve the template name that represents a qualified
6430/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006431TemplateName
6432ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6433 bool TemplateKeyword,
6434 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006435 assert(NNS && "Missing nested-name-specifier in qualified template name");
6436
Douglas Gregorc42075a2010-02-04 18:10:26 +00006437 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006438 llvm::FoldingSetNodeID ID;
6439 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6440
Craig Topper36250ad2014-05-12 05:36:57 +00006441 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006442 QualifiedTemplateName *QTN =
6443 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6444 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006445 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6446 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006447 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6448 }
6449
6450 return TemplateName(QTN);
6451}
6452
6453/// \brief Retrieve the template name that represents a dependent
6454/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006455TemplateName
6456ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6457 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006458 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006459 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006460
6461 llvm::FoldingSetNodeID ID;
6462 DependentTemplateName::Profile(ID, NNS, Name);
6463
Craig Topper36250ad2014-05-12 05:36:57 +00006464 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006465 DependentTemplateName *QTN =
6466 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6467
6468 if (QTN)
6469 return TemplateName(QTN);
6470
6471 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6472 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006473 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6474 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006475 } else {
6476 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006477 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6478 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006479 DependentTemplateName *CheckQTN =
6480 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6481 assert(!CheckQTN && "Dependent type name canonicalization broken");
6482 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006483 }
6484
6485 DependentTemplateNames.InsertNode(QTN, InsertPos);
6486 return TemplateName(QTN);
6487}
6488
Douglas Gregor71395fa2009-11-04 00:56:37 +00006489/// \brief Retrieve the template name that represents a dependent
6490/// template name such as \c MetaFun::template operator+.
6491TemplateName
6492ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006493 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006494 assert((!NNS || NNS->isDependent()) &&
6495 "Nested name specifier must be dependent");
6496
6497 llvm::FoldingSetNodeID ID;
6498 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006499
6500 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006501 DependentTemplateName *QTN
6502 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006503
6504 if (QTN)
6505 return TemplateName(QTN);
6506
6507 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6508 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006509 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6510 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006511 } else {
6512 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006513 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6514 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006515
6516 DependentTemplateName *CheckQTN
6517 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6518 assert(!CheckQTN && "Dependent template name canonicalization broken");
6519 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006520 }
6521
6522 DependentTemplateNames.InsertNode(QTN, InsertPos);
6523 return TemplateName(QTN);
6524}
6525
Douglas Gregor5590be02011-01-15 06:45:20 +00006526TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006527ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6528 TemplateName replacement) const {
6529 llvm::FoldingSetNodeID ID;
6530 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006531
6532 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006533 SubstTemplateTemplateParmStorage *subst
6534 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6535
6536 if (!subst) {
6537 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6538 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6539 }
6540
6541 return TemplateName(subst);
6542}
6543
6544TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006545ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6546 const TemplateArgument &ArgPack) const {
6547 ASTContext &Self = const_cast<ASTContext &>(*this);
6548 llvm::FoldingSetNodeID ID;
6549 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006550
6551 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006552 SubstTemplateTemplateParmPackStorage *Subst
6553 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6554
6555 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006556 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006557 ArgPack.pack_size(),
6558 ArgPack.pack_begin());
6559 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6560 }
6561
6562 return TemplateName(Subst);
6563}
6564
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006565/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006566/// TargetInfo, produce the corresponding type. The unsigned @p Type
6567/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006568CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006569 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006570 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006571 case TargetInfo::SignedChar: return SignedCharTy;
6572 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006573 case TargetInfo::SignedShort: return ShortTy;
6574 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6575 case TargetInfo::SignedInt: return IntTy;
6576 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6577 case TargetInfo::SignedLong: return LongTy;
6578 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6579 case TargetInfo::SignedLongLong: return LongLongTy;
6580 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6581 }
6582
David Blaikie83d382b2011-09-23 05:06:16 +00006583 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006584}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006585
6586//===----------------------------------------------------------------------===//
6587// Type Predicates.
6588//===----------------------------------------------------------------------===//
6589
Fariborz Jahanian96207692009-02-18 21:49:28 +00006590/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6591/// garbage collection attribute.
6592///
John McCall553d45a2011-01-12 00:34:59 +00006593Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006594 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006595 return Qualifiers::GCNone;
6596
David Blaikiebbafb8a2012-03-11 07:00:24 +00006597 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006598 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6599
6600 // Default behaviour under objective-C's gc is for ObjC pointers
6601 // (or pointers to them) be treated as though they were declared
6602 // as __strong.
6603 if (GCAttrs == Qualifiers::GCNone) {
6604 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6605 return Qualifiers::Strong;
6606 else if (Ty->isPointerType())
6607 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6608 } else {
6609 // It's not valid to set GC attributes on anything that isn't a
6610 // pointer.
6611#ifndef NDEBUG
6612 QualType CT = Ty->getCanonicalTypeInternal();
6613 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6614 CT = AT->getElementType();
6615 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6616#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006617 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006618 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006619}
6620
Chris Lattner49af6a42008-04-07 06:51:04 +00006621//===----------------------------------------------------------------------===//
6622// Type Compatibility Testing
6623//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006624
Mike Stump11289f42009-09-09 15:08:12 +00006625/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006626/// compatible.
6627static bool areCompatVectorTypes(const VectorType *LHS,
6628 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006629 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006630 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006631 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006632}
6633
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006634bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6635 QualType SecondVec) {
6636 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6637 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6638
6639 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6640 return true;
6641
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006642 // Treat Neon vector types and most AltiVec vector types as if they are the
6643 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006644 const VectorType *First = FirstVec->getAs<VectorType>();
6645 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006646 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006647 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006648 First->getVectorKind() != VectorType::AltiVecPixel &&
6649 First->getVectorKind() != VectorType::AltiVecBool &&
6650 Second->getVectorKind() != VectorType::AltiVecPixel &&
6651 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006652 return true;
6653
6654 return false;
6655}
6656
Steve Naroff8e6aee52009-07-23 01:01:38 +00006657//===----------------------------------------------------------------------===//
6658// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6659//===----------------------------------------------------------------------===//
6660
6661/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6662/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006663bool
6664ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6665 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006666 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006667 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006668 for (auto *PI : rProto->protocols())
6669 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006670 return true;
6671 return false;
6672}
6673
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006674/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6675/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006676bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6677 QualType rhs) {
6678 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6679 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6680 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6681
Aaron Ballman83731462014-03-17 16:14:00 +00006682 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006683 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006684 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006685 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6686 match = true;
6687 break;
6688 }
6689 }
6690 if (!match)
6691 return false;
6692 }
6693 return true;
6694}
6695
Steve Naroff8e6aee52009-07-23 01:01:38 +00006696/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6697/// ObjCQualifiedIDType.
6698bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6699 bool compare) {
6700 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006701 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006702 lhs->isObjCIdType() || lhs->isObjCClassType())
6703 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006704 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006705 rhs->isObjCIdType() || rhs->isObjCClassType())
6706 return true;
6707
6708 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006709 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006710
Steve Naroff8e6aee52009-07-23 01:01:38 +00006711 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006712
Steve Naroff8e6aee52009-07-23 01:01:38 +00006713 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006714 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006715 // make sure we check the class hierarchy.
6716 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006717 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006718 // when comparing an id<P> on lhs with a static type on rhs,
6719 // see if static class implements all of id's protocols, directly or
6720 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006721 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006722 return false;
6723 }
6724 }
6725 // If there are no qualifiers and no interface, we have an 'id'.
6726 return true;
6727 }
Mike Stump11289f42009-09-09 15:08:12 +00006728 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006729 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006730 bool match = false;
6731
6732 // when comparing an id<P> on lhs with a static type on rhs,
6733 // see if static class implements all of id's protocols, directly or
6734 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006735 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006736 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6737 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6738 match = true;
6739 break;
6740 }
6741 }
Mike Stump11289f42009-09-09 15:08:12 +00006742 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006743 // make sure we check the class hierarchy.
6744 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006745 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006746 // when comparing an id<P> on lhs with a static type on rhs,
6747 // see if static class implements all of id's protocols, directly or
6748 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006749 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006750 match = true;
6751 break;
6752 }
6753 }
6754 }
6755 if (!match)
6756 return false;
6757 }
Mike Stump11289f42009-09-09 15:08:12 +00006758
Steve Naroff8e6aee52009-07-23 01:01:38 +00006759 return true;
6760 }
Mike Stump11289f42009-09-09 15:08:12 +00006761
Steve Naroff8e6aee52009-07-23 01:01:38 +00006762 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6763 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6764
Mike Stump11289f42009-09-09 15:08:12 +00006765 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006766 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006767 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006768 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006769 bool match = false;
6770
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006771 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006772 // see if static class implements all of id's protocols, directly or
6773 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006774 // First, lhs protocols in the qualifier list must be found, direct
6775 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006776 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006777 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6778 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6779 match = true;
6780 break;
6781 }
6782 }
6783 if (!match)
6784 return false;
6785 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006786
6787 // Static class's protocols, or its super class or category protocols
6788 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6789 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6790 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6791 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6792 // This is rather dubious but matches gcc's behavior. If lhs has
6793 // no type qualifier and its class has no static protocol(s)
6794 // assume that it is mismatch.
6795 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6796 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006797 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006798 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006799 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006800 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6801 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6802 match = true;
6803 break;
6804 }
6805 }
6806 if (!match)
6807 return false;
6808 }
6809 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006810 return true;
6811 }
6812 return false;
6813}
6814
Eli Friedman47f77112008-08-22 00:56:42 +00006815/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006816/// compatible for assignment from RHS to LHS. This handles validation of any
6817/// protocol qualifiers on the LHS or RHS.
6818///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006819bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6820 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006821 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6822 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6823
Steve Naroff1329fa02009-07-15 18:40:39 +00006824 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006825 if (LHS->isObjCUnqualifiedIdOrClass() ||
6826 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006827 return true;
6828
Douglas Gregorab209d82015-07-07 03:58:42 +00006829 // Function object that propagates a successful result or handles
6830 // __kindof types.
6831 auto finish = [&](bool succeeded) -> bool {
6832 if (succeeded)
6833 return true;
6834
6835 if (!RHS->isKindOfType())
6836 return false;
6837
6838 // Strip off __kindof and protocol qualifiers, then check whether
6839 // we can assign the other way.
6840 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6841 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6842 };
6843
6844 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6845 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6846 QualType(RHSOPT,0),
6847 false));
6848 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006849
Douglas Gregorab209d82015-07-07 03:58:42 +00006850 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6851 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6852 QualType(RHSOPT,0)));
6853 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006854
John McCall8b07ec22010-05-15 11:32:37 +00006855 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006856 if (LHS->getInterface() && RHS->getInterface()) {
6857 return finish(canAssignObjCInterfaces(LHS, RHS));
6858 }
Mike Stump11289f42009-09-09 15:08:12 +00006859
Steve Naroff8e6aee52009-07-23 01:01:38 +00006860 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006861}
6862
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006863/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006864/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006865/// arguments in block literals. When passed as arguments, passing 'A*' where
6866/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6867/// not OK. For the return type, the opposite is not OK.
6868bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6869 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006870 const ObjCObjectPointerType *RHSOPT,
6871 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006872
6873 // Function object that propagates a successful result or handles
6874 // __kindof types.
6875 auto finish = [&](bool succeeded) -> bool {
6876 if (succeeded)
6877 return true;
6878
6879 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6880 if (!Expected->isKindOfType())
6881 return false;
6882
6883 // Strip off __kindof and protocol qualifiers, then check whether
6884 // we can assign the other way.
6885 return canAssignObjCInterfacesInBlockPointer(
6886 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6887 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6888 BlockReturnType);
6889 };
6890
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006891 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006892 return true;
6893
6894 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006895 return finish(RHSOPT->isObjCBuiltinType() ||
6896 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006897 }
6898
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006899 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006900 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6901 QualType(RHSOPT,0),
6902 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006903
6904 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6905 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6906 if (LHS && RHS) { // We have 2 user-defined types.
6907 if (LHS != RHS) {
6908 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006909 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006910 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006911 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006912 }
6913 else
6914 return true;
6915 }
6916 return false;
6917}
6918
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006919/// Comparison routine for Objective-C protocols to be used with
6920/// llvm::array_pod_sort.
6921static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6922 ObjCProtocolDecl * const *rhs) {
6923 return (*lhs)->getName().compare((*rhs)->getName());
6924
6925}
6926
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006927/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006928/// of protocols inherited from two distinct objective-c pointer objects with
6929/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006930/// It is used to build composite qualifier list of the composite type of
6931/// the conditional expression involving two objective-c pointer objects.
6932static
6933void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006934 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006935 const ObjCObjectPointerType *LHSOPT,
6936 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006937 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006938
John McCall8b07ec22010-05-15 11:32:37 +00006939 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6940 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6941 assert(LHS->getInterface() && "LHS must have an interface base");
6942 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006943
6944 // Add all of the protocols for the LHS.
6945 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6946
6947 // Start with the protocol qualifiers.
6948 for (auto proto : LHS->quals()) {
6949 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006950 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006951
6952 // Also add the protocols associated with the LHS interface.
6953 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6954
6955 // Add all of the protocls for the RHS.
6956 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6957
6958 // Start with the protocol qualifiers.
6959 for (auto proto : RHS->quals()) {
6960 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006961 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006962
6963 // Also add the protocols associated with the RHS interface.
6964 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6965
6966 // Compute the intersection of the collected protocol sets.
6967 for (auto proto : LHSProtocolSet) {
6968 if (RHSProtocolSet.count(proto))
6969 IntersectionSet.push_back(proto);
6970 }
6971
6972 // Compute the set of protocols that is implied by either the common type or
6973 // the protocols within the intersection.
6974 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6975 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6976
6977 // Remove any implied protocols from the list of inherited protocols.
6978 if (!ImpliedProtocols.empty()) {
6979 IntersectionSet.erase(
6980 std::remove_if(IntersectionSet.begin(),
6981 IntersectionSet.end(),
6982 [&](ObjCProtocolDecl *proto) -> bool {
6983 return ImpliedProtocols.count(proto) > 0;
6984 }),
6985 IntersectionSet.end());
6986 }
6987
6988 // Sort the remaining protocols by name.
6989 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
6990 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006991}
6992
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006993/// Determine whether the first type is a subtype of the second.
6994static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
6995 QualType rhs) {
6996 // Common case: two object pointers.
6997 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
6998 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6999 if (lhsOPT && rhsOPT)
7000 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7001
7002 // Two block pointers.
7003 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7004 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7005 if (lhsBlock && rhsBlock)
7006 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7007
7008 // If either is an unqualified 'id' and the other is a block, it's
7009 // acceptable.
7010 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7011 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7012 return true;
7013
7014 return false;
7015}
7016
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007017// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007018static bool sameObjCTypeArgs(ASTContext &ctx,
7019 const ObjCInterfaceDecl *iface,
7020 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007021 ArrayRef<QualType> rhsArgs,
7022 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007023 if (lhsArgs.size() != rhsArgs.size())
7024 return false;
7025
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007026 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007027 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007028 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7029 continue;
7030
7031 switch (typeParams->begin()[i]->getVariance()) {
7032 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007033 if (!stripKindOf ||
7034 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7035 rhsArgs[i].stripObjCKindOfType(ctx))) {
7036 return false;
7037 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007038 break;
7039
7040 case ObjCTypeParamVariance::Covariant:
7041 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7042 return false;
7043 break;
7044
7045 case ObjCTypeParamVariance::Contravariant:
7046 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7047 return false;
7048 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007049 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007050 }
7051
7052 return true;
7053}
7054
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007055QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007056 const ObjCObjectPointerType *Lptr,
7057 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007058 const ObjCObjectType *LHS = Lptr->getObjectType();
7059 const ObjCObjectType *RHS = Rptr->getObjectType();
7060 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7061 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007062
7063 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007064 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007065
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007066 // Follow the left-hand side up the class hierarchy until we either hit a
7067 // root or find the RHS. Record the ancestors in case we don't find it.
7068 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7069 LHSAncestors;
7070 while (true) {
7071 // Record this ancestor. We'll need this if the common type isn't in the
7072 // path from the LHS to the root.
7073 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007074
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007075 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7076 // Get the type arguments.
7077 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7078 bool anyChanges = false;
7079 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7080 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007081 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7082 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007083 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007084 return QualType();
7085 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7086 // If only one has type arguments, the result will not have type
7087 // arguments.
7088 LHSTypeArgs = { };
7089 anyChanges = true;
7090 }
7091
7092 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007093 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007094 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7095 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007096 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007097 anyChanges = true;
7098
7099 // If anything in the LHS will have changed, build a new result type.
7100 if (anyChanges) {
7101 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007102 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7103 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007104 return getObjCObjectPointerType(Result);
7105 }
7106
7107 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007108 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007109
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007110 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007111 QualType LHSSuperType = LHS->getSuperClassType();
7112 if (LHSSuperType.isNull())
7113 break;
7114
7115 LHS = LHSSuperType->castAs<ObjCObjectType>();
7116 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007117
7118 // We didn't find anything by following the LHS to its root; now check
7119 // the RHS against the cached set of ancestors.
7120 while (true) {
7121 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7122 if (KnownLHS != LHSAncestors.end()) {
7123 LHS = KnownLHS->second;
7124
7125 // Get the type arguments.
7126 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7127 bool anyChanges = false;
7128 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7129 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007130 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7131 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007132 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007133 return QualType();
7134 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7135 // If only one has type arguments, the result will not have type
7136 // arguments.
7137 RHSTypeArgs = { };
7138 anyChanges = true;
7139 }
7140
7141 // Compute the intersection of protocols.
7142 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7143 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7144 Protocols);
7145 if (!Protocols.empty())
7146 anyChanges = true;
7147
7148 if (anyChanges) {
7149 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007150 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7151 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007152 return getObjCObjectPointerType(Result);
7153 }
7154
7155 return getObjCObjectPointerType(QualType(RHS, 0));
7156 }
7157
7158 // Find the superclass of the RHS.
7159 QualType RHSSuperType = RHS->getSuperClassType();
7160 if (RHSSuperType.isNull())
7161 break;
7162
7163 RHS = RHSSuperType->castAs<ObjCObjectType>();
7164 }
7165
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007166 return QualType();
7167}
7168
John McCall8b07ec22010-05-15 11:32:37 +00007169bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7170 const ObjCObjectType *RHS) {
7171 assert(LHS->getInterface() && "LHS is not an interface type");
7172 assert(RHS->getInterface() && "RHS is not an interface type");
7173
Chris Lattner49af6a42008-04-07 06:51:04 +00007174 // Verify that the base decls are compatible: the RHS must be a subclass of
7175 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007176 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7177 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7178 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007179 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007180
Douglas Gregore83b9562015-07-07 03:57:53 +00007181 // If the LHS has protocol qualifiers, determine whether all of them are
7182 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7183 // LHS).
7184 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007185 // OK if conversion of LHS to SuperClass results in narrowing of types
7186 // ; i.e., SuperClass may implement at least one of the protocols
7187 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7188 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7189 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7190 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7191 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7192 // qualifiers.
7193 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007194 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007195 // If there is no protocols associated with RHS, it is not a match.
7196 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007197 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007198
7199 for (const auto *LHSProto : LHS->quals()) {
7200 bool SuperImplementsProtocol = false;
7201 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7202 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7203 SuperImplementsProtocol = true;
7204 break;
7205 }
7206 if (!SuperImplementsProtocol)
7207 return false;
7208 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007209 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007210
7211 // If the LHS is specialized, we may need to check type arguments.
7212 if (LHS->isSpecialized()) {
7213 // Follow the superclass chain until we've matched the LHS class in the
7214 // hierarchy. This substitutes type arguments through.
7215 const ObjCObjectType *RHSSuper = RHS;
7216 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7217 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7218
7219 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007220 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007221 !sameObjCTypeArgs(*this, LHS->getInterface(),
7222 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007223 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007224 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007225 }
7226 }
7227
7228 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007229}
7230
Steve Naroffb7605152009-02-12 17:52:19 +00007231bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7232 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007233 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7234 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007235
Steve Naroff7cae42b2009-07-10 23:34:53 +00007236 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007237 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007238
7239 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7240 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007241}
7242
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007243bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7244 return canAssignObjCInterfaces(
7245 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7246 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7247}
7248
Mike Stump11289f42009-09-09 15:08:12 +00007249/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007250/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007251/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007252/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007253bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7254 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007255 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007256 return hasSameType(LHS, RHS);
7257
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007258 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007259}
7260
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007261bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007262 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007263}
7264
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007265bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7266 return !mergeTypes(LHS, RHS, true).isNull();
7267}
7268
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007269/// mergeTransparentUnionType - if T is a transparent union type and a member
7270/// of T is compatible with SubType, return the merged type, else return
7271/// QualType()
7272QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7273 bool OfBlockPointer,
7274 bool Unqualified) {
7275 if (const RecordType *UT = T->getAsUnionType()) {
7276 RecordDecl *UD = UT->getDecl();
7277 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007278 for (const auto *I : UD->fields()) {
7279 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007280 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7281 if (!MT.isNull())
7282 return MT;
7283 }
7284 }
7285 }
7286
7287 return QualType();
7288}
7289
Alp Toker9cacbab2014-01-20 20:26:09 +00007290/// mergeFunctionParameterTypes - merge two types which appear as function
7291/// parameter types
7292QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7293 bool OfBlockPointer,
7294 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007295 // GNU extension: two types are compatible if they appear as a function
7296 // argument, one of the types is a transparent union type and the other
7297 // type is compatible with a union member
7298 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7299 Unqualified);
7300 if (!lmerge.isNull())
7301 return lmerge;
7302
7303 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7304 Unqualified);
7305 if (!rmerge.isNull())
7306 return rmerge;
7307
7308 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7309}
7310
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007311QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007312 bool OfBlockPointer,
7313 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007314 const FunctionType *lbase = lhs->getAs<FunctionType>();
7315 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007316 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7317 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007318 bool allLTypes = true;
7319 bool allRTypes = true;
7320
7321 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007322 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007323 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007324 QualType RHS = rbase->getReturnType();
7325 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007326 bool UnqualifiedResult = Unqualified;
7327 if (!UnqualifiedResult)
7328 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007329 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007330 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007331 else
Alp Toker314cc812014-01-25 16:55:45 +00007332 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007333 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007334 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007335
7336 if (Unqualified)
7337 retType = retType.getUnqualifiedType();
7338
Alp Toker314cc812014-01-25 16:55:45 +00007339 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7340 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007341 if (Unqualified) {
7342 LRetType = LRetType.getUnqualifiedType();
7343 RRetType = RRetType.getUnqualifiedType();
7344 }
7345
7346 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007347 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007348 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007349 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007350
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007351 // FIXME: double check this
7352 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7353 // rbase->getRegParmAttr() != 0 &&
7354 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007355 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7356 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007357
Douglas Gregor8c940862010-01-18 17:14:39 +00007358 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007359 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007360 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007361
John McCall8c6b56f2010-12-15 01:06:38 +00007362 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007363 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7364 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007365 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7366 return QualType();
7367
John McCall31168b02011-06-15 23:02:42 +00007368 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7369 return QualType();
7370
John McCall8c6b56f2010-12-15 01:06:38 +00007371 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7372 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007373
Rafael Espindola8778c282012-11-29 16:09:03 +00007374 if (lbaseInfo.getNoReturn() != NoReturn)
7375 allLTypes = false;
7376 if (rbaseInfo.getNoReturn() != NoReturn)
7377 allRTypes = false;
7378
John McCall31168b02011-06-15 23:02:42 +00007379 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007380
Eli Friedman47f77112008-08-22 00:56:42 +00007381 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007382 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7383 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007384 // Compatible functions must have the same number of parameters
7385 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007386 return QualType();
7387
7388 // Variadic and non-variadic functions aren't compatible
7389 if (lproto->isVariadic() != rproto->isVariadic())
7390 return QualType();
7391
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007392 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7393 return QualType();
7394
Fariborz Jahanian97676972011-09-28 21:52:05 +00007395 if (LangOpts.ObjCAutoRefCount &&
7396 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7397 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007398
7399 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007400 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007401 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7402 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7403 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7404 QualType paramType = mergeFunctionParameterTypes(
7405 lParamType, rParamType, OfBlockPointer, Unqualified);
7406 if (paramType.isNull())
7407 return QualType();
7408
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007409 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007410 paramType = paramType.getUnqualifiedType();
7411
7412 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007413 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007414 lParamType = lParamType.getUnqualifiedType();
7415 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007416 }
Alp Toker601b22c2014-01-21 23:35:24 +00007417
7418 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007419 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007420 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007421 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007422 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007423
Eli Friedman47f77112008-08-22 00:56:42 +00007424 if (allLTypes) return lhs;
7425 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007426
7427 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7428 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007429 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007430 }
7431
7432 if (lproto) allRTypes = false;
7433 if (rproto) allLTypes = false;
7434
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007435 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007436 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007437 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007438 if (proto->isVariadic()) return QualType();
7439 // Check that the types are compatible with the types that
7440 // would result from default argument promotions (C99 6.7.5.3p15).
7441 // The only types actually affected are promotable integer
7442 // types and floats, which would be passed as a different
7443 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007444 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7445 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007446
Eli Friedman448ce402012-08-30 00:44:15 +00007447 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007448 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007449 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7450 paramTy = Enum->getDecl()->getIntegerType();
7451 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007452 return QualType();
7453 }
Alp Toker601b22c2014-01-21 23:35:24 +00007454
7455 if (paramTy->isPromotableIntegerType() ||
7456 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007457 return QualType();
7458 }
7459
7460 if (allLTypes) return lhs;
7461 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007462
7463 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7464 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007465 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007466 }
7467
7468 if (allLTypes) return lhs;
7469 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007470 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007471}
7472
John McCall433c2e62013-03-21 00:10:07 +00007473/// Given that we have an enum type and a non-enum type, try to merge them.
7474static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7475 QualType other, bool isBlockReturnType) {
7476 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7477 // a signed integer type, or an unsigned integer type.
7478 // Compatibility is based on the underlying type, not the promotion
7479 // type.
7480 QualType underlyingType = ET->getDecl()->getIntegerType();
7481 if (underlyingType.isNull()) return QualType();
7482 if (Context.hasSameType(underlyingType, other))
7483 return other;
7484
7485 // In block return types, we're more permissive and accept any
7486 // integral type of the same size.
7487 if (isBlockReturnType && other->isIntegerType() &&
7488 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7489 return other;
7490
7491 return QualType();
7492}
7493
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007494QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007495 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007496 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007497 // C++ [expr]: If an expression initially has the type "reference to T", the
7498 // type is adjusted to "T" prior to any further analysis, the expression
7499 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007500 // expression is an lvalue unless the reference is an rvalue reference and
7501 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007502 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7503 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007504
7505 if (Unqualified) {
7506 LHS = LHS.getUnqualifiedType();
7507 RHS = RHS.getUnqualifiedType();
7508 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007509
Eli Friedman47f77112008-08-22 00:56:42 +00007510 QualType LHSCan = getCanonicalType(LHS),
7511 RHSCan = getCanonicalType(RHS);
7512
7513 // If two types are identical, they are compatible.
7514 if (LHSCan == RHSCan)
7515 return LHS;
7516
John McCall8ccfcb52009-09-24 19:53:00 +00007517 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007518 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7519 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007520 if (LQuals != RQuals) {
7521 // If any of these qualifiers are different, we have a type
7522 // mismatch.
7523 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007524 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7525 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007526 return QualType();
7527
7528 // Exactly one GC qualifier difference is allowed: __strong is
7529 // okay if the other type has no GC qualifier but is an Objective
7530 // C object pointer (i.e. implicitly strong by default). We fix
7531 // this by pretending that the unqualified type was actually
7532 // qualified __strong.
7533 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7534 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7535 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7536
7537 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7538 return QualType();
7539
7540 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7541 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7542 }
7543 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7544 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7545 }
Eli Friedman47f77112008-08-22 00:56:42 +00007546 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007547 }
7548
7549 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007550
Eli Friedmandcca6332009-06-01 01:22:52 +00007551 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7552 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007553
Chris Lattnerfd652912008-01-14 05:45:46 +00007554 // We want to consider the two function types to be the same for these
7555 // comparisons, just force one to the other.
7556 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7557 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007558
7559 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007560 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7561 LHSClass = Type::ConstantArray;
7562 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7563 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007564
John McCall8b07ec22010-05-15 11:32:37 +00007565 // ObjCInterfaces are just specialized ObjCObjects.
7566 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7567 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7568
Nate Begemance4d7fc2008-04-18 23:10:10 +00007569 // Canonicalize ExtVector -> Vector.
7570 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7571 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007572
Chris Lattner95554662008-04-07 05:43:21 +00007573 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007574 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007575 // Note that we only have special rules for turning block enum
7576 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007577 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007578 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007579 }
John McCall9dd450b2009-09-21 23:43:11 +00007580 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007581 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007582 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007583 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007584 if (OfBlockPointer && !BlockReturnType) {
7585 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7586 return LHS;
7587 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7588 return RHS;
7589 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007590
Eli Friedman47f77112008-08-22 00:56:42 +00007591 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007592 }
Eli Friedman47f77112008-08-22 00:56:42 +00007593
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007594 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007595 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007596#define TYPE(Class, Base)
7597#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007598#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007599#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7600#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7601#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007602 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007603
Richard Smith27d807c2013-04-30 13:56:41 +00007604 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007605 case Type::LValueReference:
7606 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007607 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007608 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007609
John McCall8b07ec22010-05-15 11:32:37 +00007610 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007611 case Type::IncompleteArray:
7612 case Type::VariableArray:
7613 case Type::FunctionProto:
7614 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007615 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007616
Chris Lattnerfd652912008-01-14 05:45:46 +00007617 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007618 {
7619 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007620 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7621 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007622 if (Unqualified) {
7623 LHSPointee = LHSPointee.getUnqualifiedType();
7624 RHSPointee = RHSPointee.getUnqualifiedType();
7625 }
7626 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7627 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007628 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007629 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007630 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007631 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007632 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007633 return getPointerType(ResultType);
7634 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007635 case Type::BlockPointer:
7636 {
7637 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007638 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7639 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007640 if (Unqualified) {
7641 LHSPointee = LHSPointee.getUnqualifiedType();
7642 RHSPointee = RHSPointee.getUnqualifiedType();
7643 }
7644 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7645 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007646 if (ResultType.isNull()) return QualType();
7647 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7648 return LHS;
7649 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7650 return RHS;
7651 return getBlockPointerType(ResultType);
7652 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007653 case Type::Atomic:
7654 {
7655 // Merge two pointer types, while trying to preserve typedef info
7656 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7657 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7658 if (Unqualified) {
7659 LHSValue = LHSValue.getUnqualifiedType();
7660 RHSValue = RHSValue.getUnqualifiedType();
7661 }
7662 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7663 Unqualified);
7664 if (ResultType.isNull()) return QualType();
7665 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7666 return LHS;
7667 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7668 return RHS;
7669 return getAtomicType(ResultType);
7670 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007671 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007672 {
7673 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7674 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7675 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7676 return QualType();
7677
7678 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7679 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007680 if (Unqualified) {
7681 LHSElem = LHSElem.getUnqualifiedType();
7682 RHSElem = RHSElem.getUnqualifiedType();
7683 }
7684
7685 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007686 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007687 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7688 return LHS;
7689 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7690 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007691 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7692 ArrayType::ArraySizeModifier(), 0);
7693 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7694 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007695 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7696 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007697 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7698 return LHS;
7699 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7700 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007701 if (LVAT) {
7702 // FIXME: This isn't correct! But tricky to implement because
7703 // the array's size has to be the size of LHS, but the type
7704 // has to be different.
7705 return LHS;
7706 }
7707 if (RVAT) {
7708 // FIXME: This isn't correct! But tricky to implement because
7709 // the array's size has to be the size of RHS, but the type
7710 // has to be different.
7711 return RHS;
7712 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007713 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7714 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007715 return getIncompleteArrayType(ResultType,
7716 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007717 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007718 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007719 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007720 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007721 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007722 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007723 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007724 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007725 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007726 case Type::Complex:
7727 // Distinct complex types are incompatible.
7728 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007729 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007730 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007731 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7732 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007733 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007734 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007735 case Type::ObjCObject: {
7736 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007737 // FIXME: This should be type compatibility, e.g. whether
7738 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007739 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7740 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7741 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007742 return LHS;
7743
Eli Friedman47f77112008-08-22 00:56:42 +00007744 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007745 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007746 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007747 if (OfBlockPointer) {
7748 if (canAssignObjCInterfacesInBlockPointer(
7749 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007750 RHS->getAs<ObjCObjectPointerType>(),
7751 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007752 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007753 return QualType();
7754 }
John McCall9dd450b2009-09-21 23:43:11 +00007755 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7756 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007757 return LHS;
7758
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007759 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007760 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007761 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007762
David Blaikie8a40f702012-01-17 06:56:22 +00007763 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007764}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007765
Fariborz Jahanian97676972011-09-28 21:52:05 +00007766bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7767 const FunctionProtoType *FromFunctionType,
7768 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007769 if (FromFunctionType->hasAnyConsumedParams() !=
7770 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007771 return false;
7772 FunctionProtoType::ExtProtoInfo FromEPI =
7773 FromFunctionType->getExtProtoInfo();
7774 FunctionProtoType::ExtProtoInfo ToEPI =
7775 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007776 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007777 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7778 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007779 return false;
7780 }
7781 return true;
7782}
7783
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007784/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7785/// 'RHS' attributes and returns the merged version; including for function
7786/// return types.
7787QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7788 QualType LHSCan = getCanonicalType(LHS),
7789 RHSCan = getCanonicalType(RHS);
7790 // If two types are identical, they are compatible.
7791 if (LHSCan == RHSCan)
7792 return LHS;
7793 if (RHSCan->isFunctionType()) {
7794 if (!LHSCan->isFunctionType())
7795 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007796 QualType OldReturnType =
7797 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007798 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007799 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007800 QualType ResReturnType =
7801 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7802 if (ResReturnType.isNull())
7803 return QualType();
7804 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7805 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7806 // In either case, use OldReturnType to build the new function type.
7807 const FunctionType *F = LHS->getAs<FunctionType>();
7808 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007809 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7810 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007811 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007812 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007813 return ResultType;
7814 }
7815 }
7816 return QualType();
7817 }
7818
7819 // If the qualifiers are different, the types can still be merged.
7820 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7821 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7822 if (LQuals != RQuals) {
7823 // If any of these qualifiers are different, we have a type mismatch.
7824 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7825 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7826 return QualType();
7827
7828 // Exactly one GC qualifier difference is allowed: __strong is
7829 // okay if the other type has no GC qualifier but is an Objective
7830 // C object pointer (i.e. implicitly strong by default). We fix
7831 // this by pretending that the unqualified type was actually
7832 // qualified __strong.
7833 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7834 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7835 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7836
7837 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7838 return QualType();
7839
7840 if (GC_L == Qualifiers::Strong)
7841 return LHS;
7842 if (GC_R == Qualifiers::Strong)
7843 return RHS;
7844 return QualType();
7845 }
7846
7847 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7848 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7849 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7850 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7851 if (ResQT == LHSBaseQT)
7852 return LHS;
7853 if (ResQT == RHSBaseQT)
7854 return RHS;
7855 }
7856 return QualType();
7857}
7858
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007859//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007860// Integer Predicates
7861//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007862
Jay Foad39c79802011-01-12 09:06:06 +00007863unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007864 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007865 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007866 if (T->isBooleanType())
7867 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007868 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007869 return (unsigned)getTypeSize(T);
7870}
7871
Abramo Bagnara13640492012-09-09 10:21:24 +00007872QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007873 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007874
7875 // Turn <4 x signed int> -> <4 x unsigned int>
7876 if (const VectorType *VTy = T->getAs<VectorType>())
7877 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007878 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007879
7880 // For enums, we return the unsigned version of the base type.
7881 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007882 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007883
7884 const BuiltinType *BTy = T->getAs<BuiltinType>();
7885 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007886 switch (BTy->getKind()) {
7887 case BuiltinType::Char_S:
7888 case BuiltinType::SChar:
7889 return UnsignedCharTy;
7890 case BuiltinType::Short:
7891 return UnsignedShortTy;
7892 case BuiltinType::Int:
7893 return UnsignedIntTy;
7894 case BuiltinType::Long:
7895 return UnsignedLongTy;
7896 case BuiltinType::LongLong:
7897 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007898 case BuiltinType::Int128:
7899 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007900 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007901 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007902 }
7903}
7904
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007905ASTMutationListener::~ASTMutationListener() { }
7906
Richard Smith1fa5d642013-05-11 05:45:24 +00007907void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7908 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007909
7910//===----------------------------------------------------------------------===//
7911// Builtin Type Computation
7912//===----------------------------------------------------------------------===//
7913
7914/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007915/// pointer over the consumed characters. This returns the resultant type. If
7916/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7917/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7918/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007919///
7920/// RequiresICE is filled in on return to indicate whether the value is required
7921/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007922static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007923 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007924 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007925 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007926 // Modifiers.
7927 int HowLong = 0;
7928 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007929 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007930
Chris Lattnerdc226c22010-10-01 22:42:38 +00007931 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007932 bool Done = false;
7933 while (!Done) {
7934 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007935 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007936 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007937 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007938 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007939 case 'S':
7940 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7941 assert(!Signed && "Can't use 'S' modifier multiple times!");
7942 Signed = true;
7943 break;
7944 case 'U':
7945 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007946 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007947 Unsigned = true;
7948 break;
7949 case 'L':
7950 assert(HowLong <= 2 && "Can't have LLLL modifier");
7951 ++HowLong;
7952 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007953 case 'W':
7954 // This modifier represents int64 type.
7955 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7956 switch (Context.getTargetInfo().getInt64Type()) {
7957 default:
7958 llvm_unreachable("Unexpected integer type");
7959 case TargetInfo::SignedLong:
7960 HowLong = 1;
7961 break;
7962 case TargetInfo::SignedLongLong:
7963 HowLong = 2;
7964 break;
7965 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007966 }
7967 }
7968
7969 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007970
Chris Lattnerecd79c62009-06-14 00:45:47 +00007971 // Read the base type.
7972 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007973 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007974 case 'v':
7975 assert(HowLong == 0 && !Signed && !Unsigned &&
7976 "Bad modifiers used with 'v'!");
7977 Type = Context.VoidTy;
7978 break;
Jack Carter24bef982013-08-15 15:16:57 +00007979 case 'h':
7980 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007981 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007982 Type = Context.HalfTy;
7983 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007984 case 'f':
7985 assert(HowLong == 0 && !Signed && !Unsigned &&
7986 "Bad modifiers used with 'f'!");
7987 Type = Context.FloatTy;
7988 break;
7989 case 'd':
7990 assert(HowLong < 2 && !Signed && !Unsigned &&
7991 "Bad modifiers used with 'd'!");
7992 if (HowLong)
7993 Type = Context.LongDoubleTy;
7994 else
7995 Type = Context.DoubleTy;
7996 break;
7997 case 's':
7998 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7999 if (Unsigned)
8000 Type = Context.UnsignedShortTy;
8001 else
8002 Type = Context.ShortTy;
8003 break;
8004 case 'i':
8005 if (HowLong == 3)
8006 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8007 else if (HowLong == 2)
8008 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8009 else if (HowLong == 1)
8010 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8011 else
8012 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8013 break;
8014 case 'c':
8015 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8016 if (Signed)
8017 Type = Context.SignedCharTy;
8018 else if (Unsigned)
8019 Type = Context.UnsignedCharTy;
8020 else
8021 Type = Context.CharTy;
8022 break;
8023 case 'b': // boolean
8024 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8025 Type = Context.BoolTy;
8026 break;
8027 case 'z': // size_t.
8028 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8029 Type = Context.getSizeType();
8030 break;
8031 case 'F':
8032 Type = Context.getCFConstantStringType();
8033 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008034 case 'G':
8035 Type = Context.getObjCIdType();
8036 break;
8037 case 'H':
8038 Type = Context.getObjCSelType();
8039 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008040 case 'M':
8041 Type = Context.getObjCSuperType();
8042 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008043 case 'a':
8044 Type = Context.getBuiltinVaListType();
8045 assert(!Type.isNull() && "builtin va list type not initialized!");
8046 break;
8047 case 'A':
8048 // This is a "reference" to a va_list; however, what exactly
8049 // this means depends on how va_list is defined. There are two
8050 // different kinds of va_list: ones passed by value, and ones
8051 // passed by reference. An example of a by-value va_list is
8052 // x86, where va_list is a char*. An example of by-ref va_list
8053 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8054 // we want this argument to be a char*&; for x86-64, we want
8055 // it to be a __va_list_tag*.
8056 Type = Context.getBuiltinVaListType();
8057 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008058 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008059 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008060 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008061 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008062 break;
8063 case 'V': {
8064 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008065 unsigned NumElements = strtoul(Str, &End, 10);
8066 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008067 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008068
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008069 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8070 RequiresICE, false);
8071 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008072
8073 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008074 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008075 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008076 break;
8077 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008078 case 'E': {
8079 char *End;
8080
8081 unsigned NumElements = strtoul(Str, &End, 10);
8082 assert(End != Str && "Missing vector size");
8083
8084 Str = End;
8085
8086 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8087 false);
8088 Type = Context.getExtVectorType(ElementType, NumElements);
8089 break;
8090 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008091 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008092 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8093 false);
8094 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008095 Type = Context.getComplexType(ElementType);
8096 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008097 }
8098 case 'Y' : {
8099 Type = Context.getPointerDiffType();
8100 break;
8101 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008102 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008103 Type = Context.getFILEType();
8104 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008105 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008106 return QualType();
8107 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008108 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008109 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008110 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008111 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008112 else
8113 Type = Context.getjmp_bufType();
8114
Mike Stump2adb4da2009-07-28 23:47:15 +00008115 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008116 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008117 return QualType();
8118 }
8119 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008120 case 'K':
8121 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8122 Type = Context.getucontext_tType();
8123
8124 if (Type.isNull()) {
8125 Error = ASTContext::GE_Missing_ucontext;
8126 return QualType();
8127 }
8128 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008129 case 'p':
8130 Type = Context.getProcessIDType();
8131 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008132 }
Mike Stump11289f42009-09-09 15:08:12 +00008133
Chris Lattnerdc226c22010-10-01 22:42:38 +00008134 // If there are modifiers and if we're allowed to parse them, go for it.
8135 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008136 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008137 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008138 default: Done = true; --Str; break;
8139 case '*':
8140 case '&': {
8141 // Both pointers and references can have their pointee types
8142 // qualified with an address space.
8143 char *End;
8144 unsigned AddrSpace = strtoul(Str, &End, 10);
8145 if (End != Str && AddrSpace != 0) {
8146 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8147 Str = End;
8148 }
8149 if (c == '*')
8150 Type = Context.getPointerType(Type);
8151 else
8152 Type = Context.getLValueReferenceType(Type);
8153 break;
8154 }
8155 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8156 case 'C':
8157 Type = Type.withConst();
8158 break;
8159 case 'D':
8160 Type = Context.getVolatileType(Type);
8161 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008162 case 'R':
8163 Type = Type.withRestrict();
8164 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008165 }
8166 }
Chris Lattner84733392010-10-01 07:13:18 +00008167
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008168 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008169 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008170
Chris Lattnerecd79c62009-06-14 00:45:47 +00008171 return Type;
8172}
8173
8174/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008175QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008176 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008177 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008178 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008179
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008180 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008181
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008182 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008183 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008184 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8185 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008186 if (Error != GE_None)
8187 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008188
8189 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8190
Chris Lattnerecd79c62009-06-14 00:45:47 +00008191 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008192 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008193 if (Error != GE_None)
8194 return QualType();
8195
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008196 // If this argument is required to be an IntegerConstantExpression and the
8197 // caller cares, fill in the bitmask we return.
8198 if (RequiresICE && IntegerConstantArgs)
8199 *IntegerConstantArgs |= 1 << ArgTypes.size();
8200
Chris Lattnerecd79c62009-06-14 00:45:47 +00008201 // Do array -> pointer decay. The builtin should use the decayed type.
8202 if (Ty->isArrayType())
8203 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008204
Chris Lattnerecd79c62009-06-14 00:45:47 +00008205 ArgTypes.push_back(Ty);
8206 }
8207
David Majnemerba3e5ec2015-03-13 18:26:17 +00008208 if (Id == Builtin::BI__GetExceptionInfo)
8209 return QualType();
8210
Chris Lattnerecd79c62009-06-14 00:45:47 +00008211 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8212 "'.' should only occur at end of builtin type list!");
8213
Reid Kleckner78af0702013-08-27 23:08:25 +00008214 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008215 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8216
8217 bool Variadic = (TypeStr[0] == '.');
8218
8219 // We really shouldn't be making a no-proto type here, especially in C++.
8220 if (ArgTypes.empty() && Variadic)
8221 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008222
John McCalldb40c7f2010-12-14 08:05:40 +00008223 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008224 EPI.ExtInfo = EI;
8225 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008226
Jordan Rose5c382722013-03-08 21:51:21 +00008227 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008228}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008229
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008230static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8231 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008232 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008233 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008234
Rafael Espindola3ae00052013-05-13 00:12:11 +00008235 GVALinkage External = GVA_StrongExternal;
8236 switch (FD->getTemplateSpecializationKind()) {
8237 case TSK_Undeclared:
8238 case TSK_ExplicitSpecialization:
8239 External = GVA_StrongExternal;
8240 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008241
Rafael Espindola3ae00052013-05-13 00:12:11 +00008242 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008243 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008244
David Majnemerc3d07332014-05-15 06:25:57 +00008245 // C++11 [temp.explicit]p10:
8246 // [ Note: The intent is that an inline function that is the subject of
8247 // an explicit instantiation declaration will still be implicitly
8248 // instantiated when used so that the body can be considered for
8249 // inlining, but that no out-of-line copy of the inline function would be
8250 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008251 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008252 return GVA_AvailableExternally;
8253
Rafael Espindola3ae00052013-05-13 00:12:11 +00008254 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008255 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008256 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008257 }
8258
8259 if (!FD->isInlined())
8260 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008261
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008262 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8263 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008264 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008265 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8266
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008267 // GNU or C99 inline semantics. Determine whether this symbol should be
8268 // externally visible.
8269 if (FD->isInlineDefinitionExternallyVisible())
8270 return External;
8271
8272 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008273 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008274 }
8275
David Majnemer54e3ba52014-04-02 23:17:29 +00008276 // Functions specified with extern and inline in -fms-compatibility mode
8277 // forcibly get emitted. While the body of the function cannot be later
8278 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008279 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008280 return GVA_StrongODR;
8281
David Majnemer27d69db2014-04-28 22:17:59 +00008282 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008283}
8284
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008285static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
8286 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8287 // dllexport/dllimport on inline functions.
8288 if (D->hasAttr<DLLImportAttr>()) {
8289 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8290 return GVA_AvailableExternally;
8291 } else if (D->hasAttr<DLLExportAttr>()) {
8292 if (L == GVA_DiscardableODR)
8293 return GVA_StrongODR;
8294 }
8295 return L;
8296}
8297
8298GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8299 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
8300 FD);
8301}
8302
8303static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8304 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008305 if (!VD->isExternallyVisible())
8306 return GVA_Internal;
8307
David Majnemer27d69db2014-04-28 22:17:59 +00008308 if (VD->isStaticLocal()) {
8309 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8310 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8311 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8312 LexicalContext = LexicalContext->getLexicalParent();
8313
Richard Smith9e2341d2015-03-23 03:25:59 +00008314 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008315 // enclosing function.
8316 if (LexicalContext)
8317 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008318 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008319
8320 // GVA_StrongODR function linkage is stronger than what we need,
8321 // downgrade to GVA_DiscardableODR.
8322 // This allows us to discard the variable if we never end up needing it.
8323 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8324 : StaticLocalLinkage;
8325 }
8326
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008327 // MSVC treats in-class initialized static data members as definitions.
8328 // By giving them non-strong linkage, out-of-line definitions won't
8329 // cause link errors.
8330 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8331 return GVA_DiscardableODR;
8332
Richard Smith8809a0c2013-09-27 20:14:12 +00008333 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008334 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008335 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008336
David Majnemer6d1780c2015-07-17 23:36:49 +00008337 case TSK_ExplicitSpecialization:
8338 return Context.getLangOpts().MSVCCompat && VD->isStaticDataMember()
8339 ? GVA_StrongODR
8340 : GVA_StrongExternal;
8341
Rafael Espindola3ae00052013-05-13 00:12:11 +00008342 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008343 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008344
David Majnemer27d69db2014-04-28 22:17:59 +00008345 case TSK_ExplicitInstantiationDeclaration:
8346 return GVA_AvailableExternally;
8347
Rafael Espindola3ae00052013-05-13 00:12:11 +00008348 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008349 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008350 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008351
8352 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008353}
8354
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008355GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8356 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8357 VD);
8358}
8359
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008360bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008361 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8362 if (!VD->isFileVarDecl())
8363 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008364 // Global named register variables (GNU extension) are never emitted.
8365 if (VD->getStorageClass() == SC_Register)
8366 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008367 if (VD->getDescribedVarTemplate() ||
8368 isa<VarTemplatePartialSpecializationDecl>(VD))
8369 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008370 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8371 // We never need to emit an uninstantiated function template.
8372 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8373 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008374 } else if (isa<OMPThreadPrivateDecl>(D))
8375 return true;
8376 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008377 return false;
8378
8379 // If this is a member of a class template, we do not need to emit it.
8380 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008381 return false;
8382
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008383 // Weak references don't produce any output by themselves.
8384 if (D->hasAttr<WeakRefAttr>())
8385 return false;
8386
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008387 // Aliases and used decls are required.
8388 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8389 return true;
8390
8391 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8392 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008393 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008394 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008395
8396 // Constructors and destructors are required.
8397 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8398 return true;
8399
John McCall6bd2a892013-01-25 22:31:03 +00008400 // The key function for a class is required. This rule only comes
8401 // into play when inline functions can be key functions, though.
8402 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8403 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8404 const CXXRecordDecl *RD = MD->getParent();
8405 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8406 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8407 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8408 return true;
8409 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008410 }
8411 }
8412
8413 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8414
8415 // static, static inline, always_inline, and extern inline functions can
8416 // always be deferred. Normal inline functions can be deferred in C99/C++.
8417 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008418 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8419 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008420 return false;
8421 return true;
8422 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008423
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008424 const VarDecl *VD = cast<VarDecl>(D);
8425 assert(VD->isFileVarDecl() && "Expected file scoped var");
8426
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008427 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8428 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008429 return false;
8430
Richard Smitha0e5e542012-11-12 21:38:00 +00008431 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008432 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008433 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8434 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008435 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008436
Richard Smitha0e5e542012-11-12 21:38:00 +00008437 // Variables that have destruction with side-effects are required.
8438 if (VD->getType().isDestructedType())
8439 return true;
8440
8441 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008442 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8443 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008444 return true;
8445
8446 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008447}
Charles Davis53c59df2010-08-16 03:33:14 +00008448
Reid Kleckner78af0702013-08-27 23:08:25 +00008449CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8450 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008451 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008452 if (IsCXXMethod)
8453 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008454
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008455 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8456
8457 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008458}
8459
Jay Foad39c79802011-01-12 09:06:06 +00008460bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008461 // Pass through to the C++ ABI object
8462 return ABI->isNearlyEmpty(RD);
8463}
8464
Reid Kleckner96f8f932014-02-05 17:27:08 +00008465VTableContextBase *ASTContext::getVTableContext() {
8466 if (!VTContext.get()) {
8467 if (Target->getCXXABI().isMicrosoft())
8468 VTContext.reset(new MicrosoftVTableContext(*this));
8469 else
8470 VTContext.reset(new ItaniumVTableContext(*this));
8471 }
8472 return VTContext.get();
8473}
8474
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008475MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008476 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008477 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008478 case TargetCXXABI::GenericItanium:
8479 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008480 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008481 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008482 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008483 case TargetCXXABI::WebAssembly:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008484 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008485 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008486 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008487 }
David Blaikie83d382b2011-09-23 05:06:16 +00008488 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008489}
8490
Charles Davis53c59df2010-08-16 03:33:14 +00008491CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008492
8493size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008494 return ASTRecordLayouts.getMemorySize() +
8495 llvm::capacity_in_bytes(ObjCLayouts) +
8496 llvm::capacity_in_bytes(KeyFunctions) +
8497 llvm::capacity_in_bytes(ObjCImpls) +
8498 llvm::capacity_in_bytes(BlockVarCopyInits) +
8499 llvm::capacity_in_bytes(DeclAttrs) +
8500 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8501 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8502 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8503 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8504 llvm::capacity_in_bytes(OverriddenMethods) +
8505 llvm::capacity_in_bytes(Types) +
8506 llvm::capacity_in_bytes(VariableArrayTypes) +
8507 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008508}
Ted Kremenek540017e2011-10-06 05:00:56 +00008509
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008510/// getIntTypeForBitwidth -
8511/// sets integer QualTy according to specified details:
8512/// bitwidth, signed/unsigned.
8513/// Returns empty type if there is no appropriate target types.
8514QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8515 unsigned Signed) const {
8516 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8517 CanQualType QualTy = getFromTargetType(Ty);
8518 if (!QualTy && DestWidth == 128)
8519 return Signed ? Int128Ty : UnsignedInt128Ty;
8520 return QualTy;
8521}
8522
8523/// getRealTypeForBitwidth -
8524/// sets floating point QualTy according to specified bitwidth.
8525/// Returns empty type if there is no appropriate target types.
8526QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8527 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8528 switch (Ty) {
8529 case TargetInfo::Float:
8530 return FloatTy;
8531 case TargetInfo::Double:
8532 return DoubleTy;
8533 case TargetInfo::LongDouble:
8534 return LongDoubleTy;
8535 case TargetInfo::NoFloat:
8536 return QualType();
8537 }
8538
8539 llvm_unreachable("Unhandled TargetInfo::RealType value");
8540}
8541
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008542void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8543 if (Number > 1)
8544 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008545}
8546
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008547unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8548 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8549 MangleNumbers.find(ND);
8550 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008551}
8552
David Majnemer2206bf52014-03-05 08:57:59 +00008553void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8554 if (Number > 1)
8555 StaticLocalNumbers[VD] = Number;
8556}
8557
8558unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8559 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8560 StaticLocalNumbers.find(VD);
8561 return I != StaticLocalNumbers.end() ? I->second : 1;
8562}
8563
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008564MangleNumberingContext &
8565ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008566 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8567 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8568 if (!MCtx)
8569 MCtx = createMangleNumberingContext();
8570 return *MCtx;
8571}
8572
8573MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8574 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008575}
8576
David Majnemere7a818f2015-03-06 18:53:55 +00008577const CXXConstructorDecl *
8578ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8579 return ABI->getCopyConstructorForExceptionObject(
8580 cast<CXXRecordDecl>(RD->getFirstDecl()));
8581}
8582
8583void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8584 CXXConstructorDecl *CD) {
8585 return ABI->addCopyConstructorForExceptionObject(
8586 cast<CXXRecordDecl>(RD->getFirstDecl()),
8587 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8588}
8589
David Majnemerdfa6d202015-03-11 18:36:39 +00008590void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8591 unsigned ParmIdx, Expr *DAE) {
8592 ABI->addDefaultArgExprForConstructor(
8593 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8594}
8595
8596Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8597 unsigned ParmIdx) {
8598 return ABI->getDefaultArgExprForConstructor(
8599 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8600}
8601
David Majnemer00350522015-08-31 18:48:39 +00008602void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8603 TypedefNameDecl *DD) {
8604 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8605}
8606
8607TypedefNameDecl *
8608ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8609 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8610}
8611
8612void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8613 DeclaratorDecl *DD) {
8614 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8615}
8616
8617DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8618 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8619}
8620
Ted Kremenek540017e2011-10-06 05:00:56 +00008621void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8622 ParamIndices[D] = index;
8623}
8624
8625unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8626 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8627 assert(I != ParamIndices.end() &&
8628 "ParmIndices lacks entry set by ParmVarDecl");
8629 return I->second;
8630}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008631
Richard Smithe6c01442013-06-05 00:46:14 +00008632APValue *
8633ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8634 bool MayCreate) {
8635 assert(E && E->getStorageDuration() == SD_Static &&
8636 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008637 if (MayCreate) {
8638 APValue *&MTVI = MaterializedTemporaryValues[E];
8639 if (!MTVI)
8640 MTVI = new (*this) APValue;
8641 return MTVI;
8642 }
Richard Smithe6c01442013-06-05 00:46:14 +00008643
David Majnemer2dcef9e2015-08-13 23:50:15 +00008644 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008645}
8646
Fariborz Jahanian615de762013-05-28 17:37:39 +00008647bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8648 const llvm::Triple &T = getTargetInfo().getTriple();
8649 if (!T.isOSDarwin())
8650 return false;
8651
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008652 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8653 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8654 return false;
8655
Fariborz Jahanian615de762013-05-28 17:37:39 +00008656 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8657 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8658 uint64_t Size = sizeChars.getQuantity();
8659 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8660 unsigned Align = alignChars.getQuantity();
8661 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8662 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8663}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008664
8665namespace {
8666
8667 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8668 /// parents as defined by the \c RecursiveASTVisitor.
8669 ///
8670 /// Note that the relationship described here is purely in terms of AST
8671 /// traversal - there are other relationships (for example declaration context)
8672 /// in the AST that are better modeled by special matchers.
8673 ///
8674 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8675 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8676
8677 public:
8678 /// \brief Builds and returns the translation unit's parent map.
8679 ///
8680 /// The caller takes ownership of the returned \c ParentMap.
8681 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8682 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8683 Visitor.TraverseDecl(&TU);
8684 return Visitor.Parents;
8685 }
8686
8687 private:
8688 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8689
8690 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8691 }
8692
8693 bool shouldVisitTemplateInstantiations() const {
8694 return true;
8695 }
8696 bool shouldVisitImplicitCode() const {
8697 return true;
8698 }
8699 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8700 // are not triggered during data recursion.
8701 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8702 return false;
8703 }
8704
8705 template <typename T>
8706 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008707 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008708 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008709 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008710 // FIXME: Currently we add the same parent multiple times, but only
8711 // when no memoization data is available for the type.
8712 // For example when we visit all subexpressions of template
8713 // instantiations; this is suboptimal, but benign: the only way to
8714 // visit those is with hasAncestor / hasParent, and those do not create
8715 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008716 // The plan is to enable DynTypedNode to be storable in a map or hash
8717 // map. The main problem there is to implement hash functions /
8718 // comparison operators for all types that DynTypedNode supports that
8719 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008720 auto &NodeOrVector = (*Parents)[Node];
8721 if (NodeOrVector.isNull()) {
8722 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008723 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008724 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8725 auto *Node =
8726 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8727 auto *Vector = new ASTContext::ParentVector(1, *Node);
8728 NodeOrVector = Vector;
8729 delete Node;
8730 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008731 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008732
8733 auto *Vector =
8734 NodeOrVector.template get<ASTContext::ParentVector *>();
8735 // Skip duplicates for types that have memoization data.
8736 // We must check that the type has memoization data before calling
8737 // std::find() because DynTypedNode::operator== can't compare all
8738 // types.
8739 bool Found = ParentStack.back().getMemoizationData() &&
8740 std::find(Vector->begin(), Vector->end(),
8741 ParentStack.back()) != Vector->end();
8742 if (!Found)
8743 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008744 }
8745 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008746 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8747 bool Result = (this ->* traverse) (Node);
8748 ParentStack.pop_back();
8749 return Result;
8750 }
8751
8752 bool TraverseDecl(Decl *DeclNode) {
8753 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8754 }
8755
8756 bool TraverseStmt(Stmt *StmtNode) {
8757 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8758 }
8759
8760 ASTContext::ParentMap *Parents;
8761 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8762
8763 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8764 };
8765
8766} // end namespace
8767
Benjamin Kramer07935292014-10-04 17:01:26 +00008768ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008769ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8770 assert(Node.getMemoizationData() &&
8771 "Invariant broken: only nodes that support memoization may be "
8772 "used in the parent map.");
8773 if (!AllParents) {
8774 // We always need to run over the whole translation unit, as
8775 // hasAncestor can escape any subtree.
8776 AllParents.reset(
8777 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8778 }
8779 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8780 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008781 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008782 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008783 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8784 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008785 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008786 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008787}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008788
8789bool
8790ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8791 const ObjCMethodDecl *MethodImpl) {
8792 // No point trying to match an unavailable/deprecated mothod.
8793 if (MethodDecl->hasAttr<UnavailableAttr>()
8794 || MethodDecl->hasAttr<DeprecatedAttr>())
8795 return false;
8796 if (MethodDecl->getObjCDeclQualifier() !=
8797 MethodImpl->getObjCDeclQualifier())
8798 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008799 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008800 return false;
8801
8802 if (MethodDecl->param_size() != MethodImpl->param_size())
8803 return false;
8804
8805 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8806 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8807 EF = MethodDecl->param_end();
8808 IM != EM && IF != EF; ++IM, ++IF) {
8809 const ParmVarDecl *DeclVar = (*IF);
8810 const ParmVarDecl *ImplVar = (*IM);
8811 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8812 return false;
8813 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8814 return false;
8815 }
8816 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8817
8818}
Richard Smith053f6c62014-05-16 23:01:30 +00008819
8820// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8821// doesn't include ASTContext.h
8822template
8823clang::LazyGenerationalUpdatePtr<
8824 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8825clang::LazyGenerationalUpdatePtr<
8826 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8827 const clang::ASTContext &Ctx, Decl *Value);