blob: d2c35851ee8e7a03befc079b751f7d3b71b78fc0 [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"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.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 {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
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}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
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) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000635 ExpandedTypes,
636 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000637 } 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
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000656 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000657
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000661 TTP->getPosition(),
662 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000663 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000666 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000667 SourceLocation(),
668 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000672 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
Charles Davis53c59df2010-08-16 03:33:14 +0000681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000682 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000687 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000688 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000689 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000690 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000693 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000694 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000695 return CreateMicrosoftCXXABI(*this);
696 }
David Blaikie8a40f702012-01-17 06:56:22 +0000697 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000698}
699
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
706 1, // opencl_global
707 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000708 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000709 4, // opencl_generic
710 5, // cuda_device
711 6, // cuda_constant
712 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000715 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000717 }
718}
719
David Tweed31d09b02013-09-13 12:04:22 +0000720static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
721 const LangOptions &LangOpts) {
722 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000723 case LangOptions::ASMM_Target:
724 return TI.useAddressSpaceMapMangling();
725 case LangOptions::ASMM_On:
726 return true;
727 case LangOptions::ASMM_Off:
728 return false;
729 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000730 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000731}
732
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000733ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000734 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000735 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000736 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
737 DependentTemplateSpecializationTypes(this_()),
738 SubstTemplateTemplateParmPacks(this_()),
739 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000740 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
741 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
742 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000743 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
744 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
745 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
746 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
747 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000748 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
749 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000750 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000751 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
752 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
753 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
754 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000755 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000756 TUDecl = TranslationUnitDecl::Create(*this);
757}
758
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000759ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000760 ReleaseParentMapEntries();
761
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000762 // Release the DenseMaps associated with DeclContext objects.
763 // FIXME: Is this the ideal solution?
764 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000765
Manuel Klimeka7328992013-06-03 13:51:33 +0000766 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000767 for (auto &Pair : Deallocations)
768 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
David Majnemere694f3e2015-08-14 14:43:50 +0000791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
794
Richard Smith423f46f2016-07-20 21:38:26 +0000795 for (const auto &Value : ModuleInitializers)
796 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000797}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000798
Manuel Klimek95403e62014-05-21 13:28:59 +0000799void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000800 if (!PointerParents) return;
801 for (const auto &Entry : *PointerParents) {
802 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
803 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
804 } else if (Entry.second.is<ParentVector *>()) {
805 delete Entry.second.get<ParentVector *>();
806 }
807 }
808 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000809 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
810 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000811 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000812 delete Entry.second.get<ParentVector *>();
813 }
814 }
815}
816
Douglas Gregor1a809332010-05-23 18:26:36 +0000817void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000818 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000819}
820
Mike Stump11289f42009-09-09 15:08:12 +0000821void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000822ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000823 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000824}
825
Chris Lattner4eb445d2007-01-26 01:27:23 +0000826void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000827 llvm::errs() << "\n*** AST Context Stats:\n";
828 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000829
Douglas Gregora30d0462009-05-26 14:40:08 +0000830 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000831#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000832#define ABSTRACT_TYPE(Name, Parent)
833#include "clang/AST/TypeNodes.def"
834 0 // Extra
835 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000836
Chris Lattner4eb445d2007-01-26 01:27:23 +0000837 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
838 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000839 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000840 }
841
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 unsigned Idx = 0;
843 unsigned TotalBytes = 0;
844#define TYPE(Name, Parent) \
845 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << " " << counts[Idx] << " " << #Name \
847 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000848 TotalBytes += counts[Idx] * sizeof(Name##Type); \
849 ++Idx;
850#define ABSTRACT_TYPE(Name, Parent)
851#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
854
Douglas Gregor7454c562010-07-02 20:37:36 +0000855 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
857 << NumImplicitDefaultConstructors
858 << " implicit default constructors created\n";
859 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
860 << NumImplicitCopyConstructors
861 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000862 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000863 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
864 << NumImplicitMoveConstructors
865 << " implicit move constructors created\n";
866 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
867 << NumImplicitCopyAssignmentOperators
868 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000870 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
871 << NumImplicitMoveAssignmentOperators
872 << " implicit move assignment operators created\n";
873 llvm::errs() << NumImplicitDestructorsDeclared << "/"
874 << NumImplicitDestructors
875 << " implicit destructors created\n";
876
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000877 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000878 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000879 ExternalSource->PrintStats();
880 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000881
Douglas Gregor5b11d492010-07-25 17:53:33 +0000882 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000883}
884
Richard Smith42413142015-05-15 20:05:43 +0000885void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
886 bool NotifyListeners) {
887 if (NotifyListeners)
888 if (auto *Listener = getASTMutationListener())
889 Listener->RedefinedHiddenDefinition(ND, M);
890
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000891 if (getLangOpts().ModulesLocalVisibility)
892 MergedDefModules[ND].push_back(M);
893 else
Richard Smith42413142015-05-15 20:05:43 +0000894 ND->setHidden(false);
895}
896
897void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
898 auto It = MergedDefModules.find(ND);
899 if (It == MergedDefModules.end())
900 return;
901
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000902 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000903 llvm::DenseSet<Module*> Found;
904 for (Module *&M : Merged)
905 if (!Found.insert(M).second)
906 M = nullptr;
907 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
908}
909
Richard Smithdc1f0422016-07-20 19:10:16 +0000910void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
911 if (LazyInitializers.empty())
912 return;
913
914 auto *Source = Ctx.getExternalSource();
915 assert(Source && "lazy initializers but no external source");
916
917 auto LazyInits = std::move(LazyInitializers);
918 LazyInitializers.clear();
919
920 for (auto ID : LazyInits)
921 Initializers.push_back(Source->GetExternalDecl(ID));
922
923 assert(LazyInitializers.empty() &&
924 "GetExternalDecl for lazy module initializer added more inits");
925}
926
927void ASTContext::addModuleInitializer(Module *M, Decl *D) {
928 // One special case: if we add a module initializer that imports another
929 // module, and that module's only initializer is an ImportDecl, simplify.
930 if (auto *ID = dyn_cast<ImportDecl>(D)) {
931 auto It = ModuleInitializers.find(ID->getImportedModule());
932
933 // Maybe the ImportDecl does nothing at all. (Common case.)
934 if (It == ModuleInitializers.end())
935 return;
936
937 // Maybe the ImportDecl only imports another ImportDecl.
938 auto &Imported = *It->second;
939 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
940 Imported.resolve(*this);
941 auto *OnlyDecl = Imported.Initializers.front();
942 if (isa<ImportDecl>(OnlyDecl))
943 D = OnlyDecl;
944 }
945 }
946
947 auto *&Inits = ModuleInitializers[M];
948 if (!Inits)
949 Inits = new (*this) PerModuleInitializers;
950 Inits->Initializers.push_back(D);
951}
952
953void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
954 auto *&Inits = ModuleInitializers[M];
955 if (!Inits)
956 Inits = new (*this) PerModuleInitializers;
957 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
958 IDs.begin(), IDs.end());
959}
960
961ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
962 auto It = ModuleInitializers.find(M);
963 if (It == ModuleInitializers.end())
964 return None;
965
966 auto *Inits = It->second;
967 Inits->resolve(*this);
968 return Inits->Initializers;
969}
970
Richard Smithf19e1272015-03-07 00:04:49 +0000971ExternCContextDecl *ASTContext::getExternCContextDecl() const {
972 if (!ExternCContext)
973 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
974
975 return ExternCContext;
976}
977
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000978BuiltinTemplateDecl *
979ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
980 const IdentifierInfo *II) const {
981 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
982 BuiltinTemplate->setImplicit();
983 TUDecl->addDecl(BuiltinTemplate);
984
985 return BuiltinTemplate;
986}
987
988BuiltinTemplateDecl *
989ASTContext::getMakeIntegerSeqDecl() const {
990 if (!MakeIntegerSeqDecl)
991 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
992 getMakeIntegerSeqName());
993 return MakeIntegerSeqDecl;
994}
995
Eric Fiselier6ad68552016-07-01 01:24:09 +0000996BuiltinTemplateDecl *
997ASTContext::getTypePackElementDecl() const {
998 if (!TypePackElementDecl)
999 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1000 getTypePackElementName());
1001 return TypePackElementDecl;
1002}
1003
Alp Toker2dea15b2013-12-17 01:22:38 +00001004RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1005 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001006 SourceLocation Loc;
1007 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001008 if (getLangOpts().CPlusPlus)
1009 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1010 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001011 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001012 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1013 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001015 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1016 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001017 return NewDecl;
1018}
1019
1020TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1021 StringRef Name) const {
1022 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1023 TypedefDecl *NewDecl = TypedefDecl::Create(
1024 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1025 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1026 NewDecl->setImplicit();
1027 return NewDecl;
1028}
1029
Douglas Gregor801c99d2011-08-12 06:49:56 +00001030TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001031 if (!Int128Decl)
1032 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033 return Int128Decl;
1034}
1035
1036TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001037 if (!UInt128Decl)
1038 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001039 return UInt128Decl;
1040}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001041
John McCall48f2d582009-10-23 23:03:21 +00001042void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001043 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001044 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001045 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001046}
1047
Artem Belevichb5bc9232015-09-22 17:23:22 +00001048void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1049 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001050 assert((!this->Target || this->Target == &Target) &&
1051 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001052 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001053
Douglas Gregore8bbc122011-09-02 00:18:52 +00001054 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001055 this->AuxTarget = AuxTarget;
1056
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 ABI.reset(createCXXABI(Target));
1058 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001059 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060
Chris Lattner970e54e2006-11-12 00:37:36 +00001061 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001062 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner970e54e2006-11-12 00:37:36 +00001064 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001065 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001066 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001067 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001068 InitBuiltinType(CharTy, BuiltinType::Char_S);
1069 else
1070 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001071 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001072 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1073 InitBuiltinType(ShortTy, BuiltinType::Short);
1074 InitBuiltinType(IntTy, BuiltinType::Int);
1075 InitBuiltinType(LongTy, BuiltinType::Long);
1076 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattner970e54e2006-11-12 00:37:36 +00001078 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001079 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1080 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1081 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1082 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1083 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Chris Lattner970e54e2006-11-12 00:37:36 +00001085 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001086 InitBuiltinType(FloatTy, BuiltinType::Float);
1087 InitBuiltinType(DoubleTy, BuiltinType::Double);
1088 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001089
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001090 // GNU extension, __float128 for IEEE quadruple precision
1091 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1092
Chris Lattnerf122cef2009-04-30 02:43:43 +00001093 // GNU extension, 128-bit integers.
1094 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1095 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1096
Hans Wennborg0d81e012013-05-10 10:08:40 +00001097 // C++ 3.9.1p5
1098 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1099 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1100 else // -fshort-wchar makes wchar_t be unsigned.
1101 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1102 if (LangOpts.CPlusPlus && LangOpts.WChar)
1103 WideCharTy = WCharTy;
1104 else {
1105 // C99 (or C++ using -fno-wchar).
1106 WideCharTy = getFromTargetType(Target.getWCharType());
1107 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001108
James Molloy36365542012-05-04 10:55:22 +00001109 WIntTy = getFromTargetType(Target.getWIntType());
1110
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001111 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1112 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1113 else // C99
1114 Char16Ty = getFromTargetType(Target.getChar16Type());
1115
1116 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1117 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1118 else // C99
1119 Char32Ty = getFromTargetType(Target.getChar32Type());
1120
Douglas Gregor4619e432008-12-05 23:32:09 +00001121 // Placeholder type for type-dependent expressions whose type is
1122 // completely unknown. No code should ever check a type against
1123 // DependentTy and users should never see it; however, it is here to
1124 // help diagnose failures to properly check for type-dependent
1125 // expressions.
1126 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127
John McCall36e7fe32010-10-12 00:20:44 +00001128 // Placeholder type for functions.
1129 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1130
John McCall0009fcc2011-04-26 20:42:42 +00001131 // Placeholder type for bound members.
1132 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1133
John McCall526ab472011-10-25 17:37:35 +00001134 // Placeholder type for pseudo-objects.
1135 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1136
John McCall31996342011-04-07 08:22:57 +00001137 // "any" type; useful for debugger-like clients.
1138 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1139
John McCall8a6b59a2011-10-17 18:09:15 +00001140 // Placeholder type for unbridged ARC casts.
1141 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1142
Eli Friedman34866c72012-08-31 00:14:07 +00001143 // Placeholder type for builtin functions.
1144 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1145
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001146 // Placeholder type for OMP array sections.
1147 if (LangOpts.OpenMP)
1148 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1149
Chris Lattner970e54e2006-11-12 00:37:36 +00001150 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001151 FloatComplexTy = getComplexType(FloatTy);
1152 DoubleComplexTy = getComplexType(DoubleTy);
1153 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001154 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001155
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001156 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001157 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1158 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001159 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001160
Alexey Bader954ba212016-04-08 13:40:33 +00001161 if (LangOpts.OpenCL) {
1162#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1163 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001164#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001165
Guy Benyei61054192013-02-07 10:55:47 +00001166 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001167 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001168 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1169 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1170 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1171 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001172 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001173
1174 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001175 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1176 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001177
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001178 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001179
1180 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001181
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001182 // void * type
1183 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001184
1185 // nullptr type (C++0x 2.14.7)
1186 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001187
1188 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1189 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001190
1191 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001192 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001193}
1194
David Blaikie9c902b52011-09-25 23:23:43 +00001195DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001196 return SourceMgr.getDiagnostics();
1197}
1198
Douglas Gregor561eceb2010-08-30 16:49:28 +00001199AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1200 AttrVec *&Result = DeclAttrs[D];
1201 if (!Result) {
1202 void *Mem = Allocate(sizeof(AttrVec));
1203 Result = new (Mem) AttrVec;
1204 }
1205
1206 return *Result;
1207}
1208
1209/// \brief Erase the attributes corresponding to the given declaration.
1210void ASTContext::eraseDeclAttrs(const Decl *D) {
1211 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1212 if (Pos != DeclAttrs.end()) {
1213 Pos->second->~AttrVec();
1214 DeclAttrs.erase(Pos);
1215 }
1216}
1217
Larisse Voufo39a1e502013-08-06 01:03:05 +00001218// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001219MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001220ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001221 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001222 return getTemplateOrSpecializationInfo(Var)
1223 .dyn_cast<MemberSpecializationInfo *>();
1224}
1225
1226ASTContext::TemplateOrSpecializationInfo
1227ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1228 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1229 TemplateOrInstantiation.find(Var);
1230 if (Pos == TemplateOrInstantiation.end())
1231 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001232
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001233 return Pos->second;
1234}
1235
Mike Stump11289f42009-09-09 15:08:12 +00001236void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001237ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001238 TemplateSpecializationKind TSK,
1239 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001240 assert(Inst->isStaticDataMember() && "Not a static data member");
1241 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001242 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1243 Tmpl, TSK, PointOfInstantiation));
1244}
1245
1246void
1247ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1248 TemplateOrSpecializationInfo TSI) {
1249 assert(!TemplateOrInstantiation[Inst] &&
1250 "Already noted what the variable was instantiated from");
1251 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001252}
1253
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001254FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1255 const FunctionDecl *FD){
1256 assert(FD && "Specialization is 0");
1257 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001258 = ClassScopeSpecializationPattern.find(FD);
1259 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001260 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001261
1262 return Pos->second;
1263}
1264
1265void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1266 FunctionDecl *Pattern) {
1267 assert(FD && "Specialization is 0");
1268 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001269 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001270}
1271
John McCalle61f2ba2009-11-18 02:36:19 +00001272NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001273ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001274 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001275 = InstantiatedFromUsingDecl.find(UUD);
1276 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001277 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001278
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001279 return Pos->second;
1280}
1281
1282void
John McCallb96ec562009-12-04 22:46:56 +00001283ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1284 assert((isa<UsingDecl>(Pattern) ||
1285 isa<UnresolvedUsingValueDecl>(Pattern) ||
1286 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1287 "pattern decl is not a using decl");
1288 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1289 InstantiatedFromUsingDecl[Inst] = Pattern;
1290}
1291
1292UsingShadowDecl *
1293ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1294 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1295 = InstantiatedFromUsingShadowDecl.find(Inst);
1296 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001297 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001298
1299 return Pos->second;
1300}
1301
1302void
1303ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1304 UsingShadowDecl *Pattern) {
1305 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1306 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001307}
1308
Anders Carlsson5da84842009-09-01 04:26:58 +00001309FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1310 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1311 = InstantiatedFromUnnamedFieldDecl.find(Field);
1312 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001313 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Anders Carlsson5da84842009-09-01 04:26:58 +00001315 return Pos->second;
1316}
1317
1318void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1319 FieldDecl *Tmpl) {
1320 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1321 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1322 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1323 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001324
Anders Carlsson5da84842009-09-01 04:26:58 +00001325 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1326}
1327
Douglas Gregor832940b2010-03-02 23:58:15 +00001328ASTContext::overridden_cxx_method_iterator
1329ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001330 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1331 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001332 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001333 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001334 return Pos->second.begin();
1335}
1336
1337ASTContext::overridden_cxx_method_iterator
1338ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001339 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1340 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001341 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001342 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001343 return Pos->second.end();
1344}
1345
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001346unsigned
1347ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001348 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1349 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001350 if (Pos == OverriddenMethods.end())
1351 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001352 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001353}
1354
Clement Courbet6ecaec82016-07-05 07:49:31 +00001355ASTContext::overridden_method_range
1356ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1357 return overridden_method_range(overridden_methods_begin(Method),
1358 overridden_methods_end(Method));
1359}
1360
Douglas Gregor832940b2010-03-02 23:58:15 +00001361void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1362 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001363 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001364 OverriddenMethods[Method].push_back(Overridden);
1365}
1366
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001367void ASTContext::getOverriddenMethods(
1368 const NamedDecl *D,
1369 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001370 assert(D);
1371
1372 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001373 Overridden.append(overridden_methods_begin(CXXMethod),
1374 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001375 return;
1376 }
1377
1378 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1379 if (!Method)
1380 return;
1381
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001382 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1383 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001384 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001385}
1386
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001387void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1388 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1389 assert(!Import->isFromASTFile() && "Non-local import declaration");
1390 if (!FirstLocalImport) {
1391 FirstLocalImport = Import;
1392 LastLocalImport = Import;
1393 return;
1394 }
1395
1396 LastLocalImport->NextLocalImport = Import;
1397 LastLocalImport = Import;
1398}
1399
Chris Lattner53cfe802007-07-18 17:52:12 +00001400//===----------------------------------------------------------------------===//
1401// Type Sizing and Analysis
1402//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001403
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001404/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1405/// scalar floating point type.
1406const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001407 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001408 assert(BT && "Not a floating point type!");
1409 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001410 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001411 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001412 case BuiltinType::Float: return Target->getFloatFormat();
1413 case BuiltinType::Double: return Target->getDoubleFormat();
1414 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001415 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001416 }
1417}
1418
Rafael Espindola71eccb32013-08-08 19:53:46 +00001419CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001420 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001421
John McCall94268702010-10-08 18:24:19 +00001422 bool UseAlignAttrOnly = false;
1423 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1424 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001425
John McCall94268702010-10-08 18:24:19 +00001426 // __attribute__((aligned)) can increase or decrease alignment
1427 // *except* on a struct or struct member, where it only increases
1428 // alignment unless 'packed' is also specified.
1429 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001430 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001431 // ignore that possibility; Sema should diagnose it.
1432 if (isa<FieldDecl>(D)) {
1433 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1434 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1435 } else {
1436 UseAlignAttrOnly = true;
1437 }
1438 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001439 else if (isa<FieldDecl>(D))
1440 UseAlignAttrOnly =
1441 D->hasAttr<PackedAttr>() ||
1442 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001443
John McCall4e819612011-01-20 07:57:12 +00001444 // If we're using the align attribute only, just ignore everything
1445 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001446 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001447 // do nothing
1448
John McCall94268702010-10-08 18:24:19 +00001449 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001450 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001451 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001452 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001453 T = RT->getPointeeType();
1454 else
1455 T = getPointerType(RT->getPointeeType());
1456 }
Richard Smithf6d70302014-06-10 23:34:28 +00001457 QualType BaseT = getBaseElementType(T);
1458 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001459 // Adjust alignments of declarations with array type by the
1460 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001461 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001462 unsigned MinWidth = Target->getLargeArrayMinWidth();
1463 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001464 if (isa<VariableArrayType>(arrayType))
1465 Align = std::max(Align, Target->getLargeArrayAlign());
1466 else if (isa<ConstantArrayType>(arrayType) &&
1467 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1468 Align = std::max(Align, Target->getLargeArrayAlign());
1469 }
John McCall33ddac02011-01-19 10:06:00 +00001470 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001471 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001472 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001473 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001474 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1475 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001476 }
John McCall4e819612011-01-20 07:57:12 +00001477
1478 // Fields can be subject to extra alignment constraints, like if
1479 // the field is packed, the struct is packed, or the struct has a
1480 // a max-field-alignment constraint (#pragma pack). So calculate
1481 // the actual alignment of the field within the struct, and then
1482 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001483 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1484 const RecordDecl *Parent = Field->getParent();
1485 // We can only produce a sensible answer if the record is valid.
1486 if (!Parent->isInvalidDecl()) {
1487 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001488
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001489 // Start with the record's overall alignment.
1490 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001491
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001492 // Use the GCD of that and the offset within the record.
1493 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1494 if (Offset > 0) {
1495 // Alignment is always a power of 2, so the GCD will be a power of 2,
1496 // which means we get to do this crazy thing instead of Euclid's.
1497 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1498 if (LowBitOfOffset < FieldAlign)
1499 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1500 }
1501
1502 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001503 }
Charles Davis3fc51072010-02-23 04:52:00 +00001504 }
Chris Lattner68061312009-01-24 21:53:27 +00001505 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001506
Ken Dyckcc56c542011-01-15 18:38:59 +00001507 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001508}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001509
John McCallf1249922012-08-21 04:10:00 +00001510// getTypeInfoDataSizeInChars - Return the size of a type, in
1511// chars. If the type is a record, its data size is returned. This is
1512// the size of the memcpy that's performed when assigning this type
1513// using a trivial copy/move assignment operator.
1514std::pair<CharUnits, CharUnits>
1515ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1516 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1517
1518 // In C++, objects can sometimes be allocated into the tail padding
1519 // of a base-class subobject. We decide whether that's possible
1520 // during class layout, so here we can just trust the layout results.
1521 if (getLangOpts().CPlusPlus) {
1522 if (const RecordType *RT = T->getAs<RecordType>()) {
1523 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1524 sizeAndAlign.first = layout.getDataSize();
1525 }
1526 }
1527
1528 return sizeAndAlign;
1529}
1530
Richard Trieu04d2d942013-05-14 21:59:17 +00001531/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1532/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1533std::pair<CharUnits, CharUnits>
1534static getConstantArrayInfoInChars(const ASTContext &Context,
1535 const ConstantArrayType *CAT) {
1536 std::pair<CharUnits, CharUnits> EltInfo =
1537 Context.getTypeInfoInChars(CAT->getElementType());
1538 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001539 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1540 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001541 "Overflow in array type char size evaluation");
1542 uint64_t Width = EltInfo.first.getQuantity() * Size;
1543 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001544 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1545 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001546 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001547 return std::make_pair(CharUnits::fromQuantity(Width),
1548 CharUnits::fromQuantity(Align));
1549}
1550
John McCall87fe5d52010-05-20 01:18:31 +00001551std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001552ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001553 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1554 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001555 TypeInfo Info = getTypeInfo(T);
1556 return std::make_pair(toCharUnitsFromBits(Info.Width),
1557 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001558}
1559
1560std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001561ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001562 return getTypeInfoInChars(T.getTypePtr());
1563}
1564
David Majnemer34b57492014-07-30 01:30:47 +00001565bool ASTContext::isAlignmentRequired(const Type *T) const {
1566 return getTypeInfo(T).AlignIsRequired;
1567}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001568
David Majnemer34b57492014-07-30 01:30:47 +00001569bool ASTContext::isAlignmentRequired(QualType T) const {
1570 return isAlignmentRequired(T.getTypePtr());
1571}
1572
Richard Smithb2f0f052016-10-10 18:54:32 +00001573unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1574 // An alignment on a typedef overrides anything else.
1575 if (auto *TT = T->getAs<TypedefType>())
1576 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1577 return Align;
1578
1579 // If we have an (array of) complete type, we're done.
1580 T = getBaseElementType(T);
1581 if (!T->isIncompleteType())
1582 return getTypeAlign(T);
1583
1584 // If we had an array type, its element type might be a typedef
1585 // type with an alignment attribute.
1586 if (auto *TT = T->getAs<TypedefType>())
1587 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1588 return Align;
1589
1590 // Otherwise, see if the declaration of the type had an attribute.
1591 if (auto *TT = T->getAs<TagType>())
1592 return TT->getDecl()->getMaxAlignment();
1593
1594 return 0;
1595}
1596
David Majnemer34b57492014-07-30 01:30:47 +00001597TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001598 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1599 if (I != MemoizedTypeInfo.end())
1600 return I->second;
1601
1602 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1603 TypeInfo TI = getTypeInfoImpl(T);
1604 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001605 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001606}
1607
1608/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1609/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001610///
1611/// FIXME: Pointers into different addr spaces could have different sizes and
1612/// alignment requirements: getPointerInfo should take an AddrSpace, this
1613/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001614TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1615 uint64_t Width = 0;
1616 unsigned Align = 8;
1617 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001618 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001619#define TYPE(Class, Base)
1620#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001621#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001622#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001623#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1624 case Type::Class: \
1625 assert(!T->isDependentType() && "should not see dependent types here"); \
1626 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001627#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001628 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001629
Chris Lattner355332d2007-07-13 22:27:08 +00001630 case Type::FunctionNoProto:
1631 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001632 // GCC extension: alignof(function) = 32 bits
1633 Width = 0;
1634 Align = 32;
1635 break;
1636
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001637 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001638 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001639 Width = 0;
1640 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1641 break;
1642
Steve Naroff5c131802007-08-30 01:06:46 +00001643 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001644 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001645
David Majnemer34b57492014-07-30 01:30:47 +00001646 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001647 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001648 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001649 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001650 Width = EltInfo.Width * Size;
1651 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001652 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1653 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001654 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001655 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001656 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001657 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001658 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001659 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001660 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1661 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001662 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001663 // If the alignment is not a power of 2, round up to the next power of 2.
1664 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001665 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001666 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001667 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001668 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001669 // Adjust the alignment based on the target max.
1670 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1671 if (TargetVectorAlign && TargetVectorAlign < Align)
1672 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001673 break;
1674 }
Chris Lattner647fb222007-07-18 18:26:58 +00001675
Chris Lattner7570e9c2008-03-08 08:52:55 +00001676 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001677 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001678 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001679 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001680 // GCC extension: alignof(void) = 8 bits.
1681 Width = 0;
1682 Align = 8;
1683 break;
1684
Chris Lattner6a4f7452007-12-19 19:23:28 +00001685 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001686 Width = Target->getBoolWidth();
1687 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001688 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001689 case BuiltinType::Char_S:
1690 case BuiltinType::Char_U:
1691 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001692 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001693 Width = Target->getCharWidth();
1694 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001695 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001696 case BuiltinType::WChar_S:
1697 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001698 Width = Target->getWCharWidth();
1699 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001700 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001701 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001702 Width = Target->getChar16Width();
1703 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001704 break;
1705 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001706 Width = Target->getChar32Width();
1707 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001708 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001709 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001710 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001711 Width = Target->getShortWidth();
1712 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001713 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001714 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001715 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001716 Width = Target->getIntWidth();
1717 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001718 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001719 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001720 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001721 Width = Target->getLongWidth();
1722 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001723 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001724 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001725 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001726 Width = Target->getLongLongWidth();
1727 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001728 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001729 case BuiltinType::Int128:
1730 case BuiltinType::UInt128:
1731 Width = 128;
1732 Align = 128; // int128_t is 128-bit aligned on all targets.
1733 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001734 case BuiltinType::Half:
1735 Width = Target->getHalfWidth();
1736 Align = Target->getHalfAlign();
1737 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001738 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001739 Width = Target->getFloatWidth();
1740 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001741 break;
1742 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001743 Width = Target->getDoubleWidth();
1744 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001745 break;
1746 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001747 Width = Target->getLongDoubleWidth();
1748 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001749 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001750 case BuiltinType::Float128:
1751 Width = Target->getFloat128Width();
1752 Align = Target->getFloat128Align();
1753 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001754 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001755 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1756 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001757 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001758 case BuiltinType::ObjCId:
1759 case BuiltinType::ObjCClass:
1760 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001761 Width = Target->getPointerWidth(0);
1762 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001763 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001764 case BuiltinType::OCLSampler: {
1765 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1766 Width = Target->getPointerWidth(AS);
1767 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001768 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001769 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001770 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001771 case BuiltinType::OCLClkEvent:
1772 case BuiltinType::OCLQueue:
1773 case BuiltinType::OCLNDRange:
1774 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001775 // Currently these types are pointers to opaque types.
1776 Width = Target->getPointerWidth(0);
1777 Align = Target->getPointerAlign(0);
1778 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001779#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1780 case BuiltinType::Id:
1781#include "clang/Basic/OpenCLImageTypes.def"
1782 {
1783 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1784 Width = Target->getPointerWidth(AS);
1785 Align = Target->getPointerAlign(AS);
1786 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001787 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001788 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001789 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001790 Width = Target->getPointerWidth(0);
1791 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001792 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001793 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001794 unsigned AS = getTargetAddressSpace(
1795 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001796 Width = Target->getPointerWidth(AS);
1797 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001798 break;
1799 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001800 case Type::LValueReference:
1801 case Type::RValueReference: {
1802 // alignof and sizeof should never enter this code path here, so we go
1803 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001804 unsigned AS = getTargetAddressSpace(
1805 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001806 Width = Target->getPointerWidth(AS);
1807 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001808 break;
1809 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001810 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001811 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001812 Width = Target->getPointerWidth(AS);
1813 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001814 break;
1815 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001816 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001817 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001818 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001819 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001820 }
Chris Lattner647fb222007-07-18 18:26:58 +00001821 case Type::Complex: {
1822 // Complex types have the same alignment as their elements, but twice the
1823 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001824 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1825 Width = EltInfo.Width * 2;
1826 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001827 break;
1828 }
John McCall8b07ec22010-05-15 11:32:37 +00001829 case Type::ObjCObject:
1830 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001831 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001832 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001833 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001834 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001835 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001836 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001837 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001838 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001839 break;
1840 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001841 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001842 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001843 const TagType *TT = cast<TagType>(T);
1844
1845 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001846 Width = 8;
1847 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001848 break;
1849 }
Mike Stump11289f42009-09-09 15:08:12 +00001850
David Majnemer475b25e2015-01-21 10:54:38 +00001851 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1852 const EnumDecl *ED = ET->getDecl();
1853 TypeInfo Info =
1854 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1855 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1856 Info.Align = AttrAlign;
1857 Info.AlignIsRequired = true;
1858 }
1859 return Info;
1860 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001861
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001862 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001863 const RecordDecl *RD = RT->getDecl();
1864 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001865 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001866 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001867 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001868 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001869 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001870
Chris Lattner63d2b362009-10-22 05:17:15 +00001871 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001872 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1873 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001874
Richard Smith30482bc2011-02-20 03:19:35 +00001875 case Type::Auto: {
1876 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001877 assert(!A->getDeducedType().isNull() &&
1878 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001879 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001880 }
1881
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001882 case Type::Paren:
1883 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1884
Manman Rene6be26c2016-09-13 17:25:08 +00001885 case Type::ObjCTypeParam:
1886 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1887
Douglas Gregoref462e62009-04-30 17:32:17 +00001888 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001889 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001890 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001891 // If the typedef has an aligned attribute on it, it overrides any computed
1892 // alignment we have. This violates the GCC documentation (which says that
1893 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001894 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001895 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001896 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001897 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001898 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001899 AlignIsRequired = Info.AlignIsRequired;
1900 }
David Majnemer34b57492014-07-30 01:30:47 +00001901 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001902 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001903 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001904
Abramo Bagnara6150c882010-05-11 21:36:43 +00001905 case Type::Elaborated:
1906 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001907
John McCall81904512011-01-06 01:58:22 +00001908 case Type::Attributed:
1909 return getTypeInfo(
1910 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1911
Eli Friedman0dfb8892011-10-06 23:00:33 +00001912 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001913 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001914 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1915 Width = Info.Width;
1916 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001917
1918 // If the size of the type doesn't exceed the platform's max
1919 // atomic promotion width, make the size and alignment more
1920 // favorable to atomic operations:
1921 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1922 // Round the size up to a power of 2.
1923 if (!llvm::isPowerOf2_64(Width))
1924 Width = llvm::NextPowerOf2(Width);
1925
1926 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001927 Align = static_cast<unsigned>(Width);
1928 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001929 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001930 break;
1931
1932 case Type::Pipe: {
1933 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1934 Width = Info.Width;
1935 Align = Info.Align;
1936 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001937
Douglas Gregoref462e62009-04-30 17:32:17 +00001938 }
Mike Stump11289f42009-09-09 15:08:12 +00001939
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001940 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001941 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001942}
1943
Alexey Bataev00396512015-07-02 03:40:19 +00001944unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1945 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1946 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1947 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1948 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1949 getTargetInfo().getABI() == "elfv1-qpx" &&
1950 T->isSpecificBuiltinType(BuiltinType::Double))
1951 SimdAlign = 256;
1952 return SimdAlign;
1953}
1954
Ken Dyckcc56c542011-01-15 18:38:59 +00001955/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1956CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1957 return CharUnits::fromQuantity(BitSize / getCharWidth());
1958}
1959
Ken Dyckb0fcc592011-02-11 01:54:29 +00001960/// toBits - Convert a size in characters to a size in characters.
1961int64_t ASTContext::toBits(CharUnits CharSize) const {
1962 return CharSize.getQuantity() * getCharWidth();
1963}
1964
Ken Dyck8c89d592009-12-22 14:23:30 +00001965/// getTypeSizeInChars - Return the size of the specified type, in characters.
1966/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001967CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001968 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001969}
Jay Foad39c79802011-01-12 09:06:06 +00001970CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001971 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001972}
1973
Ken Dycka6046ab2010-01-26 17:25:18 +00001974/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001975/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001976CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001977 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001978}
Jay Foad39c79802011-01-12 09:06:06 +00001979CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001980 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001981}
1982
Chris Lattnera3402cd2009-01-27 18:08:34 +00001983/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1984/// type for the current target in bits. This can be different than the ABI
1985/// alignment in cases where it is beneficial for performance to overalign
1986/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001987unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001988 TypeInfo TI = getTypeInfo(T);
1989 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001990
David Majnemere1544562015-04-24 01:25:05 +00001991 T = T->getBaseElementTypeUnsafe();
1992
1993 // The preferred alignment of member pointers is that of a pointer.
1994 if (T->isMemberPointerType())
1995 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1996
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001997 if (!Target->allowsLargerPreferedTypeAlignment())
1998 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001999
Eli Friedman7ab09572009-05-25 21:27:19 +00002000 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002001 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002002 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002003 if (const EnumType *ET = T->getAs<EnumType>())
2004 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002005 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002006 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2007 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002008 // Don't increase the alignment if an alignment attribute was specified on a
2009 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002010 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002011 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002012
Chris Lattnera3402cd2009-01-27 18:08:34 +00002013 return ABIAlign;
2014}
2015
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002016/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2017/// for __attribute__((aligned)) on this target, to be used if no alignment
2018/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002019unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002020 return getTargetInfo().getDefaultAlignForAttributeAligned();
2021}
2022
Ulrich Weigandfa806422013-05-06 16:23:57 +00002023/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2024/// to a global variable of the specified type.
2025unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2026 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2027}
2028
2029/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2030/// should be given to a global variable of the specified type.
2031CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2032 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2033}
2034
David Majnemer08ef2ba2015-06-23 20:34:18 +00002035CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2036 CharUnits Offset = CharUnits::Zero();
2037 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2038 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2039 Offset += Layout->getBaseClassOffset(Base);
2040 Layout = &getASTRecordLayout(Base);
2041 }
2042 return Offset;
2043}
2044
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002045/// DeepCollectObjCIvars -
2046/// This routine first collects all declared, but not synthesized, ivars in
2047/// super class and then collects all ivars, including those synthesized for
2048/// current class. This routine is used for implementation of current class
2049/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002050///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002051void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2052 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002053 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002054 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2055 DeepCollectObjCIvars(SuperClass, false, Ivars);
2056 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002057 for (const auto *I : OI->ivars())
2058 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002059 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002060 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002061 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002062 Iv= Iv->getNextIvar())
2063 Ivars.push_back(Iv);
2064 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002065}
2066
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002067/// CollectInheritedProtocols - Collect all protocols in current class and
2068/// those inherited by it.
2069void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002070 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002071 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002072 // We can use protocol_iterator here instead of
2073 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002074 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002075 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002076 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002077
2078 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002079 for (const auto *Cat : OI->visible_categories())
2080 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002081
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002082 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2083 while (SD) {
2084 CollectInheritedProtocols(SD, Protocols);
2085 SD = SD->getSuperClass();
2086 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002087 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002088 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002089 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002090 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002091 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002092 // Insert the protocol.
2093 if (!Protocols.insert(
2094 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2095 return;
2096
2097 for (auto *Proto : OP->protocols())
2098 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002099 }
2100}
2101
Jay Foad39c79802011-01-12 09:06:06 +00002102unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002103 unsigned count = 0;
2104 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002105 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002106 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002107
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002108 // Count ivar defined in this class's implementation. This
2109 // includes synthesized ivars.
2110 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002111 count += ImplDecl->ivar_size();
2112
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002113 return count;
2114}
2115
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002116bool ASTContext::isSentinelNullExpr(const Expr *E) {
2117 if (!E)
2118 return false;
2119
2120 // nullptr_t is always treated as null.
2121 if (E->getType()->isNullPtrType()) return true;
2122
2123 if (E->getType()->isAnyPointerType() &&
2124 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2125 Expr::NPC_ValueDependentIsNull))
2126 return true;
2127
2128 // Unfortunately, __null has type 'int'.
2129 if (isa<GNUNullExpr>(E)) return true;
2130
2131 return false;
2132}
2133
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002134/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2135ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2136 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2137 I = ObjCImpls.find(D);
2138 if (I != ObjCImpls.end())
2139 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002140 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002141}
2142/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2143ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2144 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2145 I = ObjCImpls.find(D);
2146 if (I != ObjCImpls.end())
2147 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002148 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002149}
2150
2151/// \brief Set the implementation of ObjCInterfaceDecl.
2152void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2153 ObjCImplementationDecl *ImplD) {
2154 assert(IFaceD && ImplD && "Passed null params");
2155 ObjCImpls[IFaceD] = ImplD;
2156}
2157/// \brief Set the implementation of ObjCCategoryDecl.
2158void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2159 ObjCCategoryImplDecl *ImplD) {
2160 assert(CatD && ImplD && "Passed null params");
2161 ObjCImpls[CatD] = ImplD;
2162}
2163
Chandler Carruth21c90602015-12-30 03:24:14 +00002164const ObjCMethodDecl *
2165ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2166 return ObjCMethodRedecls.lookup(MD);
2167}
2168
2169void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2170 const ObjCMethodDecl *Redecl) {
2171 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2172 ObjCMethodRedecls[MD] = Redecl;
2173}
2174
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002175const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2176 const NamedDecl *ND) const {
2177 if (const ObjCInterfaceDecl *ID =
2178 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002179 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002180 if (const ObjCCategoryDecl *CD =
2181 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002182 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002183 if (const ObjCImplDecl *IMD =
2184 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002185 return IMD->getClassInterface();
2186
Craig Topper36250ad2014-05-12 05:36:57 +00002187 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002188}
2189
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002190/// \brief Get the copy initialization expression of VarDecl,or NULL if
2191/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002192Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002193 assert(VD && "Passed null params");
2194 assert(VD->hasAttr<BlocksAttr>() &&
2195 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002196 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002197 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002198 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002199}
2200
2201/// \brief Set the copy inialization expression of a block var decl.
2202void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2203 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002204 assert(VD->hasAttr<BlocksAttr>() &&
2205 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002206 BlockVarCopyInits[VD] = Init;
2207}
2208
John McCallbcd03502009-12-07 02:54:59 +00002209TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002210 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002211 if (!DataSize)
2212 DataSize = TypeLoc::getFullDataSizeForType(T);
2213 else
2214 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002215 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002216
John McCallbcd03502009-12-07 02:54:59 +00002217 TypeSourceInfo *TInfo =
2218 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2219 new (TInfo) TypeSourceInfo(T);
2220 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002221}
2222
John McCallbcd03502009-12-07 02:54:59 +00002223TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002224 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002225 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002226 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002227 return DI;
2228}
2229
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002230const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002231ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002232 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002233}
2234
2235const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002236ASTContext::getASTObjCImplementationLayout(
2237 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002238 return getObjCLayout(D->getClassInterface(), D);
2239}
2240
Chris Lattner983a8bb2007-07-13 22:13:22 +00002241//===----------------------------------------------------------------------===//
2242// Type creation/memoization methods
2243//===----------------------------------------------------------------------===//
2244
Jay Foad39c79802011-01-12 09:06:06 +00002245QualType
John McCall33ddac02011-01-19 10:06:00 +00002246ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2247 unsigned fastQuals = quals.getFastQualifiers();
2248 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002249
2250 // Check if we've already instantiated this type.
2251 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002252 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002253 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002254 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2255 assert(eq->getQualifiers() == quals);
2256 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002257 }
2258
John McCall33ddac02011-01-19 10:06:00 +00002259 // If the base type is not canonical, make the appropriate canonical type.
2260 QualType canon;
2261 if (!baseType->isCanonicalUnqualified()) {
2262 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002263 canonSplit.Quals.addConsistentQualifiers(quals);
2264 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002265
2266 // Re-find the insert position.
2267 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2268 }
2269
2270 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2271 ExtQualNodes.InsertNode(eq, insertPos);
2272 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002273}
2274
Jay Foad39c79802011-01-12 09:06:06 +00002275QualType
2276ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002277 QualType CanT = getCanonicalType(T);
2278 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002279 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002280
John McCall8ccfcb52009-09-24 19:53:00 +00002281 // If we are composing extended qualifiers together, merge together
2282 // into one ExtQuals node.
2283 QualifierCollector Quals;
2284 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002285
John McCall8ccfcb52009-09-24 19:53:00 +00002286 // If this type already has an address space specified, it cannot get
2287 // another one.
2288 assert(!Quals.hasAddressSpace() &&
2289 "Type cannot be in multiple addr spaces!");
2290 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002291
John McCall8ccfcb52009-09-24 19:53:00 +00002292 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002293}
2294
Chris Lattnerd60183d2009-02-18 22:53:11 +00002295QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002296 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002297 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002298 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002299 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002300
John McCall53fa7142010-12-24 02:08:15 +00002301 if (const PointerType *ptr = T->getAs<PointerType>()) {
2302 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002303 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002304 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2305 return getPointerType(ResultType);
2306 }
2307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
John McCall8ccfcb52009-09-24 19:53:00 +00002309 // If we are composing extended qualifiers together, merge together
2310 // into one ExtQuals node.
2311 QualifierCollector Quals;
2312 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002313
John McCall8ccfcb52009-09-24 19:53:00 +00002314 // If this type already has an ObjCGC specified, it cannot get
2315 // another one.
2316 assert(!Quals.hasObjCGCAttr() &&
2317 "Type cannot have multiple ObjCGCs!");
2318 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002319
John McCall8ccfcb52009-09-24 19:53:00 +00002320 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002321}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002322
John McCall4f5019e2010-12-19 02:44:49 +00002323const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2324 FunctionType::ExtInfo Info) {
2325 if (T->getExtInfo() == Info)
2326 return T;
2327
2328 QualType Result;
2329 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002330 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002331 } else {
2332 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2333 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2334 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002335 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002336 }
2337
2338 return cast<FunctionType>(Result.getTypePtr());
2339}
2340
Richard Smith2a7d4812013-05-04 07:00:32 +00002341void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2342 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002343 FD = FD->getMostRecentDecl();
2344 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002345 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2346 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002347 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002348 if (FunctionDecl *Next = FD->getPreviousDecl())
2349 FD = Next;
2350 else
2351 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002352 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002353 if (ASTMutationListener *L = getASTMutationListener())
2354 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002355}
2356
Richard Smith0b3a4622014-11-13 20:01:57 +00002357/// Get a function type and produce the equivalent function type with the
2358/// specified exception specification. Type sugar that can be present on a
2359/// declaration of a function with an exception specification is permitted
2360/// and preserved. Other type sugar (for instance, typedefs) is not.
2361static QualType getFunctionTypeWithExceptionSpec(
2362 ASTContext &Context, QualType Orig,
2363 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2364 // Might have some parens.
2365 if (auto *PT = dyn_cast<ParenType>(Orig))
2366 return Context.getParenType(
2367 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2368
2369 // Might have a calling-convention attribute.
2370 if (auto *AT = dyn_cast<AttributedType>(Orig))
2371 return Context.getAttributedType(
2372 AT->getAttrKind(),
2373 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2374 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2375 ESI));
2376
2377 // Anything else must be a function type. Rebuild it with the new exception
2378 // specification.
2379 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2380 return Context.getFunctionType(
2381 Proto->getReturnType(), Proto->getParamTypes(),
2382 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2383}
2384
2385void ASTContext::adjustExceptionSpec(
2386 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2387 bool AsWritten) {
2388 // Update the type.
2389 QualType Updated =
2390 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2391 FD->setType(Updated);
2392
2393 if (!AsWritten)
2394 return;
2395
2396 // Update the type in the type source information too.
2397 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2398 // If the type and the type-as-written differ, we may need to update
2399 // the type-as-written too.
2400 if (TSInfo->getType() != FD->getType())
2401 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2402
2403 // FIXME: When we get proper type location information for exceptions,
2404 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2405 // up the TypeSourceInfo;
2406 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2407 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2408 "TypeLoc size mismatch from updating exception specification");
2409 TSInfo->overrideType(Updated);
2410 }
2411}
2412
Chris Lattnerc6395932007-06-22 20:56:16 +00002413/// getComplexType - Return the uniqued reference to the type for a complex
2414/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002415QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002416 // Unique pointers, to guarantee there is only one pointer of a particular
2417 // structure.
2418 llvm::FoldingSetNodeID ID;
2419 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002420
Craig Topper36250ad2014-05-12 05:36:57 +00002421 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002422 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2423 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002424
Chris Lattnerc6395932007-06-22 20:56:16 +00002425 // If the pointee type isn't canonical, this won't be a canonical type either,
2426 // so fill in the canonical type field.
2427 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002428 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002429 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002430
Chris Lattnerc6395932007-06-22 20:56:16 +00002431 // Get the new insert position for the node we care about.
2432 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002433 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002434 }
John McCall90d1c2d2009-09-24 23:30:46 +00002435 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002436 Types.push_back(New);
2437 ComplexTypes.InsertNode(New, InsertPos);
2438 return QualType(New, 0);
2439}
2440
Chris Lattner970e54e2006-11-12 00:37:36 +00002441/// getPointerType - Return the uniqued reference to the type for a pointer to
2442/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002443QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002444 // Unique pointers, to guarantee there is only one pointer of a particular
2445 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002446 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002447 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002448
Craig Topper36250ad2014-05-12 05:36:57 +00002449 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002450 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002451 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002452
Chris Lattner7ccecb92006-11-12 08:50:50 +00002453 // If the pointee type isn't canonical, this won't be a canonical type either,
2454 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002455 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002456 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002457 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002458
Bob Wilsonc8541f22013-03-15 17:12:43 +00002459 // Get the new insert position for the node we care about.
2460 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002461 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002462 }
John McCall90d1c2d2009-09-24 23:30:46 +00002463 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002464 Types.push_back(New);
2465 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002466 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002467}
2468
Reid Kleckner0503a872013-12-05 01:23:43 +00002469QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2470 llvm::FoldingSetNodeID ID;
2471 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002472 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002473 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2474 if (AT)
2475 return QualType(AT, 0);
2476
2477 QualType Canonical = getCanonicalType(New);
2478
2479 // Get the new insert position for the node we care about.
2480 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002481 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002482
2483 AT = new (*this, TypeAlignment)
2484 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2485 Types.push_back(AT);
2486 AdjustedTypes.InsertNode(AT, InsertPos);
2487 return QualType(AT, 0);
2488}
2489
Reid Kleckner8a365022013-06-24 17:51:48 +00002490QualType ASTContext::getDecayedType(QualType T) const {
2491 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2492
Reid Kleckner8a365022013-06-24 17:51:48 +00002493 QualType Decayed;
2494
2495 // C99 6.7.5.3p7:
2496 // A declaration of a parameter as "array of type" shall be
2497 // adjusted to "qualified pointer to type", where the type
2498 // qualifiers (if any) are those specified within the [ and ] of
2499 // the array type derivation.
2500 if (T->isArrayType())
2501 Decayed = getArrayDecayedType(T);
2502
2503 // C99 6.7.5.3p8:
2504 // A declaration of a parameter as "function returning type"
2505 // shall be adjusted to "pointer to function returning type", as
2506 // in 6.3.2.1.
2507 if (T->isFunctionType())
2508 Decayed = getPointerType(T);
2509
Reid Kleckner0503a872013-12-05 01:23:43 +00002510 llvm::FoldingSetNodeID ID;
2511 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002512 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002513 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2514 if (AT)
2515 return QualType(AT, 0);
2516
Reid Kleckner8a365022013-06-24 17:51:48 +00002517 QualType Canonical = getCanonicalType(Decayed);
2518
2519 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002520 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002521 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002522
Reid Kleckner0503a872013-12-05 01:23:43 +00002523 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2524 Types.push_back(AT);
2525 AdjustedTypes.InsertNode(AT, InsertPos);
2526 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002527}
2528
Mike Stump11289f42009-09-09 15:08:12 +00002529/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002530/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002531QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002532 assert(T->isFunctionType() && "block of function types only");
2533 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002534 // structure.
2535 llvm::FoldingSetNodeID ID;
2536 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002537
Craig Topper36250ad2014-05-12 05:36:57 +00002538 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002539 if (BlockPointerType *PT =
2540 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2541 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002542
2543 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002544 // type either so fill in the canonical type field.
2545 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002546 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002547 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002548
Steve Naroffec33ed92008-08-27 16:04:49 +00002549 // Get the new insert position for the node we care about.
2550 BlockPointerType *NewIP =
2551 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002552 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002553 }
John McCall90d1c2d2009-09-24 23:30:46 +00002554 BlockPointerType *New
2555 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002556 Types.push_back(New);
2557 BlockPointerTypes.InsertNode(New, InsertPos);
2558 return QualType(New, 0);
2559}
2560
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002561/// getLValueReferenceType - Return the uniqued reference to the type for an
2562/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002563QualType
2564ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002565 assert(getCanonicalType(T) != OverloadTy &&
2566 "Unresolved overloaded function type");
2567
Bill Wendling3708c182007-05-27 10:15:43 +00002568 // Unique pointers, to guarantee there is only one pointer of a particular
2569 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002570 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002571 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002572
Craig Topper36250ad2014-05-12 05:36:57 +00002573 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002574 if (LValueReferenceType *RT =
2575 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002576 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002577
John McCallfc93cf92009-10-22 22:37:11 +00002578 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2579
Bill Wendling3708c182007-05-27 10:15:43 +00002580 // If the referencee type isn't canonical, this won't be a canonical type
2581 // either, so fill in the canonical type field.
2582 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002583 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2584 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2585 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002586
Bill Wendling3708c182007-05-27 10:15:43 +00002587 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002588 LValueReferenceType *NewIP =
2589 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002590 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002591 }
2592
John McCall90d1c2d2009-09-24 23:30:46 +00002593 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002594 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2595 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002596 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002597 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002598
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002599 return QualType(New, 0);
2600}
2601
2602/// getRValueReferenceType - Return the uniqued reference to the type for an
2603/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002604QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002605 // Unique pointers, to guarantee there is only one pointer of a particular
2606 // structure.
2607 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002608 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002609
Craig Topper36250ad2014-05-12 05:36:57 +00002610 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002611 if (RValueReferenceType *RT =
2612 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2613 return QualType(RT, 0);
2614
John McCallfc93cf92009-10-22 22:37:11 +00002615 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2616
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002617 // If the referencee type isn't canonical, this won't be a canonical type
2618 // either, so fill in the canonical type field.
2619 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002620 if (InnerRef || !T.isCanonical()) {
2621 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2622 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002623
2624 // Get the new insert position for the node we care about.
2625 RValueReferenceType *NewIP =
2626 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002627 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002628 }
2629
John McCall90d1c2d2009-09-24 23:30:46 +00002630 RValueReferenceType *New
2631 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002632 Types.push_back(New);
2633 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002634 return QualType(New, 0);
2635}
2636
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002637/// getMemberPointerType - Return the uniqued reference to the type for a
2638/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002639QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002640 // Unique pointers, to guarantee there is only one pointer of a particular
2641 // structure.
2642 llvm::FoldingSetNodeID ID;
2643 MemberPointerType::Profile(ID, T, Cls);
2644
Craig Topper36250ad2014-05-12 05:36:57 +00002645 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002646 if (MemberPointerType *PT =
2647 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2648 return QualType(PT, 0);
2649
2650 // If the pointee or class type isn't canonical, this won't be a canonical
2651 // type either, so fill in the canonical type field.
2652 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002653 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002654 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2655
2656 // Get the new insert position for the node we care about.
2657 MemberPointerType *NewIP =
2658 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002659 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002660 }
John McCall90d1c2d2009-09-24 23:30:46 +00002661 MemberPointerType *New
2662 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002663 Types.push_back(New);
2664 MemberPointerTypes.InsertNode(New, InsertPos);
2665 return QualType(New, 0);
2666}
2667
Mike Stump11289f42009-09-09 15:08:12 +00002668/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002669/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002670QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002671 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002672 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002673 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002674 assert((EltTy->isDependentType() ||
2675 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002676 "Constant array of VLAs is illegal!");
2677
Chris Lattnere2df3f92009-05-13 04:12:56 +00002678 // Convert the array size into a canonical width matching the pointer size for
2679 // the target.
2680 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002681 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002682 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002683
Chris Lattner23b7eb62007-06-15 23:05:46 +00002684 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002685 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Craig Topper36250ad2014-05-12 05:36:57 +00002687 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002688 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002689 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002690 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002691
John McCall33ddac02011-01-19 10:06:00 +00002692 // If the element type isn't canonical or has qualifiers, this won't
2693 // be a canonical type either, so fill in the canonical type field.
2694 QualType Canon;
2695 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2696 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002697 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002698 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002699 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002700
Chris Lattner36f8e652007-01-27 08:31:04 +00002701 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002702 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002703 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002704 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002705 }
Mike Stump11289f42009-09-09 15:08:12 +00002706
John McCall90d1c2d2009-09-24 23:30:46 +00002707 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002708 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002709 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002710 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002711 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002712}
2713
John McCall06549462011-01-18 08:40:38 +00002714/// getVariableArrayDecayedType - Turns the given type, which may be
2715/// variably-modified, into the corresponding type with all the known
2716/// sizes replaced with [*].
2717QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2718 // Vastly most common case.
2719 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002720
John McCall06549462011-01-18 08:40:38 +00002721 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002722
John McCall06549462011-01-18 08:40:38 +00002723 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002724 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002725 switch (ty->getTypeClass()) {
2726#define TYPE(Class, Base)
2727#define ABSTRACT_TYPE(Class, Base)
2728#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2729#include "clang/AST/TypeNodes.def"
2730 llvm_unreachable("didn't desugar past all non-canonical types?");
2731
2732 // These types should never be variably-modified.
2733 case Type::Builtin:
2734 case Type::Complex:
2735 case Type::Vector:
2736 case Type::ExtVector:
2737 case Type::DependentSizedExtVector:
2738 case Type::ObjCObject:
2739 case Type::ObjCInterface:
2740 case Type::ObjCObjectPointer:
2741 case Type::Record:
2742 case Type::Enum:
2743 case Type::UnresolvedUsing:
2744 case Type::TypeOfExpr:
2745 case Type::TypeOf:
2746 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002747 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002748 case Type::DependentName:
2749 case Type::InjectedClassName:
2750 case Type::TemplateSpecialization:
2751 case Type::DependentTemplateSpecialization:
2752 case Type::TemplateTypeParm:
2753 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002754 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002755 case Type::PackExpansion:
2756 llvm_unreachable("type should never be variably-modified");
2757
2758 // These types can be variably-modified but should never need to
2759 // further decay.
2760 case Type::FunctionNoProto:
2761 case Type::FunctionProto:
2762 case Type::BlockPointer:
2763 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002764 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002765 return type;
2766
2767 // These types can be variably-modified. All these modifications
2768 // preserve structure except as noted by comments.
2769 // TODO: if we ever care about optimizing VLAs, there are no-op
2770 // optimizations available here.
2771 case Type::Pointer:
2772 result = getPointerType(getVariableArrayDecayedType(
2773 cast<PointerType>(ty)->getPointeeType()));
2774 break;
2775
2776 case Type::LValueReference: {
2777 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2778 result = getLValueReferenceType(
2779 getVariableArrayDecayedType(lv->getPointeeType()),
2780 lv->isSpelledAsLValue());
2781 break;
2782 }
2783
2784 case Type::RValueReference: {
2785 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2786 result = getRValueReferenceType(
2787 getVariableArrayDecayedType(lv->getPointeeType()));
2788 break;
2789 }
2790
Eli Friedman0dfb8892011-10-06 23:00:33 +00002791 case Type::Atomic: {
2792 const AtomicType *at = cast<AtomicType>(ty);
2793 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2794 break;
2795 }
2796
John McCall06549462011-01-18 08:40:38 +00002797 case Type::ConstantArray: {
2798 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2799 result = getConstantArrayType(
2800 getVariableArrayDecayedType(cat->getElementType()),
2801 cat->getSize(),
2802 cat->getSizeModifier(),
2803 cat->getIndexTypeCVRQualifiers());
2804 break;
2805 }
2806
2807 case Type::DependentSizedArray: {
2808 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2809 result = getDependentSizedArrayType(
2810 getVariableArrayDecayedType(dat->getElementType()),
2811 dat->getSizeExpr(),
2812 dat->getSizeModifier(),
2813 dat->getIndexTypeCVRQualifiers(),
2814 dat->getBracketsRange());
2815 break;
2816 }
2817
2818 // Turn incomplete types into [*] types.
2819 case Type::IncompleteArray: {
2820 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2821 result = getVariableArrayType(
2822 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002823 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002824 ArrayType::Normal,
2825 iat->getIndexTypeCVRQualifiers(),
2826 SourceRange());
2827 break;
2828 }
2829
2830 // Turn VLA types into [*] types.
2831 case Type::VariableArray: {
2832 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2833 result = getVariableArrayType(
2834 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002835 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002836 ArrayType::Star,
2837 vat->getIndexTypeCVRQualifiers(),
2838 vat->getBracketsRange());
2839 break;
2840 }
2841 }
2842
2843 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002844 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002845}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002846
Steve Naroffcadebd02007-08-30 18:14:25 +00002847/// getVariableArrayType - Returns a non-unique reference to the type for a
2848/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002849QualType ASTContext::getVariableArrayType(QualType EltTy,
2850 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002851 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002852 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002853 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002854 // Since we don't unique expressions, it isn't possible to unique VLA's
2855 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002856 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002857
John McCall33ddac02011-01-19 10:06:00 +00002858 // Be sure to pull qualifiers off the element type.
2859 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2860 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002861 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002862 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002863 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002864 }
2865
John McCall90d1c2d2009-09-24 23:30:46 +00002866 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002867 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002868
2869 VariableArrayTypes.push_back(New);
2870 Types.push_back(New);
2871 return QualType(New, 0);
2872}
2873
Douglas Gregor4619e432008-12-05 23:32:09 +00002874/// getDependentSizedArrayType - Returns a non-unique reference to
2875/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002876/// type.
John McCall33ddac02011-01-19 10:06:00 +00002877QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2878 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002879 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002880 unsigned elementTypeQuals,
2881 SourceRange brackets) const {
2882 assert((!numElements || numElements->isTypeDependent() ||
2883 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002884 "Size must be type- or value-dependent!");
2885
John McCall33ddac02011-01-19 10:06:00 +00002886 // Dependently-sized array types that do not have a specified number
2887 // of elements will have their sizes deduced from a dependent
2888 // initializer. We do no canonicalization here at all, which is okay
2889 // because they can't be used in most locations.
2890 if (!numElements) {
2891 DependentSizedArrayType *newType
2892 = new (*this, TypeAlignment)
2893 DependentSizedArrayType(*this, elementType, QualType(),
2894 numElements, ASM, elementTypeQuals,
2895 brackets);
2896 Types.push_back(newType);
2897 return QualType(newType, 0);
2898 }
2899
2900 // Otherwise, we actually build a new type every time, but we
2901 // also build a canonical type.
2902
2903 SplitQualType canonElementType = getCanonicalType(elementType).split();
2904
Craig Topper36250ad2014-05-12 05:36:57 +00002905 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002906 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002907 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002908 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002909 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002910
John McCall33ddac02011-01-19 10:06:00 +00002911 // Look for an existing type with these properties.
2912 DependentSizedArrayType *canonTy =
2913 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002914
John McCall33ddac02011-01-19 10:06:00 +00002915 // If we don't have one, build one.
2916 if (!canonTy) {
2917 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002918 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002919 QualType(), numElements, ASM, elementTypeQuals,
2920 brackets);
2921 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2922 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002923 }
2924
John McCall33ddac02011-01-19 10:06:00 +00002925 // Apply qualifiers from the element type to the array.
2926 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002927 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002928
David Majnemer16a74702015-07-24 05:54:19 +00002929 // If we didn't need extra canonicalization for the element type or the size
2930 // expression, then just use that as our result.
2931 if (QualType(canonElementType.Ty, 0) == elementType &&
2932 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002933 return canon;
2934
2935 // Otherwise, we need to build a type which follows the spelling
2936 // of the element type.
2937 DependentSizedArrayType *sugaredType
2938 = new (*this, TypeAlignment)
2939 DependentSizedArrayType(*this, elementType, canon, numElements,
2940 ASM, elementTypeQuals, brackets);
2941 Types.push_back(sugaredType);
2942 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002943}
2944
John McCall33ddac02011-01-19 10:06:00 +00002945QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002946 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002947 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002948 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002949 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002950
Craig Topper36250ad2014-05-12 05:36:57 +00002951 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002952 if (IncompleteArrayType *iat =
2953 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2954 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002955
2956 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002957 // either, so fill in the canonical type field. We also have to pull
2958 // qualifiers off the element type.
2959 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002960
John McCall33ddac02011-01-19 10:06:00 +00002961 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2962 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002963 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002964 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002965 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002966
2967 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002968 IncompleteArrayType *existing =
2969 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2970 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002971 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002972
John McCall33ddac02011-01-19 10:06:00 +00002973 IncompleteArrayType *newType = new (*this, TypeAlignment)
2974 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002975
John McCall33ddac02011-01-19 10:06:00 +00002976 IncompleteArrayTypes.InsertNode(newType, insertPos);
2977 Types.push_back(newType);
2978 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002979}
2980
Steve Naroff91fcddb2007-07-18 18:00:27 +00002981/// getVectorType - Return the unique reference to a vector type of
2982/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002983QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002984 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002985 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002986
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002987 // Check if we've already instantiated a vector of this type.
2988 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002989 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002990
Craig Topper36250ad2014-05-12 05:36:57 +00002991 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002992 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2993 return QualType(VTP, 0);
2994
2995 // If the element type isn't canonical, this won't be a canonical type either,
2996 // so fill in the canonical type field.
2997 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002998 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002999 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003000
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003001 // Get the new insert position for the node we care about.
3002 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003003 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003004 }
John McCall90d1c2d2009-09-24 23:30:46 +00003005 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003006 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003007 VectorTypes.InsertNode(New, InsertPos);
3008 Types.push_back(New);
3009 return QualType(New, 0);
3010}
3011
Nate Begemance4d7fc2008-04-18 23:10:10 +00003012/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003013/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003014QualType
3015ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003016 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003017
Steve Naroff91fcddb2007-07-18 18:00:27 +00003018 // Check if we've already instantiated a vector of this type.
3019 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003020 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003021 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003022 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003023 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3024 return QualType(VTP, 0);
3025
3026 // If the element type isn't canonical, this won't be a canonical type either,
3027 // so fill in the canonical type field.
3028 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003029 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003030 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003031
Steve Naroff91fcddb2007-07-18 18:00:27 +00003032 // Get the new insert position for the node we care about.
3033 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003034 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003035 }
John McCall90d1c2d2009-09-24 23:30:46 +00003036 ExtVectorType *New = new (*this, TypeAlignment)
3037 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003038 VectorTypes.InsertNode(New, InsertPos);
3039 Types.push_back(New);
3040 return QualType(New, 0);
3041}
3042
Jay Foad39c79802011-01-12 09:06:06 +00003043QualType
3044ASTContext::getDependentSizedExtVectorType(QualType vecType,
3045 Expr *SizeExpr,
3046 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003047 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003048 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003049 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003050
Craig Topper36250ad2014-05-12 05:36:57 +00003051 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003052 DependentSizedExtVectorType *Canon
3053 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3054 DependentSizedExtVectorType *New;
3055 if (Canon) {
3056 // We already have a canonical version of this array type; use it as
3057 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003058 New = new (*this, TypeAlignment)
3059 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3060 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003061 } else {
3062 QualType CanonVecTy = getCanonicalType(vecType);
3063 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003064 New = new (*this, TypeAlignment)
3065 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3066 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003067
3068 DependentSizedExtVectorType *CanonCheck
3069 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3070 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3071 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003072 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3073 } else {
3074 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3075 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003076 New = new (*this, TypeAlignment)
3077 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003078 }
3079 }
Mike Stump11289f42009-09-09 15:08:12 +00003080
Douglas Gregor758a8692009-06-17 21:51:59 +00003081 Types.push_back(New);
3082 return QualType(New, 0);
3083}
3084
John McCall18afab72016-03-01 00:49:02 +00003085/// \brief Determine whether \p T is canonical as the result type of a function.
3086static bool isCanonicalResultType(QualType T) {
3087 return T.isCanonical() &&
3088 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3089 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3090}
3091
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003092/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003093///
Jay Foad39c79802011-01-12 09:06:06 +00003094QualType
3095ASTContext::getFunctionNoProtoType(QualType ResultTy,
3096 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003097 // Unique functions, to guarantee there is only one function of a particular
3098 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003099 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003100 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003101
Craig Topper36250ad2014-05-12 05:36:57 +00003102 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003103 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003104 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003105 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003106
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003107 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003108 if (!isCanonicalResultType(ResultTy)) {
3109 Canonical =
3110 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003111
Chris Lattner47955de2007-01-27 08:37:20 +00003112 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003113 FunctionNoProtoType *NewIP =
3114 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003115 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003116 }
Mike Stump11289f42009-09-09 15:08:12 +00003117
John McCall90d1c2d2009-09-24 23:30:46 +00003118 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003119 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003120 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003121 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003122 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003123}
3124
Douglas Gregora602a152015-10-01 20:20:47 +00003125CanQualType
3126ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3127 CanQualType CanResultType = getCanonicalType(ResultType);
3128
3129 // Canonical result types do not have ARC lifetime qualifiers.
3130 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3131 Qualifiers Qs = CanResultType.getQualifiers();
3132 Qs.removeObjCLifetime();
3133 return CanQualType::CreateUnsafe(
3134 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3135 }
3136
3137 return CanResultType;
3138}
3139
Richard Smith3c4f8d22016-10-16 17:54:23 +00003140static bool isCanonicalExceptionSpecification(
3141 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3142 if (ESI.Type == EST_None)
3143 return true;
3144 if (!NoexceptInType)
3145 return false;
3146
3147 // C++17 onwards: exception specification is part of the type, as a simple
3148 // boolean "can this function type throw".
3149 if (ESI.Type == EST_BasicNoexcept)
3150 return true;
3151
3152 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003153 // expansions (so we can't tell whether it's non-throwing) and all its
3154 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003155 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003156 bool AnyPackExpansions = false;
3157 for (QualType ET : ESI.Exceptions) {
3158 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003159 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003160 if (ET->getAs<PackExpansionType>())
3161 AnyPackExpansions = true;
3162 }
3163 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003164 }
3165
Richard Smith2a2cda52016-10-18 19:29:18 +00003166 // A noexcept(expr) specification is (possibly) canonical if expr is
3167 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003168 if (ESI.Type == EST_ComputedNoexcept)
3169 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3170
3171 return false;
3172}
3173
Richard Smith304b1242016-10-18 20:13:25 +00003174QualType ASTContext::getFunctionTypeInternal(
3175 QualType ResultTy, ArrayRef<QualType> ArgArray,
3176 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003177 size_t NumArgs = ArgArray.size();
3178
Richard Smith2a2cda52016-10-18 19:29:18 +00003179 // Unique functions, to guarantee there is only one function of a particular
3180 // structure.
3181 llvm::FoldingSetNodeID ID;
3182 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3183 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003184
Richard Smith2a2cda52016-10-18 19:29:18 +00003185 QualType Canonical;
3186 bool Unique = false;
3187
3188 void *InsertPos = nullptr;
3189 if (FunctionProtoType *FPT =
3190 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3191 QualType Existing = QualType(FPT, 0);
3192
3193 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3194 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003195 // noexcept expression, or we're just looking for a canonical type.
3196 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003197 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003198 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003199 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3200 return Existing;
3201
3202 // We need a new type sugar node for this one, to hold the new noexcept
3203 // expression. We do no canonicalization here, but that's OK since we don't
3204 // expect to see the same noexcept expression much more than once.
3205 Canonical = getCanonicalType(Existing);
3206 Unique = true;
3207 }
3208
3209 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003210 bool IsCanonicalExceptionSpec =
3211 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3212
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003213 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003214 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003215 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003216 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003217 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003218 isCanonical = false;
3219
Richard Smith304b1242016-10-18 20:13:25 +00003220 if (OnlyWantCanonical)
3221 assert(isCanonical &&
3222 "given non-canonical parameters constructing canonical type");
3223
Richard Smith2a2cda52016-10-18 19:29:18 +00003224 // If this type isn't canonical, get the canonical version of it if we don't
3225 // already have it. The exception spec is only partially part of the
3226 // canonical type, and only in C++17 onwards.
3227 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003228 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003229 CanonicalArgs.reserve(NumArgs);
3230 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003231 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003232
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003233 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003234 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003235 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003236
3237 if (IsCanonicalExceptionSpec) {
3238 // Exception spec is already OK.
3239 } else if (NoexceptInType) {
3240 switch (EPI.ExceptionSpec.Type) {
3241 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3242 // We don't know yet. It shouldn't matter what we pick here; no-one
3243 // should ever look at this.
3244 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003245 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003246 CanonicalEPI.ExceptionSpec.Type = EST_None;
3247 break;
3248
Richard Smith2a2cda52016-10-18 19:29:18 +00003249 // A dynamic exception specification is almost always "not noexcept",
3250 // with the exception that a pack expansion might expand to no types.
3251 case EST_Dynamic: {
3252 bool AnyPacks = false;
3253 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3254 if (ET->getAs<PackExpansionType>())
3255 AnyPacks = true;
3256 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3257 }
3258 if (!AnyPacks)
3259 CanonicalEPI.ExceptionSpec.Type = EST_None;
3260 else {
3261 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3262 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3263 }
3264 break;
3265 }
3266
Richard Smith3c4f8d22016-10-16 17:54:23 +00003267 case EST_DynamicNone: case EST_BasicNoexcept:
3268 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3269 break;
3270
3271 case EST_ComputedNoexcept:
3272 llvm::APSInt Value(1);
3273 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3274 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3275 /*IsEvaluated*/false)) {
3276 // This noexcept specification is invalid.
3277 // FIXME: Should this be able to happen?
3278 CanonicalEPI.ExceptionSpec.Type = EST_None;
3279 break;
3280 }
3281
3282 CanonicalEPI.ExceptionSpec.Type =
3283 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3284 break;
3285 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003286 } else {
3287 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3288 }
John McCalldb40c7f2010-12-14 08:05:40 +00003289
Douglas Gregora602a152015-10-01 20:20:47 +00003290 // Adjust the canonical function result type.
3291 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003292 Canonical =
3293 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003294
Chris Lattnerfd4de792007-01-27 01:15:32 +00003295 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003296 FunctionProtoType *NewIP =
3297 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003298 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003299 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003300
John McCall31168b02011-06-15 23:02:42 +00003301 // FunctionProtoType objects are allocated with extra bytes after
3302 // them for three variable size arrays at the end:
3303 // - parameter types
3304 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003305 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003306 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003307 // expression, or information used to resolve the exception
3308 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003309 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003310 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003311
Richard Smith8acb4282014-07-31 21:57:55 +00003312 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3313 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3314 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003315 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003316 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003317 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003318 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003319 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003320 }
John McCall18afab72016-03-01 00:49:02 +00003321
3322 // Put the ExtParameterInfos last. If all were equal, it would make
3323 // more sense to put these before the exception specification, because
3324 // it's much easier to skip past them compared to the elaborate switch
3325 // required to skip the exception specification. However, all is not
3326 // equal; ExtParameterInfos are used to model very uncommon features,
3327 // and it's better not to burden the more common paths.
3328 if (EPI.ExtParameterInfos) {
3329 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3330 }
John McCall31168b02011-06-15 23:02:42 +00003331
John McCalldb40c7f2010-12-14 08:05:40 +00003332 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003333 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003334 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003335 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003336 if (!Unique)
3337 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003338 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003339}
Chris Lattneref51c202006-11-10 07:17:23 +00003340
Xiuli Pan9c14e282016-01-09 12:53:17 +00003341/// Return pipe type for the specified type.
3342QualType ASTContext::getPipeType(QualType T) const {
3343 llvm::FoldingSetNodeID ID;
3344 PipeType::Profile(ID, T);
3345
3346 void *InsertPos = 0;
3347 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3348 return QualType(PT, 0);
3349
3350 // If the pipe element type isn't canonical, this won't be a canonical type
3351 // either, so fill in the canonical type field.
3352 QualType Canonical;
3353 if (!T.isCanonical()) {
3354 Canonical = getPipeType(getCanonicalType(T));
3355
3356 // Get the new insert position for the node we care about.
3357 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3358 assert(!NewIP && "Shouldn't be in the map!");
3359 (void)NewIP;
3360 }
3361 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3362 Types.push_back(New);
3363 PipeTypes.InsertNode(New, InsertPos);
3364 return QualType(New, 0);
3365}
3366
John McCalle78aac42010-03-10 03:28:59 +00003367#ifndef NDEBUG
3368static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3369 if (!isa<CXXRecordDecl>(D)) return false;
3370 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3371 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3372 return true;
3373 if (RD->getDescribedClassTemplate() &&
3374 !isa<ClassTemplateSpecializationDecl>(RD))
3375 return true;
3376 return false;
3377}
3378#endif
3379
3380/// getInjectedClassNameType - Return the unique reference to the
3381/// injected class name type for the specified templated declaration.
3382QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003383 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003384 assert(NeedsInjectedClassNameType(Decl));
3385 if (Decl->TypeForDecl) {
3386 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003387 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003388 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3389 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3390 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3391 } else {
John McCall424cec92011-01-19 06:33:43 +00003392 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003393 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003394 Decl->TypeForDecl = newType;
3395 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003396 }
3397 return QualType(Decl->TypeForDecl, 0);
3398}
3399
Douglas Gregor83a586e2008-04-13 21:07:44 +00003400/// getTypeDeclType - Return the unique reference to the type for the
3401/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003402QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003403 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003404 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003405
Richard Smithdda56e42011-04-15 14:24:37 +00003406 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003407 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003408
John McCall96f0b5f2010-03-10 06:48:02 +00003409 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3410 "Template type parameter types are always available.");
3411
John McCall81e38502010-02-16 03:57:14 +00003412 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003413 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003414 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003415 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003416 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003417 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003418 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003419 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003420 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003421 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3422 Decl->TypeForDecl = newType;
3423 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003424 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003425 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003426
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003427 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003428}
3429
Chris Lattner32d920b2007-01-26 02:01:53 +00003430/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003431/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003432QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003433ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3434 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003435 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003436
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003437 if (Canonical.isNull())
3438 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003439 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003440 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003441 Decl->TypeForDecl = newType;
3442 Types.push_back(newType);
3443 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003444}
3445
Jay Foad39c79802011-01-12 09:06:06 +00003446QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003447 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3448
Douglas Gregorec9fd132012-01-14 16:38:05 +00003449 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003450 if (PrevDecl->TypeForDecl)
3451 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3452
John McCall424cec92011-01-19 06:33:43 +00003453 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3454 Decl->TypeForDecl = newType;
3455 Types.push_back(newType);
3456 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003457}
3458
Jay Foad39c79802011-01-12 09:06:06 +00003459QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003460 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3461
Douglas Gregorec9fd132012-01-14 16:38:05 +00003462 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003463 if (PrevDecl->TypeForDecl)
3464 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3465
John McCall424cec92011-01-19 06:33:43 +00003466 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3467 Decl->TypeForDecl = newType;
3468 Types.push_back(newType);
3469 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003470}
3471
John McCall81904512011-01-06 01:58:22 +00003472QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3473 QualType modifiedType,
3474 QualType equivalentType) {
3475 llvm::FoldingSetNodeID id;
3476 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3477
Craig Topper36250ad2014-05-12 05:36:57 +00003478 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003479 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3480 if (type) return QualType(type, 0);
3481
3482 QualType canon = getCanonicalType(equivalentType);
3483 type = new (*this, TypeAlignment)
3484 AttributedType(canon, attrKind, modifiedType, equivalentType);
3485
3486 Types.push_back(type);
3487 AttributedTypes.InsertNode(type, insertPos);
3488
3489 return QualType(type, 0);
3490}
3491
John McCallcebee162009-10-18 09:09:24 +00003492/// \brief Retrieve a substitution-result type.
3493QualType
3494ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003495 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003496 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003497 && "replacement types must always be canonical");
3498
3499 llvm::FoldingSetNodeID ID;
3500 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003501 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003502 SubstTemplateTypeParmType *SubstParm
3503 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3504
3505 if (!SubstParm) {
3506 SubstParm = new (*this, TypeAlignment)
3507 SubstTemplateTypeParmType(Parm, Replacement);
3508 Types.push_back(SubstParm);
3509 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3510 }
3511
3512 return QualType(SubstParm, 0);
3513}
3514
Douglas Gregorada4b792011-01-14 02:55:32 +00003515/// \brief Retrieve a
3516QualType ASTContext::getSubstTemplateTypeParmPackType(
3517 const TemplateTypeParmType *Parm,
3518 const TemplateArgument &ArgPack) {
3519#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003520 for (const auto &P : ArgPack.pack_elements()) {
3521 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3522 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003523 }
3524#endif
3525
3526 llvm::FoldingSetNodeID ID;
3527 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003528 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003529 if (SubstTemplateTypeParmPackType *SubstParm
3530 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3531 return QualType(SubstParm, 0);
3532
3533 QualType Canon;
3534 if (!Parm->isCanonicalUnqualified()) {
3535 Canon = getCanonicalType(QualType(Parm, 0));
3536 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3537 ArgPack);
3538 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3539 }
3540
3541 SubstTemplateTypeParmPackType *SubstParm
3542 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3543 ArgPack);
3544 Types.push_back(SubstParm);
3545 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3546 return QualType(SubstParm, 0);
3547}
3548
Douglas Gregoreff93e02009-02-05 23:33:38 +00003549/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003550/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003551/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003552QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003553 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003554 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003555 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003556 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003557 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003558 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003559 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3560
3561 if (TypeParm)
3562 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003563
Chandler Carruth08836322011-05-01 00:51:33 +00003564 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003565 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003566 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003567
3568 TemplateTypeParmType *TypeCheck
3569 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3570 assert(!TypeCheck && "Template type parameter canonical type broken");
3571 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003572 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003573 TypeParm = new (*this, TypeAlignment)
3574 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003575
3576 Types.push_back(TypeParm);
3577 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3578
3579 return QualType(TypeParm, 0);
3580}
3581
John McCalle78aac42010-03-10 03:28:59 +00003582TypeSourceInfo *
3583ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3584 SourceLocation NameLoc,
3585 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003586 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003587 assert(!Name.getAsDependentTemplateName() &&
3588 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003589 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003590
3591 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003592 TemplateSpecializationTypeLoc TL =
3593 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003594 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003595 TL.setTemplateNameLoc(NameLoc);
3596 TL.setLAngleLoc(Args.getLAngleLoc());
3597 TL.setRAngleLoc(Args.getRAngleLoc());
3598 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3599 TL.setArgLocInfo(i, Args[i].getLocInfo());
3600 return DI;
3601}
3602
Mike Stump11289f42009-09-09 15:08:12 +00003603QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003604ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003605 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003606 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003607 assert(!Template.getAsDependentTemplateName() &&
3608 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003609
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003610 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003611 ArgVec.reserve(Args.size());
3612 for (const TemplateArgumentLoc &Arg : Args.arguments())
3613 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003614
David Majnemer6fbeee32016-07-07 04:43:07 +00003615 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003616}
3617
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003618#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003619static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3620 for (const TemplateArgument &Arg : Args)
3621 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003622 return true;
3623
3624 return true;
3625}
3626#endif
3627
John McCall0ad16662009-10-29 08:12:44 +00003628QualType
3629ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003630 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003631 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003632 assert(!Template.getAsDependentTemplateName() &&
3633 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003634 // Look through qualified template names.
3635 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3636 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003637
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003638 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003639 Template.getAsTemplateDecl() &&
3640 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003641 QualType CanonType;
3642 if (!Underlying.isNull())
3643 CanonType = getCanonicalType(Underlying);
3644 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003645 // We can get here with an alias template when the specialization contains
3646 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003647 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003648 "Caller must compute aliased type");
3649 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003650 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003651 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003652
Douglas Gregora8e02e72009-07-28 23:00:59 +00003653 // Allocate the (non-canonical) template specialization type, but don't
3654 // try to unique it: these types typically have location information that
3655 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003656 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003657 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003658 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003659 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003660 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003661 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003662 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003663
Douglas Gregor8bf42052009-02-09 18:46:07 +00003664 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003665 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003666}
3667
David Majnemer6fbeee32016-07-07 04:43:07 +00003668QualType ASTContext::getCanonicalTemplateSpecializationType(
3669 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003670 assert(!Template.getAsDependentTemplateName() &&
3671 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003672
Douglas Gregore29139c2011-03-03 17:04:51 +00003673 // Look through qualified template names.
3674 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3675 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003676
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003677 // Build the canonical template specialization type.
3678 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003679 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003680 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003681 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003682 for (const TemplateArgument &Arg : Args)
3683 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003684
3685 // Determine whether this canonical template specialization type already
3686 // exists.
3687 llvm::FoldingSetNodeID ID;
3688 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003689 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003690
Craig Topper36250ad2014-05-12 05:36:57 +00003691 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003692 TemplateSpecializationType *Spec
3693 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3694
3695 if (!Spec) {
3696 // Allocate a new canonical template specialization type.
3697 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3698 sizeof(TemplateArgument) * NumArgs),
3699 TypeAlignment);
3700 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003701 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003702 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003703 Types.push_back(Spec);
3704 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3705 }
3706
3707 assert(Spec->isDependentType() &&
3708 "Non-dependent template-id type must have a canonical type");
3709 return QualType(Spec, 0);
3710}
3711
3712QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003713ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3714 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003715 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003716 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003717 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003718
Craig Topper36250ad2014-05-12 05:36:57 +00003719 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003720 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003721 if (T)
3722 return QualType(T, 0);
3723
Douglas Gregorc42075a2010-02-04 18:10:26 +00003724 QualType Canon = NamedType;
3725 if (!Canon.isCanonical()) {
3726 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003727 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3728 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003729 (void)CheckT;
3730 }
3731
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003732 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003733 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003734 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003735 return QualType(T, 0);
3736}
3737
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003738QualType
Jay Foad39c79802011-01-12 09:06:06 +00003739ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003740 llvm::FoldingSetNodeID ID;
3741 ParenType::Profile(ID, InnerType);
3742
Craig Topper36250ad2014-05-12 05:36:57 +00003743 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003744 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3745 if (T)
3746 return QualType(T, 0);
3747
3748 QualType Canon = InnerType;
3749 if (!Canon.isCanonical()) {
3750 Canon = getCanonicalType(InnerType);
3751 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3752 assert(!CheckT && "Paren canonical type broken");
3753 (void)CheckT;
3754 }
3755
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003756 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003757 Types.push_back(T);
3758 ParenTypes.InsertNode(T, InsertPos);
3759 return QualType(T, 0);
3760}
3761
Douglas Gregor02085352010-03-31 20:19:30 +00003762QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3763 NestedNameSpecifier *NNS,
3764 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003765 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003766 if (Canon.isNull()) {
3767 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003768 ElaboratedTypeKeyword CanonKeyword = Keyword;
3769 if (Keyword == ETK_None)
3770 CanonKeyword = ETK_Typename;
3771
3772 if (CanonNNS != NNS || CanonKeyword != Keyword)
3773 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003774 }
3775
3776 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003777 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003778
Craig Topper36250ad2014-05-12 05:36:57 +00003779 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003780 DependentNameType *T
3781 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003782 if (T)
3783 return QualType(T, 0);
3784
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003785 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003786 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003787 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003788 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003789}
3790
Mike Stump11289f42009-09-09 15:08:12 +00003791QualType
John McCallc392f372010-06-11 00:33:02 +00003792ASTContext::getDependentTemplateSpecializationType(
3793 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003794 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003795 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003796 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003797 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003798 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003799 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3800 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003801 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003802}
3803
3804QualType
3805ASTContext::getDependentTemplateSpecializationType(
3806 ElaboratedTypeKeyword Keyword,
3807 NestedNameSpecifier *NNS,
3808 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003809 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003810 assert((!NNS || NNS->isDependent()) &&
3811 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003812
Douglas Gregorc42075a2010-02-04 18:10:26 +00003813 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003814 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003815 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003816
Craig Topper36250ad2014-05-12 05:36:57 +00003817 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003818 DependentTemplateSpecializationType *T
3819 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003820 if (T)
3821 return QualType(T, 0);
3822
John McCallc392f372010-06-11 00:33:02 +00003823 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003824
John McCallc392f372010-06-11 00:33:02 +00003825 ElaboratedTypeKeyword CanonKeyword = Keyword;
3826 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3827
3828 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003829 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003830 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003831 for (unsigned I = 0; I != NumArgs; ++I) {
3832 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3833 if (!CanonArgs[I].structurallyEquals(Args[I]))
3834 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003835 }
3836
John McCallc392f372010-06-11 00:33:02 +00003837 QualType Canon;
3838 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3839 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003840 Name,
3841 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003842
3843 // Find the insert position again.
3844 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3845 }
3846
3847 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3848 sizeof(TemplateArgument) * NumArgs),
3849 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003850 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003851 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003852 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003853 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003854 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003855}
3856
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003857QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003858 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003859 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003860 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003861
3862 assert(Pattern->containsUnexpandedParameterPack() &&
3863 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003864 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003865 PackExpansionType *T
3866 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3867 if (T)
3868 return QualType(T, 0);
3869
3870 QualType Canon;
3871 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003872 Canon = getCanonicalType(Pattern);
3873 // The canonical type might not contain an unexpanded parameter pack, if it
3874 // contains an alias template specialization which ignores one of its
3875 // parameters.
3876 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003877 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003878
Richard Smith68eea502012-07-16 00:20:35 +00003879 // Find the insert position again, in case we inserted an element into
3880 // PackExpansionTypes and invalidated our insert position.
3881 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3882 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003883 }
3884
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003885 T = new (*this, TypeAlignment)
3886 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003887 Types.push_back(T);
3888 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003889 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003890}
3891
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003892/// CmpProtocolNames - Comparison predicate for sorting protocols
3893/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003894static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3895 ObjCProtocolDecl *const *RHS) {
3896 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003897}
3898
Craig Topper1f26d5b2016-01-03 19:43:23 +00003899static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3900 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003901
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003902 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3903 return false;
3904
Craig Topper1f26d5b2016-01-03 19:43:23 +00003905 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003906 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003907 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003908 return false;
3909 return true;
3910}
3911
Craig Topper6a8c1512015-10-22 01:56:18 +00003912static void
3913SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003914 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003915 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003916
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003917 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003918 for (ObjCProtocolDecl *&P : Protocols)
3919 P = P->getCanonicalDecl();
3920
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003921 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003922 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3923 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003924}
3925
John McCall8b07ec22010-05-15 11:32:37 +00003926QualType ASTContext::getObjCObjectType(QualType BaseType,
3927 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003928 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003929 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003930 llvm::makeArrayRef(Protocols, NumProtocols),
3931 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003932}
3933
3934QualType ASTContext::getObjCObjectType(
3935 QualType baseType,
3936 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003937 ArrayRef<ObjCProtocolDecl *> protocols,
3938 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003939 // If the base type is an interface and there aren't any protocols or
3940 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003941 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3942 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003943 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003944
3945 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003946 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003947 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003948 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003949 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3950 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003951
Douglas Gregore9d95f12015-07-07 03:57:35 +00003952 // Determine the type arguments to be used for canonicalization,
3953 // which may be explicitly specified here or written on the base
3954 // type.
3955 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3956 if (effectiveTypeArgs.empty()) {
3957 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3958 effectiveTypeArgs = baseObject->getTypeArgs();
3959 }
John McCallfc93cf92009-10-22 22:37:11 +00003960
Douglas Gregore9d95f12015-07-07 03:57:35 +00003961 // Build the canonical type, which has the canonical base type and a
3962 // sorted-and-uniqued list of protocols and the type arguments
3963 // canonicalized.
3964 QualType canonical;
3965 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3966 effectiveTypeArgs.end(),
3967 [&](QualType type) {
3968 return type.isCanonical();
3969 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003970 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003971 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3972 // Determine the canonical type arguments.
3973 ArrayRef<QualType> canonTypeArgs;
3974 SmallVector<QualType, 4> canonTypeArgsVec;
3975 if (!typeArgsAreCanonical) {
3976 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3977 for (auto typeArg : effectiveTypeArgs)
3978 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3979 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003980 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003981 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003982 }
3983
Douglas Gregore9d95f12015-07-07 03:57:35 +00003984 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3985 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3986 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003987 canonProtocolsVec.append(protocols.begin(), protocols.end());
3988 SortAndUniqueProtocols(canonProtocolsVec);
3989 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003990 } else {
3991 canonProtocols = protocols;
3992 }
3993
3994 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003995 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003996
John McCallfc93cf92009-10-22 22:37:11 +00003997 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003998 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3999 }
4000
Douglas Gregore9d95f12015-07-07 03:57:35 +00004001 unsigned size = sizeof(ObjCObjectTypeImpl);
4002 size += typeArgs.size() * sizeof(QualType);
4003 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4004 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004005 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004006 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4007 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004008
4009 Types.push_back(T);
4010 ObjCObjectTypes.InsertNode(T, InsertPos);
4011 return QualType(T, 0);
4012}
4013
Manman Ren3569eb52016-09-13 17:03:12 +00004014/// Apply Objective-C protocol qualifiers to the given type.
4015/// If this is for the canonical type of a type parameter, we can apply
4016/// protocol qualifiers on the ObjCObjectPointerType.
4017QualType
4018ASTContext::applyObjCProtocolQualifiers(QualType type,
4019 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4020 bool allowOnPointerType) const {
4021 hasError = false;
4022
Manman Renc5705ba2016-09-13 17:41:05 +00004023 if (const ObjCTypeParamType *objT =
4024 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4025 return getObjCTypeParamType(objT->getDecl(), protocols);
4026 }
4027
Manman Ren3569eb52016-09-13 17:03:12 +00004028 // Apply protocol qualifiers to ObjCObjectPointerType.
4029 if (allowOnPointerType) {
4030 if (const ObjCObjectPointerType *objPtr =
4031 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4032 const ObjCObjectType *objT = objPtr->getObjectType();
4033 // Merge protocol lists and construct ObjCObjectType.
4034 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4035 protocolsVec.append(objT->qual_begin(),
4036 objT->qual_end());
4037 protocolsVec.append(protocols.begin(), protocols.end());
4038 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4039 type = getObjCObjectType(
4040 objT->getBaseType(),
4041 objT->getTypeArgsAsWritten(),
4042 protocols,
4043 objT->isKindOfTypeAsWritten());
4044 return getObjCObjectPointerType(type);
4045 }
4046 }
4047
4048 // Apply protocol qualifiers to ObjCObjectType.
4049 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4050 // FIXME: Check for protocols to which the class type is already
4051 // known to conform.
4052
4053 return getObjCObjectType(objT->getBaseType(),
4054 objT->getTypeArgsAsWritten(),
4055 protocols,
4056 objT->isKindOfTypeAsWritten());
4057 }
4058
4059 // If the canonical type is ObjCObjectType, ...
4060 if (type->isObjCObjectType()) {
4061 // Silently overwrite any existing protocol qualifiers.
4062 // TODO: determine whether that's the right thing to do.
4063
4064 // FIXME: Check for protocols to which the class type is already
4065 // known to conform.
4066 return getObjCObjectType(type, { }, protocols, false);
4067 }
4068
4069 // id<protocol-list>
4070 if (type->isObjCIdType()) {
4071 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4072 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4073 objPtr->isKindOfType());
4074 return getObjCObjectPointerType(type);
4075 }
4076
4077 // Class<protocol-list>
4078 if (type->isObjCClassType()) {
4079 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4080 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4081 objPtr->isKindOfType());
4082 return getObjCObjectPointerType(type);
4083 }
4084
4085 hasError = true;
4086 return type;
4087}
4088
Manman Rene6be26c2016-09-13 17:25:08 +00004089QualType
4090ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4091 ArrayRef<ObjCProtocolDecl *> protocols,
4092 QualType Canonical) const {
4093 // Look in the folding set for an existing type.
4094 llvm::FoldingSetNodeID ID;
4095 ObjCTypeParamType::Profile(ID, Decl, protocols);
4096 void *InsertPos = nullptr;
4097 if (ObjCTypeParamType *TypeParam =
4098 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4099 return QualType(TypeParam, 0);
4100
4101 if (Canonical.isNull()) {
4102 // We canonicalize to the underlying type.
4103 Canonical = getCanonicalType(Decl->getUnderlyingType());
4104 if (!protocols.empty()) {
4105 // Apply the protocol qualifers.
4106 bool hasError;
4107 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4108 true/*allowOnPointerType*/);
4109 assert(!hasError && "Error when apply protocol qualifier to bound type");
4110 }
4111 }
4112
4113 unsigned size = sizeof(ObjCTypeParamType);
4114 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4115 void *mem = Allocate(size, TypeAlignment);
4116 ObjCTypeParamType *newType = new (mem)
4117 ObjCTypeParamType(Decl, Canonical, protocols);
4118
4119 Types.push_back(newType);
4120 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4121 return QualType(newType, 0);
4122}
4123
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004124/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4125/// protocol list adopt all protocols in QT's qualified-id protocol
4126/// list.
4127bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4128 ObjCInterfaceDecl *IC) {
4129 if (!QT->isObjCQualifiedIdType())
4130 return false;
4131
4132 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4133 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004134 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004135 if (!IC->ClassImplementsProtocol(Proto, false))
4136 return false;
4137 }
4138 return true;
4139 }
4140 return false;
4141}
4142
4143/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4144/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4145/// of protocols.
4146bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4147 ObjCInterfaceDecl *IDecl) {
4148 if (!QT->isObjCQualifiedIdType())
4149 return false;
4150 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4151 if (!OPT)
4152 return false;
4153 if (!IDecl->hasDefinition())
4154 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004155 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4156 CollectInheritedProtocols(IDecl, InheritedProtocols);
4157 if (InheritedProtocols.empty())
4158 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004159 // Check that if every protocol in list of id<plist> conforms to a protcol
4160 // of IDecl's, then bridge casting is ok.
4161 bool Conforms = false;
4162 for (auto *Proto : OPT->quals()) {
4163 Conforms = false;
4164 for (auto *PI : InheritedProtocols) {
4165 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4166 Conforms = true;
4167 break;
4168 }
4169 }
4170 if (!Conforms)
4171 break;
4172 }
4173 if (Conforms)
4174 return true;
4175
Aaron Ballman83731462014-03-17 16:14:00 +00004176 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004177 // If both the right and left sides have qualifiers.
4178 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004179 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004180 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004181 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004182 break;
4183 }
4184 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004185 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004186 }
4187 return true;
4188}
4189
John McCall8b07ec22010-05-15 11:32:37 +00004190/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4191/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004192QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004193 llvm::FoldingSetNodeID ID;
4194 ObjCObjectPointerType::Profile(ID, ObjectT);
4195
Craig Topper36250ad2014-05-12 05:36:57 +00004196 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004197 if (ObjCObjectPointerType *QT =
4198 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4199 return QualType(QT, 0);
4200
4201 // Find the canonical object type.
4202 QualType Canonical;
4203 if (!ObjectT.isCanonical()) {
4204 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4205
4206 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004207 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4208 }
4209
Douglas Gregorf85bee62010-02-08 22:59:26 +00004210 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004211 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4212 ObjCObjectPointerType *QType =
4213 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004214
Steve Narofffb4330f2009-06-17 22:40:22 +00004215 Types.push_back(QType);
4216 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004217 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004218}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004219
Douglas Gregor1c283312010-08-11 12:19:30 +00004220/// getObjCInterfaceType - Return the unique reference to the type for the
4221/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004222QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4223 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004224 if (Decl->TypeForDecl)
4225 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004226
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004227 if (PrevDecl) {
4228 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4229 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4230 return QualType(PrevDecl->TypeForDecl, 0);
4231 }
4232
Douglas Gregor7671e532011-12-16 16:34:57 +00004233 // Prefer the definition, if there is one.
4234 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4235 Decl = Def;
4236
Douglas Gregor1c283312010-08-11 12:19:30 +00004237 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4238 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4239 Decl->TypeForDecl = T;
4240 Types.push_back(T);
4241 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004242}
4243
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004244/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4245/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004246/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004247/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004248/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004249QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004250 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004251 if (tofExpr->isTypeDependent()) {
4252 llvm::FoldingSetNodeID ID;
4253 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004254
Craig Topper36250ad2014-05-12 05:36:57 +00004255 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004256 DependentTypeOfExprType *Canon
4257 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4258 if (Canon) {
4259 // We already have a "canonical" version of an identical, dependent
4260 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004261 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004262 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004263 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004264 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004265 Canon
4266 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004267 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4268 toe = Canon;
4269 }
4270 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004271 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004272 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004273 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004274 Types.push_back(toe);
4275 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004276}
4277
Steve Naroffa773cd52007-08-01 18:02:17 +00004278/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004279/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004280/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004281/// an issue. This doesn't affect the type checker, since it operates
4282/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004283QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004284 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004285 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004286 Types.push_back(tot);
4287 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004288}
4289
Richard Smith8eb1d322014-06-05 20:13:13 +00004290/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4291/// nodes. This would never be helpful, since each such type has its own
4292/// expression, and would not give a significant memory saving, since there
4293/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004294QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004295 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004296
4297 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004298 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004299 // unique dependent type. Two such decltype-specifiers refer to the same
4300 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004301 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004302 llvm::FoldingSetNodeID ID;
4303 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004304
Craig Topper36250ad2014-05-12 05:36:57 +00004305 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004306 DependentDecltypeType *Canon
4307 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004308 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004309 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004310 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004311 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004312 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004313 dt = new (*this, TypeAlignment)
4314 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004315 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004316 dt = new (*this, TypeAlignment)
4317 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004318 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004319 Types.push_back(dt);
4320 return QualType(dt, 0);
4321}
4322
Alexis Hunte852b102011-05-24 22:41:36 +00004323/// getUnaryTransformationType - We don't unique these, since the memory
4324/// savings are minimal and these are rare.
4325QualType ASTContext::getUnaryTransformType(QualType BaseType,
4326 QualType UnderlyingType,
4327 UnaryTransformType::UTTKind Kind)
4328 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004329 UnaryTransformType *ut = nullptr;
4330
4331 if (BaseType->isDependentType()) {
4332 // Look in the folding set for an existing type.
4333 llvm::FoldingSetNodeID ID;
4334 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4335
4336 void *InsertPos = nullptr;
4337 DependentUnaryTransformType *Canon
4338 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4339
4340 if (!Canon) {
4341 // Build a new, canonical __underlying_type(type) type.
4342 Canon = new (*this, TypeAlignment)
4343 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4344 Kind);
4345 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4346 }
4347 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4348 QualType(), Kind,
4349 QualType(Canon, 0));
4350 } else {
4351 QualType CanonType = getCanonicalType(UnderlyingType);
4352 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4353 UnderlyingType, Kind,
4354 CanonType);
4355 }
4356 Types.push_back(ut);
4357 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004358}
4359
Richard Smith2a7d4812013-05-04 07:00:32 +00004360/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4361/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4362/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004363QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004364 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004365 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004366 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004367
Richard Smith2a7d4812013-05-04 07:00:32 +00004368 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004369 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004370 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004371 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004372 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4373 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004374
Richard Smith74aeef52013-04-26 16:15:35 +00004375 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004376 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004377 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004378 Types.push_back(AT);
4379 if (InsertPos)
4380 AutoTypes.InsertNode(AT, InsertPos);
4381 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004382}
4383
Eli Friedman0dfb8892011-10-06 23:00:33 +00004384/// getAtomicType - Return the uniqued reference to the atomic type for
4385/// the given value type.
4386QualType ASTContext::getAtomicType(QualType T) const {
4387 // Unique pointers, to guarantee there is only one pointer of a particular
4388 // structure.
4389 llvm::FoldingSetNodeID ID;
4390 AtomicType::Profile(ID, T);
4391
Craig Topper36250ad2014-05-12 05:36:57 +00004392 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004393 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4394 return QualType(AT, 0);
4395
4396 // If the atomic value type isn't canonical, this won't be a canonical type
4397 // either, so fill in the canonical type field.
4398 QualType Canonical;
4399 if (!T.isCanonical()) {
4400 Canonical = getAtomicType(getCanonicalType(T));
4401
4402 // Get the new insert position for the node we care about.
4403 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004404 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004405 }
4406 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4407 Types.push_back(New);
4408 AtomicTypes.InsertNode(New, InsertPos);
4409 return QualType(New, 0);
4410}
4411
Richard Smith02e85f32011-04-14 22:09:26 +00004412/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4413QualType ASTContext::getAutoDeductType() const {
4414 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004415 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004416 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004417 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004418 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004419 return AutoDeductTy;
4420}
4421
4422/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4423QualType ASTContext::getAutoRRefDeductType() const {
4424 if (AutoRRefDeductTy.isNull())
4425 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4426 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4427 return AutoRRefDeductTy;
4428}
4429
Chris Lattnerfb072462007-01-23 05:45:31 +00004430/// getTagDeclType - Return the unique reference to the type for the
4431/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004432QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004433 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004434 // FIXME: What is the design on getTagDeclType when it requires casting
4435 // away const? mutable?
4436 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004437}
4438
Mike Stump11289f42009-09-09 15:08:12 +00004439/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4440/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4441/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004442CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004443 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004444}
Chris Lattnerfb072462007-01-23 05:45:31 +00004445
Hans Wennborg27541db2011-10-27 08:29:09 +00004446/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4447CanQualType ASTContext::getIntMaxType() const {
4448 return getFromTargetType(Target->getIntMaxType());
4449}
4450
4451/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4452CanQualType ASTContext::getUIntMaxType() const {
4453 return getFromTargetType(Target->getUIntMaxType());
4454}
4455
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004456/// getSignedWCharType - Return the type of "signed wchar_t".
4457/// Used when in C++, as a GCC extension.
4458QualType ASTContext::getSignedWCharType() const {
4459 // FIXME: derive from "Target" ?
4460 return WCharTy;
4461}
4462
4463/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4464/// Used when in C++, as a GCC extension.
4465QualType ASTContext::getUnsignedWCharType() const {
4466 // FIXME: derive from "Target" ?
4467 return UnsignedIntTy;
4468}
4469
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004470QualType ASTContext::getIntPtrType() const {
4471 return getFromTargetType(Target->getIntPtrType());
4472}
4473
4474QualType ASTContext::getUIntPtrType() const {
4475 return getCorrespondingUnsignedType(getIntPtrType());
4476}
4477
Hans Wennborg27541db2011-10-27 08:29:09 +00004478/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004479/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4480QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004481 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004482}
4483
Eli Friedman4e91899e2012-11-27 02:58:24 +00004484/// \brief Return the unique type for "pid_t" defined in
4485/// <sys/types.h>. We need this to compute the correct type for vfork().
4486QualType ASTContext::getProcessIDType() const {
4487 return getFromTargetType(Target->getProcessIDType());
4488}
4489
Chris Lattnera21ad802008-04-02 05:18:44 +00004490//===----------------------------------------------------------------------===//
4491// Type Operators
4492//===----------------------------------------------------------------------===//
4493
Jay Foad39c79802011-01-12 09:06:06 +00004494CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004495 // Push qualifiers into arrays, and then discard any remaining
4496 // qualifiers.
4497 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004498 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004499 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004500 QualType Result;
4501 if (isa<ArrayType>(Ty)) {
4502 Result = getArrayDecayedType(QualType(Ty,0));
4503 } else if (isa<FunctionType>(Ty)) {
4504 Result = getPointerType(QualType(Ty, 0));
4505 } else {
4506 Result = QualType(Ty, 0);
4507 }
4508
4509 return CanQualType::CreateUnsafe(Result);
4510}
4511
John McCall6c9dd522011-01-18 07:41:22 +00004512QualType ASTContext::getUnqualifiedArrayType(QualType type,
4513 Qualifiers &quals) {
4514 SplitQualType splitType = type.getSplitUnqualifiedType();
4515
4516 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4517 // the unqualified desugared type and then drops it on the floor.
4518 // We then have to strip that sugar back off with
4519 // getUnqualifiedDesugaredType(), which is silly.
4520 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004521 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004522
4523 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004524 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004525 quals = splitType.Quals;
4526 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004527 }
4528
John McCall6c9dd522011-01-18 07:41:22 +00004529 // Otherwise, recurse on the array's element type.
4530 QualType elementType = AT->getElementType();
4531 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4532
4533 // If that didn't change the element type, AT has no qualifiers, so we
4534 // can just use the results in splitType.
4535 if (elementType == unqualElementType) {
4536 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004537 quals = splitType.Quals;
4538 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004539 }
4540
4541 // Otherwise, add in the qualifiers from the outermost type, then
4542 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004543 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004544
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004545 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004546 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004547 CAT->getSizeModifier(), 0);
4548 }
4549
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004550 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004551 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004552 }
4553
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004554 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004555 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004556 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004557 VAT->getSizeModifier(),
4558 VAT->getIndexTypeCVRQualifiers(),
4559 VAT->getBracketsRange());
4560 }
4561
4562 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004563 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004564 DSAT->getSizeModifier(), 0,
4565 SourceRange());
4566}
4567
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004568/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4569/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4570/// they point to and return true. If T1 and T2 aren't pointer types
4571/// or pointer-to-member types, or if they are not similar at this
4572/// level, returns false and leaves T1 and T2 unchanged. Top-level
4573/// qualifiers on T1 and T2 are ignored. This function will typically
4574/// be called in a loop that successively "unwraps" pointer and
4575/// pointer-to-member types to compare them at each level.
4576bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4577 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4578 *T2PtrType = T2->getAs<PointerType>();
4579 if (T1PtrType && T2PtrType) {
4580 T1 = T1PtrType->getPointeeType();
4581 T2 = T2PtrType->getPointeeType();
4582 return true;
4583 }
4584
4585 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4586 *T2MPType = T2->getAs<MemberPointerType>();
4587 if (T1MPType && T2MPType &&
4588 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4589 QualType(T2MPType->getClass(), 0))) {
4590 T1 = T1MPType->getPointeeType();
4591 T2 = T2MPType->getPointeeType();
4592 return true;
4593 }
4594
David Blaikiebbafb8a2012-03-11 07:00:24 +00004595 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004596 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4597 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4598 if (T1OPType && T2OPType) {
4599 T1 = T1OPType->getPointeeType();
4600 T2 = T2OPType->getPointeeType();
4601 return true;
4602 }
4603 }
4604
4605 // FIXME: Block pointers, too?
4606
4607 return false;
4608}
4609
Jay Foad39c79802011-01-12 09:06:06 +00004610DeclarationNameInfo
4611ASTContext::getNameForTemplate(TemplateName Name,
4612 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004613 switch (Name.getKind()) {
4614 case TemplateName::QualifiedTemplate:
4615 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004616 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004617 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4618 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004619
John McCalld9dfe3a2011-06-30 08:33:18 +00004620 case TemplateName::OverloadedTemplate: {
4621 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4622 // DNInfo work in progress: CHECKME: what about DNLoc?
4623 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4624 }
4625
4626 case TemplateName::DependentTemplate: {
4627 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004628 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004629 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004630 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4631 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004632 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004633 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4634 // DNInfo work in progress: FIXME: source locations?
4635 DeclarationNameLoc DNLoc;
4636 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4637 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4638 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004639 }
4640 }
4641
John McCalld9dfe3a2011-06-30 08:33:18 +00004642 case TemplateName::SubstTemplateTemplateParm: {
4643 SubstTemplateTemplateParmStorage *subst
4644 = Name.getAsSubstTemplateTemplateParm();
4645 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4646 NameLoc);
4647 }
4648
4649 case TemplateName::SubstTemplateTemplateParmPack: {
4650 SubstTemplateTemplateParmPackStorage *subst
4651 = Name.getAsSubstTemplateTemplateParmPack();
4652 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4653 NameLoc);
4654 }
4655 }
4656
4657 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004658}
4659
Jay Foad39c79802011-01-12 09:06:06 +00004660TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004661 switch (Name.getKind()) {
4662 case TemplateName::QualifiedTemplate:
4663 case TemplateName::Template: {
4664 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004665 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004666 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004667 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4668
4669 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004670 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004671 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004672
John McCalld9dfe3a2011-06-30 08:33:18 +00004673 case TemplateName::OverloadedTemplate:
4674 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004675
John McCalld9dfe3a2011-06-30 08:33:18 +00004676 case TemplateName::DependentTemplate: {
4677 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4678 assert(DTN && "Non-dependent template names must refer to template decls.");
4679 return DTN->CanonicalTemplateName;
4680 }
4681
4682 case TemplateName::SubstTemplateTemplateParm: {
4683 SubstTemplateTemplateParmStorage *subst
4684 = Name.getAsSubstTemplateTemplateParm();
4685 return getCanonicalTemplateName(subst->getReplacement());
4686 }
4687
4688 case TemplateName::SubstTemplateTemplateParmPack: {
4689 SubstTemplateTemplateParmPackStorage *subst
4690 = Name.getAsSubstTemplateTemplateParmPack();
4691 TemplateTemplateParmDecl *canonParameter
4692 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4693 TemplateArgument canonArgPack
4694 = getCanonicalTemplateArgument(subst->getArgumentPack());
4695 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4696 }
4697 }
4698
4699 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004700}
4701
Douglas Gregoradee3e32009-11-11 23:06:43 +00004702bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4703 X = getCanonicalTemplateName(X);
4704 Y = getCanonicalTemplateName(Y);
4705 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4706}
4707
Mike Stump11289f42009-09-09 15:08:12 +00004708TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004709ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004710 switch (Arg.getKind()) {
4711 case TemplateArgument::Null:
4712 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004713
Douglas Gregora8e02e72009-07-28 23:00:59 +00004714 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004715 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004716
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004717 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004718 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004719 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004720 }
Mike Stump11289f42009-09-09 15:08:12 +00004721
Eli Friedmanb826a002012-09-26 02:36:12 +00004722 case TemplateArgument::NullPtr:
4723 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4724 /*isNullPtr*/true);
4725
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004726 case TemplateArgument::Template:
4727 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004728
4729 case TemplateArgument::TemplateExpansion:
4730 return TemplateArgument(getCanonicalTemplateName(
4731 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004732 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004733
Douglas Gregora8e02e72009-07-28 23:00:59 +00004734 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004735 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004736
Douglas Gregora8e02e72009-07-28 23:00:59 +00004737 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004738 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004739
Douglas Gregora8e02e72009-07-28 23:00:59 +00004740 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004741 if (Arg.pack_size() == 0)
4742 return Arg;
4743
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004744 TemplateArgument *CanonArgs
4745 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004746 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004747 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004748 AEnd = Arg.pack_end();
4749 A != AEnd; (void)++A, ++Idx)
4750 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004751
Benjamin Kramercce63472015-08-05 09:40:22 +00004752 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004753 }
4754 }
4755
4756 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004757 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004758}
4759
Douglas Gregor333489b2009-03-27 23:10:48 +00004760NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004761ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004762 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004763 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004764
4765 switch (NNS->getKind()) {
4766 case NestedNameSpecifier::Identifier:
4767 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004768 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004769 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4770 NNS->getAsIdentifier());
4771
4772 case NestedNameSpecifier::Namespace:
4773 // A namespace is canonical; build a nested-name-specifier with
4774 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004775 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004776 NNS->getAsNamespace()->getOriginalNamespace());
4777
4778 case NestedNameSpecifier::NamespaceAlias:
4779 // A namespace is canonical; build a nested-name-specifier with
4780 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004781 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004782 NNS->getAsNamespaceAlias()->getNamespace()
4783 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004784
4785 case NestedNameSpecifier::TypeSpec:
4786 case NestedNameSpecifier::TypeSpecWithTemplate: {
4787 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004788
4789 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4790 // break it apart into its prefix and identifier, then reconsititute those
4791 // as the canonical nested-name-specifier. This is required to canonicalize
4792 // a dependent nested-name-specifier involving typedefs of dependent-name
4793 // types, e.g.,
4794 // typedef typename T::type T1;
4795 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004796 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4797 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004798 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004799
Eli Friedman5358a0a2012-03-03 04:09:56 +00004800 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4801 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4802 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004803 return NestedNameSpecifier::Create(*this, nullptr, false,
4804 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004805 }
4806
4807 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004808 case NestedNameSpecifier::Super:
4809 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004810 return NNS;
4811 }
4812
David Blaikie8a40f702012-01-17 06:56:22 +00004813 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004814}
4815
Jay Foad39c79802011-01-12 09:06:06 +00004816const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004817 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004818 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004819 // Handle the common positive case fast.
4820 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4821 return AT;
4822 }
Mike Stump11289f42009-09-09 15:08:12 +00004823
John McCall8ccfcb52009-09-24 19:53:00 +00004824 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004825 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004826 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004827
John McCall8ccfcb52009-09-24 19:53:00 +00004828 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004829 // implements C99 6.7.3p8: "If the specification of an array type includes
4830 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004831
Chris Lattner7adf0762008-08-04 07:31:14 +00004832 // If we get here, we either have type qualifiers on the type, or we have
4833 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004834 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004835
John McCall33ddac02011-01-19 10:06:00 +00004836 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004837 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004838
Chris Lattner7adf0762008-08-04 07:31:14 +00004839 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004840 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004841 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004842 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004843
Chris Lattner7adf0762008-08-04 07:31:14 +00004844 // Otherwise, we have an array and we have qualifiers on it. Push the
4845 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004846 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004847
Chris Lattner7adf0762008-08-04 07:31:14 +00004848 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4849 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4850 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004851 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004852 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4853 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4854 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004855 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004856
Mike Stump11289f42009-09-09 15:08:12 +00004857 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004858 = dyn_cast<DependentSizedArrayType>(ATy))
4859 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004860 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004861 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004862 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004863 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004864 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004865
Chris Lattner7adf0762008-08-04 07:31:14 +00004866 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004867 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004868 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004869 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004870 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004871 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004872}
4873
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004874QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004875 if (T->isArrayType() || T->isFunctionType())
4876 return getDecayedType(T);
4877 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004878}
4879
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004880QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004881 T = getVariableArrayDecayedType(T);
4882 T = getAdjustedParameterType(T);
4883 return T.getUnqualifiedType();
4884}
4885
David Majnemerd09a51c2015-03-03 01:50:05 +00004886QualType ASTContext::getExceptionObjectType(QualType T) const {
4887 // C++ [except.throw]p3:
4888 // A throw-expression initializes a temporary object, called the exception
4889 // object, the type of which is determined by removing any top-level
4890 // cv-qualifiers from the static type of the operand of throw and adjusting
4891 // the type from "array of T" or "function returning T" to "pointer to T"
4892 // or "pointer to function returning T", [...]
4893 T = getVariableArrayDecayedType(T);
4894 if (T->isArrayType() || T->isFunctionType())
4895 T = getDecayedType(T);
4896 return T.getUnqualifiedType();
4897}
4898
Chris Lattnera21ad802008-04-02 05:18:44 +00004899/// getArrayDecayedType - Return the properly qualified result of decaying the
4900/// specified array type to a pointer. This operation is non-trivial when
4901/// handling typedefs etc. The canonical type of "T" must be an array type,
4902/// this returns a pointer to a properly qualified element of the array.
4903///
4904/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004905QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004906 // Get the element type with 'getAsArrayType' so that we don't lose any
4907 // typedefs in the element type of the array. This also handles propagation
4908 // of type qualifiers from the array type into the element type if present
4909 // (C99 6.7.3p8).
4910 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4911 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004912
Chris Lattner7adf0762008-08-04 07:31:14 +00004913 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004914
4915 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004916 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004917}
4918
John McCall33ddac02011-01-19 10:06:00 +00004919QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4920 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004921}
4922
John McCall33ddac02011-01-19 10:06:00 +00004923QualType ASTContext::getBaseElementType(QualType type) const {
4924 Qualifiers qs;
4925 while (true) {
4926 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004927 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004928 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004929
John McCall33ddac02011-01-19 10:06:00 +00004930 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004931 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004932 }
Mike Stump11289f42009-09-09 15:08:12 +00004933
John McCall33ddac02011-01-19 10:06:00 +00004934 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004935}
4936
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004937/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004938uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004939ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4940 uint64_t ElementCount = 1;
4941 do {
4942 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004943 CA = dyn_cast_or_null<ConstantArrayType>(
4944 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004945 } while (CA);
4946 return ElementCount;
4947}
4948
Steve Naroff0af91202007-04-27 21:51:21 +00004949/// getFloatingRank - Return a relative rank for floating point types.
4950/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004951static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004952 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004953 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004954
John McCall9dd450b2009-09-21 23:43:11 +00004955 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4956 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004957 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004958 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004959 case BuiltinType::Float: return FloatRank;
4960 case BuiltinType::Double: return DoubleRank;
4961 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004962 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00004963 }
4964}
4965
Mike Stump11289f42009-09-09 15:08:12 +00004966/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4967/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004968/// 'typeDomain' is a real floating point or complex type.
4969/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004970QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4971 QualType Domain) const {
4972 FloatingRank EltRank = getFloatingRank(Size);
4973 if (Domain->isComplexType()) {
4974 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004975 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004976 case FloatRank: return FloatComplexTy;
4977 case DoubleRank: return DoubleComplexTy;
4978 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004979 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004980 }
Steve Naroff0af91202007-04-27 21:51:21 +00004981 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004982
4983 assert(Domain->isRealFloatingType() && "Unknown domain!");
4984 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004985 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004986 case FloatRank: return FloatTy;
4987 case DoubleRank: return DoubleTy;
4988 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004989 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00004990 }
David Blaikief47fa302012-01-17 02:30:50 +00004991 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004992}
4993
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004994/// getFloatingTypeOrder - Compare the rank of the two specified floating
4995/// point types, ignoring the domain of the type (i.e. 'double' ==
4996/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004997/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004998int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004999 FloatingRank LHSR = getFloatingRank(LHS);
5000 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005001
Chris Lattnerb90739d2008-04-06 23:38:49 +00005002 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005003 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005004 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005005 return 1;
5006 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005007}
5008
Chris Lattner76a00cf2008-04-06 22:59:24 +00005009/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5010/// routine will assert if passed a built-in type that isn't an integer or enum,
5011/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005012unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005013 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005014
Chris Lattner76a00cf2008-04-06 22:59:24 +00005015 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005016 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005017 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005018 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005019 case BuiltinType::Char_S:
5020 case BuiltinType::Char_U:
5021 case BuiltinType::SChar:
5022 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005023 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005024 case BuiltinType::Short:
5025 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005026 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005027 case BuiltinType::Int:
5028 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005029 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005030 case BuiltinType::Long:
5031 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005032 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005033 case BuiltinType::LongLong:
5034 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005035 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005036 case BuiltinType::Int128:
5037 case BuiltinType::UInt128:
5038 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005039 }
5040}
5041
Eli Friedman629ffb92009-08-20 04:21:42 +00005042/// \brief Whether this is a promotable bitfield reference according
5043/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5044///
5045/// \returns the type this bit-field will promote to, or NULL if no
5046/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005047QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005048 if (E->isTypeDependent() || E->isValueDependent())
5049 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005050
5051 // FIXME: We should not do this unless E->refersToBitField() is true. This
5052 // matters in C where getSourceBitField() will find bit-fields for various
5053 // cases where the source expression is not a bit-field designator.
5054
John McCalld25db7e2013-05-06 21:39:12 +00005055 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005056 if (!Field)
5057 return QualType();
5058
5059 QualType FT = Field->getType();
5060
Richard Smithcaf33902011-10-10 18:28:20 +00005061 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005062 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005063 // C++ [conv.prom]p5:
5064 // A prvalue for an integral bit-field can be converted to a prvalue of type
5065 // int if int can represent all the values of the bit-field; otherwise, it
5066 // can be converted to unsigned int if unsigned int can represent all the
5067 // values of the bit-field. If the bit-field is larger yet, no integral
5068 // promotion applies to it.
5069 // C11 6.3.1.1/2:
5070 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5071 // If an int can represent all values of the original type (as restricted by
5072 // the width, for a bit-field), the value is converted to an int; otherwise,
5073 // it is converted to an unsigned int.
5074 //
5075 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5076 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005077 if (BitWidth < IntSize)
5078 return IntTy;
5079
5080 if (BitWidth == IntSize)
5081 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5082
5083 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005084 // like the base type. GCC has some weird bugs in this area that we
5085 // deliberately do not follow (GCC follows a pre-standard resolution to
5086 // C's DR315 which treats bit-width as being part of the type, and this leaks
5087 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005088 return QualType();
5089}
5090
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005091/// getPromotedIntegerType - Returns the type that Promotable will
5092/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5093/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005094QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005095 assert(!Promotable.isNull());
5096 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005097 if (const EnumType *ET = Promotable->getAs<EnumType>())
5098 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005099
5100 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5101 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5102 // (3.9.1) can be converted to a prvalue of the first of the following
5103 // types that can represent all the values of its underlying type:
5104 // int, unsigned int, long int, unsigned long int, long long int, or
5105 // unsigned long long int [...]
5106 // FIXME: Is there some better way to compute this?
5107 if (BT->getKind() == BuiltinType::WChar_S ||
5108 BT->getKind() == BuiltinType::WChar_U ||
5109 BT->getKind() == BuiltinType::Char16 ||
5110 BT->getKind() == BuiltinType::Char32) {
5111 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5112 uint64_t FromSize = getTypeSize(BT);
5113 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5114 LongLongTy, UnsignedLongLongTy };
5115 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5116 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5117 if (FromSize < ToSize ||
5118 (FromSize == ToSize &&
5119 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5120 return PromoteTypes[Idx];
5121 }
5122 llvm_unreachable("char type should fit into long long");
5123 }
5124 }
5125
5126 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005127 if (Promotable->isSignedIntegerType())
5128 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005129 uint64_t PromotableSize = getIntWidth(Promotable);
5130 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005131 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5132 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5133}
5134
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005135/// \brief Recurses in pointer/array types until it finds an objc retainable
5136/// type and returns its ownership.
5137Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5138 while (!T.isNull()) {
5139 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5140 return T.getObjCLifetime();
5141 if (T->isArrayType())
5142 T = getBaseElementType(T);
5143 else if (const PointerType *PT = T->getAs<PointerType>())
5144 T = PT->getPointeeType();
5145 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005146 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005147 else
5148 break;
5149 }
5150
5151 return Qualifiers::OCL_None;
5152}
5153
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005154static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5155 // Incomplete enum types are not treated as integer types.
5156 // FIXME: In C++, enum types are never integer types.
5157 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5158 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005159 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005160}
5161
Mike Stump11289f42009-09-09 15:08:12 +00005162/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005163/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005164/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005165int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005166 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5167 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005168
5169 // Unwrap enums to their underlying type.
5170 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5171 LHSC = getIntegerTypeForEnum(ET);
5172 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5173 RHSC = getIntegerTypeForEnum(ET);
5174
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005175 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005176
Chris Lattner76a00cf2008-04-06 22:59:24 +00005177 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5178 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005179
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005180 unsigned LHSRank = getIntegerRank(LHSC);
5181 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005182
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005183 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5184 if (LHSRank == RHSRank) return 0;
5185 return LHSRank > RHSRank ? 1 : -1;
5186 }
Mike Stump11289f42009-09-09 15:08:12 +00005187
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005188 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5189 if (LHSUnsigned) {
5190 // If the unsigned [LHS] type is larger, return it.
5191 if (LHSRank >= RHSRank)
5192 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005193
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005194 // If the signed type can represent all values of the unsigned type, it
5195 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005196 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005197 return -1;
5198 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005199
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005200 // If the unsigned [RHS] type is larger, return it.
5201 if (RHSRank >= LHSRank)
5202 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005203
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005204 // If the signed type can represent all values of the unsigned type, it
5205 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005206 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005207 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005208}
Anders Carlsson98f07902007-08-17 05:31:46 +00005209
Ben Langmuirf5416742016-02-04 00:55:24 +00005210TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005211 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005212 assert(!CFConstantStringTagDecl &&
5213 "tag and typedef should be initialized together");
5214 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5215 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005216
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005217 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005218 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005219
Anders Carlsson98f07902007-08-17 05:31:46 +00005220 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005221 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005222 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005223 // int flags;
5224 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005225 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005226 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005227 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005228 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005229 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005230 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005231 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005232
Anders Carlsson98f07902007-08-17 05:31:46 +00005233 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005234 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005235 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005236 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005237 SourceLocation(),
5238 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005239 FieldTypes[i], /*TInfo=*/nullptr,
5240 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005241 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005242 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005243 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005244 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005245 }
5246
Ben Langmuirf5416742016-02-04 00:55:24 +00005247 CFConstantStringTagDecl->completeDefinition();
5248 // This type is designed to be compatible with NSConstantString, but cannot
5249 // use the same name, since NSConstantString is an interface.
5250 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5251 CFConstantStringTypeDecl =
5252 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005253 }
Mike Stump11289f42009-09-09 15:08:12 +00005254
Quentin Colombet043406b2016-02-03 22:41:00 +00005255 return CFConstantStringTypeDecl;
5256}
5257
Ben Langmuirf5416742016-02-04 00:55:24 +00005258RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5259 if (!CFConstantStringTagDecl)
5260 getCFConstantStringDecl(); // Build the tag and the typedef.
5261 return CFConstantStringTagDecl;
5262}
5263
Quentin Colombet043406b2016-02-03 22:41:00 +00005264// getCFConstantStringType - Return the type used for constant CFStrings.
5265QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005266 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005267}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005268
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005269QualType ASTContext::getObjCSuperType() const {
5270 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005271 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005272 TUDecl->addDecl(ObjCSuperTypeDecl);
5273 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5274 }
5275 return ObjCSuperType;
5276}
5277
Douglas Gregor512b0772009-04-23 22:29:11 +00005278void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005279 const TypedefType *TD = T->getAs<TypedefType>();
5280 assert(TD && "Invalid CFConstantStringType");
5281 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5282 auto TagType =
5283 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5284 assert(TagType && "Invalid CFConstantStringType");
5285 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005286}
5287
Jay Foad39c79802011-01-12 09:06:06 +00005288QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005289 if (BlockDescriptorType)
5290 return getTagDeclType(BlockDescriptorType);
5291
Alp Toker2dea15b2013-12-17 01:22:38 +00005292 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005293 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005294 RD = buildImplicitRecord("__block_descriptor");
5295 RD->startDefinition();
5296
Mike Stumpd0153282009-10-20 02:12:22 +00005297 QualType FieldTypes[] = {
5298 UnsignedLongTy,
5299 UnsignedLongTy,
5300 };
5301
Craig Topperd6d31ac2013-07-15 08:24:27 +00005302 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005303 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005304 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005305 };
5306
5307 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005308 FieldDecl *Field = FieldDecl::Create(
5309 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005310 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5311 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005312 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005313 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005314 }
5315
Alp Toker2dea15b2013-12-17 01:22:38 +00005316 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005317
Alp Toker2dea15b2013-12-17 01:22:38 +00005318 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005319
5320 return getTagDeclType(BlockDescriptorType);
5321}
5322
Jay Foad39c79802011-01-12 09:06:06 +00005323QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005324 if (BlockDescriptorExtendedType)
5325 return getTagDeclType(BlockDescriptorExtendedType);
5326
Alp Toker2dea15b2013-12-17 01:22:38 +00005327 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005328 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005329 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5330 RD->startDefinition();
5331
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005332 QualType FieldTypes[] = {
5333 UnsignedLongTy,
5334 UnsignedLongTy,
5335 getPointerType(VoidPtrTy),
5336 getPointerType(VoidPtrTy)
5337 };
5338
Craig Topperd6d31ac2013-07-15 08:24:27 +00005339 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005340 "reserved",
5341 "Size",
5342 "CopyFuncPtr",
5343 "DestroyFuncPtr"
5344 };
5345
5346 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005347 FieldDecl *Field = FieldDecl::Create(
5348 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005349 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5350 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005351 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005352 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005353 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005354 }
5355
Alp Toker2dea15b2013-12-17 01:22:38 +00005356 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005357
Alp Toker2dea15b2013-12-17 01:22:38 +00005358 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005359 return getTagDeclType(BlockDescriptorExtendedType);
5360}
5361
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005362/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5363/// requires copy/dispose. Note that this must match the logic
5364/// in buildByrefHelpers.
5365bool ASTContext::BlockRequiresCopying(QualType Ty,
5366 const VarDecl *D) {
5367 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5368 const Expr *copyExpr = getBlockVarCopyInits(D);
5369 if (!copyExpr && record->hasTrivialDestructor()) return false;
5370
Mike Stump94967902009-10-21 18:16:27 +00005371 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005372 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005373
5374 if (!Ty->isObjCRetainableType()) return false;
5375
5376 Qualifiers qs = Ty.getQualifiers();
5377
5378 // If we have lifetime, that dominates.
5379 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005380 switch (lifetime) {
5381 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5382
5383 // These are just bits as far as the runtime is concerned.
5384 case Qualifiers::OCL_ExplicitNone:
5385 case Qualifiers::OCL_Autoreleasing:
5386 return false;
5387
5388 // Tell the runtime that this is ARC __weak, called by the
5389 // byref routines.
5390 case Qualifiers::OCL_Weak:
5391 // ARC __strong __block variables need to be retained.
5392 case Qualifiers::OCL_Strong:
5393 return true;
5394 }
5395 llvm_unreachable("fell out of lifetime switch!");
5396 }
5397 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5398 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005399}
5400
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005401bool ASTContext::getByrefLifetime(QualType Ty,
5402 Qualifiers::ObjCLifetime &LifeTime,
5403 bool &HasByrefExtendedLayout) const {
5404
5405 if (!getLangOpts().ObjC1 ||
5406 getLangOpts().getGC() != LangOptions::NonGC)
5407 return false;
5408
5409 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005410 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005411 HasByrefExtendedLayout = true;
5412 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005413 } else if ((LifeTime = Ty.getObjCLifetime())) {
5414 // Honor the ARC qualifiers.
5415 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5416 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005417 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005418 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005419 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005420 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005421 return true;
5422}
5423
Douglas Gregorbab8a962011-09-08 01:46:34 +00005424TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5425 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005426 ObjCInstanceTypeDecl =
5427 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005428 return ObjCInstanceTypeDecl;
5429}
5430
Anders Carlsson18acd442007-10-29 06:33:42 +00005431// This returns true if a type has been typedefed to BOOL:
5432// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005433static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005434 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005435 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5436 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005437
Anders Carlssond8499822007-10-29 05:01:08 +00005438 return false;
5439}
5440
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005441/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005442/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005443CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005444 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5445 return CharUnits::Zero();
5446
Ken Dyck40775002010-01-11 17:06:35 +00005447 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005448
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005449 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005450 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005451 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005452 // Treat arrays as pointers, since that's how they're passed in.
5453 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005454 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005455 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005456}
5457
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005458bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005459 return getTargetInfo().getCXXABI().isMicrosoft() &&
5460 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005461 VD->getType()->isIntegralOrEnumerationType() &&
5462 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005463}
5464
Richard Smithd9b90092016-07-02 01:32:16 +00005465ASTContext::InlineVariableDefinitionKind
5466ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5467 if (!VD->isInline())
5468 return InlineVariableDefinitionKind::None;
5469
5470 // In almost all cases, it's a weak definition.
5471 auto *First = VD->getFirstDecl();
5472 if (!First->isConstexpr() || First->isInlineSpecified() ||
5473 !VD->isStaticDataMember())
5474 return InlineVariableDefinitionKind::Weak;
5475
5476 // If there's a file-context declaration in this translation unit, it's a
5477 // non-discardable definition.
5478 for (auto *D : VD->redecls())
5479 if (D->getLexicalDeclContext()->isFileContext())
5480 return InlineVariableDefinitionKind::Strong;
5481
5482 // If we've not seen one yet, we don't know.
5483 return InlineVariableDefinitionKind::WeakUnknown;
5484}
5485
Ken Dyck40775002010-01-11 17:06:35 +00005486static inline
5487std::string charUnitsToString(const CharUnits &CU) {
5488 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005489}
5490
John McCall351762c2011-02-07 10:33:21 +00005491/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005492/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005493std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5494 std::string S;
5495
David Chisnall950a9512009-11-17 19:33:30 +00005496 const BlockDecl *Decl = Expr->getBlockDecl();
5497 QualType BlockTy =
5498 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5499 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005500 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005501 getObjCEncodingForMethodParameter(
5502 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5503 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005504 else
Alp Toker314cc812014-01-25 16:55:45 +00005505 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005506 // Compute size of all parameters.
5507 // Start with computing size of a pointer in number of bytes.
5508 // FIXME: There might(should) be a better way of doing this computation!
5509 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005510 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5511 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005512 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005513 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005514 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005515 if (sz.isZero())
5516 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005517 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005518 ParmOffset += sz;
5519 }
5520 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005521 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005522 // Block pointer and offset.
5523 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005524
5525 // Argument types.
5526 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005527 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005528 QualType PType = PVDecl->getOriginalType();
5529 if (const ArrayType *AT =
5530 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5531 // Use array's original type only if it has known number of
5532 // elements.
5533 if (!isa<ConstantArrayType>(AT))
5534 PType = PVDecl->getType();
5535 } else if (PType->isFunctionType())
5536 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005537 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005538 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5539 S, true /*Extended*/);
5540 else
5541 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005542 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005543 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005544 }
John McCall351762c2011-02-07 10:33:21 +00005545
5546 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005547}
5548
Douglas Gregora9d84932011-05-27 01:19:52 +00005549bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005550 std::string& S) {
5551 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005552 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005553 CharUnits ParmOffset;
5554 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005555 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005556 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005557 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005558 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005559 continue;
5560
David Chisnall50e4eba2010-12-30 14:05:53 +00005561 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005562 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005563 ParmOffset += sz;
5564 }
5565 S += charUnitsToString(ParmOffset);
5566 ParmOffset = CharUnits::Zero();
5567
5568 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005569 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005570 QualType PType = PVDecl->getOriginalType();
5571 if (const ArrayType *AT =
5572 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5573 // Use array's original type only if it has known number of
5574 // elements.
5575 if (!isa<ConstantArrayType>(AT))
5576 PType = PVDecl->getType();
5577 } else if (PType->isFunctionType())
5578 PType = PVDecl->getType();
5579 getObjCEncodingForType(PType, S);
5580 S += charUnitsToString(ParmOffset);
5581 ParmOffset += getObjCEncodingTypeSize(PType);
5582 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005583
5584 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005585}
5586
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005587/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5588/// method parameter or return type. If Extended, include class names and
5589/// block object types.
5590void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5591 QualType T, std::string& S,
5592 bool Extended) const {
5593 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5594 getObjCEncodingForTypeQualifier(QT, S);
5595 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005596 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005597 true /*OutermostType*/,
5598 false /*EncodingProperty*/,
5599 false /*StructField*/,
5600 Extended /*EncodeBlockParameters*/,
5601 Extended /*EncodeClassNames*/);
5602}
5603
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005604/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005605/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005606bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005607 std::string& S,
5608 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005609 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005610 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005611 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5612 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005613 // Compute size of all parameters.
5614 // Start with computing size of a pointer in number of bytes.
5615 // FIXME: There might(should) be a better way of doing this computation!
5616 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005617 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005618 // The first two arguments (self and _cmd) are pointers; account for
5619 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005620 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005621 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005622 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005623 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005624 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005625 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005626 continue;
5627
Ken Dyck40775002010-01-11 17:06:35 +00005628 assert (sz.isPositive() &&
5629 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005630 ParmOffset += sz;
5631 }
Ken Dyck40775002010-01-11 17:06:35 +00005632 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005633 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005634 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005635
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005636 // Argument types.
5637 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005638 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005639 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005640 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005641 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005642 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005643 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5644 // Use array's original type only if it has known number of
5645 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005646 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005647 PType = PVDecl->getType();
5648 } else if (PType->isFunctionType())
5649 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005650 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5651 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005652 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005653 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005654 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005655
5656 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005657}
5658
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005659ObjCPropertyImplDecl *
5660ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5661 const ObjCPropertyDecl *PD,
5662 const Decl *Container) const {
5663 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005664 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005665 if (const ObjCCategoryImplDecl *CID =
5666 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005667 for (auto *PID : CID->property_impls())
5668 if (PID->getPropertyDecl() == PD)
5669 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005670 } else {
5671 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5672 for (auto *PID : OID->property_impls())
5673 if (PID->getPropertyDecl() == PD)
5674 return PID;
5675 }
5676 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005677}
5678
Daniel Dunbar4932b362008-08-28 04:38:10 +00005679/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005680/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005681/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5682/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005683/// Property attributes are stored as a comma-delimited C string. The simple
5684/// attributes readonly and bycopy are encoded as single characters. The
5685/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5686/// encoded as single characters, followed by an identifier. Property types
5687/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005688/// these attributes are defined by the following enumeration:
5689/// @code
5690/// enum PropertyAttributes {
5691/// kPropertyReadOnly = 'R', // property is read-only.
5692/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5693/// kPropertyByref = '&', // property is a reference to the value last assigned
5694/// kPropertyDynamic = 'D', // property is dynamic
5695/// kPropertyGetter = 'G', // followed by getter selector name
5696/// kPropertySetter = 'S', // followed by setter selector name
5697/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005698/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005699/// kPropertyWeak = 'W' // 'weak' property
5700/// kPropertyStrong = 'P' // property GC'able
5701/// kPropertyNonAtomic = 'N' // property non-atomic
5702/// };
5703/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005704void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005705 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005706 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005707 // Collect information from the property implementation decl(s).
5708 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005709 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005710
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005711 if (ObjCPropertyImplDecl *PropertyImpDecl =
5712 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5713 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5714 Dynamic = true;
5715 else
5716 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005717 }
5718
5719 // FIXME: This is not very efficient.
5720 S = "T";
5721
5722 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005723 // GCC has some special rules regarding encoding of properties which
5724 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005725 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005726
5727 if (PD->isReadOnly()) {
5728 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005729 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5730 S += ",C";
5731 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5732 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005733 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5734 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005735 } else {
5736 switch (PD->getSetterKind()) {
5737 case ObjCPropertyDecl::Assign: break;
5738 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005739 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005740 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005741 }
5742 }
5743
5744 // It really isn't clear at all what this means, since properties
5745 // are "dynamic by default".
5746 if (Dynamic)
5747 S += ",D";
5748
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005749 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5750 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005751
Daniel Dunbar4932b362008-08-28 04:38:10 +00005752 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5753 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005754 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005755 }
5756
5757 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5758 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005759 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005760 }
5761
5762 if (SynthesizePID) {
5763 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5764 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005765 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005766 }
5767
5768 // FIXME: OBJCGC: weak & strong
5769}
5770
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005771/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005772/// Another legacy compatibility encoding: 32-bit longs are encoded as
5773/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005774/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5775///
5776void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005777 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005778 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005779 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005780 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005781 else
Jay Foad39c79802011-01-12 09:06:06 +00005782 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005783 PointeeTy = IntTy;
5784 }
5785 }
5786}
5787
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005788void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005789 const FieldDecl *Field,
5790 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005791 // We follow the behavior of gcc, expanding structures which are
5792 // directly pointed to, and expanding embedded structures. Note that
5793 // these rules are sufficient to prevent recursive encoding of the
5794 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005795 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005796 true /* outermost type */, false, false,
5797 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005798}
5799
Joe Groff98ac7d22014-07-07 22:25:15 +00005800void ASTContext::getObjCEncodingForPropertyType(QualType T,
5801 std::string& S) const {
5802 // Encode result type.
5803 // GCC has some special rules regarding encoding of properties which
5804 // closely resembles encoding of ivars.
5805 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5806 true /* outermost type */,
5807 true /* encoding property */);
5808}
5809
John McCall393a78d2012-12-20 02:45:14 +00005810static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5811 BuiltinType::Kind kind) {
5812 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005813 case BuiltinType::Void: return 'v';
5814 case BuiltinType::Bool: return 'B';
5815 case BuiltinType::Char_U:
5816 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005817 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005818 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005819 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005820 case BuiltinType::UInt: return 'I';
5821 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005822 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005823 case BuiltinType::UInt128: return 'T';
5824 case BuiltinType::ULongLong: return 'Q';
5825 case BuiltinType::Char_S:
5826 case BuiltinType::SChar: return 'c';
5827 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005828 case BuiltinType::WChar_S:
5829 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005830 case BuiltinType::Int: return 'i';
5831 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005832 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005833 case BuiltinType::LongLong: return 'q';
5834 case BuiltinType::Int128: return 't';
5835 case BuiltinType::Float: return 'f';
5836 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005837 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005838 case BuiltinType::NullPtr: return '*'; // like char*
5839
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005840 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005841 case BuiltinType::Half:
5842 // FIXME: potentially need @encodes for these!
5843 return ' ';
5844
5845 case BuiltinType::ObjCId:
5846 case BuiltinType::ObjCClass:
5847 case BuiltinType::ObjCSel:
5848 llvm_unreachable("@encoding ObjC primitive type");
5849
5850 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005851#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5852 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005853#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005854 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005855 case BuiltinType::OCLClkEvent:
5856 case BuiltinType::OCLQueue:
5857 case BuiltinType::OCLNDRange:
5858 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005859 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005860 case BuiltinType::Dependent:
5861#define BUILTIN_TYPE(KIND, ID)
5862#define PLACEHOLDER_TYPE(KIND, ID) \
5863 case BuiltinType::KIND:
5864#include "clang/AST/BuiltinTypes.def"
5865 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005866 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005867 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005868}
5869
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005870static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5871 EnumDecl *Enum = ET->getDecl();
5872
5873 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5874 if (!Enum->isFixed())
5875 return 'i';
5876
5877 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005878 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5879 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005880}
5881
Jay Foad39c79802011-01-12 09:06:06 +00005882static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005883 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005884 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005885 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005886 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5887 // The GNU runtime requires more information; bitfields are encoded as b,
5888 // then the offset (in bits) of the first element, then the type of the
5889 // bitfield, then the size in bits. For example, in this structure:
5890 //
5891 // struct
5892 // {
5893 // int integer;
5894 // int flags:2;
5895 // };
5896 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5897 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5898 // information is not especially sensible, but we're stuck with it for
5899 // compatibility with GCC, although providing it breaks anything that
5900 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005901 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005902 const RecordDecl *RD = FD->getParent();
5903 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005904 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005905 if (const EnumType *ET = T->getAs<EnumType>())
5906 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005907 else {
5908 const BuiltinType *BT = T->castAs<BuiltinType>();
5909 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5910 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005911 }
Richard Smithcaf33902011-10-10 18:28:20 +00005912 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005913}
5914
Daniel Dunbar07d07852009-10-18 21:17:35 +00005915// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005916void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5917 bool ExpandPointedToStructures,
5918 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005919 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005920 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005921 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005922 bool StructField,
5923 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005924 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005925 bool EncodePointerToObjCTypedef,
5926 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005927 CanQualType CT = getCanonicalType(T);
5928 switch (CT->getTypeClass()) {
5929 case Type::Builtin:
5930 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005931 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005932 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005933 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5934 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5935 else
5936 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005937 return;
Mike Stump11289f42009-09-09 15:08:12 +00005938
John McCall393a78d2012-12-20 02:45:14 +00005939 case Type::Complex: {
5940 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005941 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005942 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005943 return;
5944 }
John McCall393a78d2012-12-20 02:45:14 +00005945
5946 case Type::Atomic: {
5947 const AtomicType *AT = T->castAs<AtomicType>();
5948 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005949 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005950 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005951 }
John McCall393a78d2012-12-20 02:45:14 +00005952
5953 // encoding for pointer or reference types.
5954 case Type::Pointer:
5955 case Type::LValueReference:
5956 case Type::RValueReference: {
5957 QualType PointeeTy;
5958 if (isa<PointerType>(CT)) {
5959 const PointerType *PT = T->castAs<PointerType>();
5960 if (PT->isObjCSelType()) {
5961 S += ':';
5962 return;
5963 }
5964 PointeeTy = PT->getPointeeType();
5965 } else {
5966 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5967 }
5968
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005969 bool isReadOnly = false;
5970 // For historical/compatibility reasons, the read-only qualifier of the
5971 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5972 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005973 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005974 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005975 if (OutermostType && T.isConstQualified()) {
5976 isReadOnly = true;
5977 S += 'r';
5978 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005979 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005980 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005981 while (P->getAs<PointerType>())
5982 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005983 if (P.isConstQualified()) {
5984 isReadOnly = true;
5985 S += 'r';
5986 }
5987 }
5988 if (isReadOnly) {
5989 // Another legacy compatibility encoding. Some ObjC qualifier and type
5990 // combinations need to be rearranged.
5991 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005992 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005993 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005994 }
Mike Stump11289f42009-09-09 15:08:12 +00005995
Anders Carlssond8499822007-10-29 05:01:08 +00005996 if (PointeeTy->isCharType()) {
5997 // char pointer types should be encoded as '*' unless it is a
5998 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005999 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006000 S += '*';
6001 return;
6002 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006003 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006004 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6005 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6006 S += '#';
6007 return;
6008 }
6009 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6010 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6011 S += '@';
6012 return;
6013 }
6014 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006015 }
Anders Carlssond8499822007-10-29 05:01:08 +00006016 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006017 getLegacyIntegralTypeEncoding(PointeeTy);
6018
Mike Stump11289f42009-09-09 15:08:12 +00006019 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006020 nullptr, false, false, false, false, false, false,
6021 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006022 return;
6023 }
John McCall393a78d2012-12-20 02:45:14 +00006024
6025 case Type::ConstantArray:
6026 case Type::IncompleteArray:
6027 case Type::VariableArray: {
6028 const ArrayType *AT = cast<ArrayType>(CT);
6029
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006030 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006031 // Incomplete arrays are encoded as a pointer to the array element.
6032 S += '^';
6033
Mike Stump11289f42009-09-09 15:08:12 +00006034 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006035 false, ExpandStructures, FD);
6036 } else {
6037 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006038
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006039 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6040 S += llvm::utostr(CAT->getSize().getZExtValue());
6041 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006042 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006043 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6044 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006045 S += '0';
6046 }
Mike Stump11289f42009-09-09 15:08:12 +00006047
6048 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006049 false, ExpandStructures, FD,
6050 false, false, false, false, false, false,
6051 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006052 S += ']';
6053 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006054 return;
6055 }
Mike Stump11289f42009-09-09 15:08:12 +00006056
John McCall393a78d2012-12-20 02:45:14 +00006057 case Type::FunctionNoProto:
6058 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006059 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006060 return;
Mike Stump11289f42009-09-09 15:08:12 +00006061
John McCall393a78d2012-12-20 02:45:14 +00006062 case Type::Record: {
6063 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006064 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006065 // Anonymous structures print as '?'
6066 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6067 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006068 if (ClassTemplateSpecializationDecl *Spec
6069 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6070 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006071 llvm::raw_string_ostream OS(S);
6072 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006073 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006074 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006075 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006076 } else {
6077 S += '?';
6078 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006079 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006080 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006081 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006082 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006083 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006084 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006085 if (FD) {
6086 S += '"';
6087 S += Field->getNameAsString();
6088 S += '"';
6089 }
Mike Stump11289f42009-09-09 15:08:12 +00006090
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006091 // Special case bit-fields.
6092 if (Field->isBitField()) {
6093 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006094 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006095 } else {
6096 QualType qt = Field->getType();
6097 getLegacyIntegralTypeEncoding(qt);
6098 getObjCEncodingForTypeImpl(qt, S, false, true,
6099 FD, /*OutermostType*/false,
6100 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006101 /*StructField*/true,
6102 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006103 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006104 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006105 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006106 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006107 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006108 return;
6109 }
Mike Stump11289f42009-09-09 15:08:12 +00006110
John McCall393a78d2012-12-20 02:45:14 +00006111 case Type::BlockPointer: {
6112 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006113 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006114 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006115 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006116
6117 S += '<';
6118 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006119 getObjCEncodingForTypeImpl(
6120 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6121 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006122 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6123 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006124 // Block self
6125 S += "@?";
6126 // Block parameters
6127 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006128 for (const auto &I : FPT->param_types())
6129 getObjCEncodingForTypeImpl(
6130 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6131 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006132 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6133 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006134 }
6135 S += '>';
6136 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006137 return;
6138 }
Mike Stump11289f42009-09-09 15:08:12 +00006139
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006140 case Type::ObjCObject: {
6141 // hack to match legacy encoding of *id and *Class
6142 QualType Ty = getObjCObjectPointerType(CT);
6143 if (Ty->isObjCIdType()) {
6144 S += "{objc_object=}";
6145 return;
6146 }
6147 else if (Ty->isObjCClassType()) {
6148 S += "{objc_class=}";
6149 return;
6150 }
6151 }
6152
John McCall393a78d2012-12-20 02:45:14 +00006153 case Type::ObjCInterface: {
6154 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006155 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006156 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006157 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006158 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006159 if (ExpandStructures) {
6160 S += '=';
6161 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6162 DeepCollectObjCIvars(OI, true, Ivars);
6163 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6164 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6165 if (Field->isBitField())
6166 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6167 else
6168 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6169 false, false, false, false, false,
6170 EncodePointerToObjCTypedef,
6171 NotEncodedT);
6172 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006173 }
6174 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006175 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006176 }
Mike Stump11289f42009-09-09 15:08:12 +00006177
John McCall393a78d2012-12-20 02:45:14 +00006178 case Type::ObjCObjectPointer: {
6179 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006180 if (OPT->isObjCIdType()) {
6181 S += '@';
6182 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006183 }
Mike Stump11289f42009-09-09 15:08:12 +00006184
Steve Narofff0c86112009-10-28 22:03:49 +00006185 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6186 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6187 // Since this is a binary compatibility issue, need to consult with runtime
6188 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006189 S += '#';
6190 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006191 }
Mike Stump11289f42009-09-09 15:08:12 +00006192
Chris Lattnere7cabb92009-07-13 00:10:46 +00006193 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006194 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006195 ExpandPointedToStructures,
6196 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006197 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006198 // Note that we do extended encoding of protocol qualifer list
6199 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006200 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006201 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006202 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006203 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006204 S += '>';
6205 }
6206 S += '"';
6207 }
6208 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006209 }
Mike Stump11289f42009-09-09 15:08:12 +00006210
Chris Lattnere7cabb92009-07-13 00:10:46 +00006211 QualType PointeeTy = OPT->getPointeeType();
6212 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006213 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6214 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006215 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006216 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006217 // {...};
6218 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006219 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006220 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006221 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6222 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6223 DeepCollectObjCIvars(OI, true, Ivars);
6224 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6225 if (cast<FieldDecl>(Ivars[i]) == FD) {
6226 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006227 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006228 S += '}';
6229 return;
6230 }
6231 }
6232 }
Mike Stump11289f42009-09-09 15:08:12 +00006233 getObjCEncodingForTypeImpl(PointeeTy, S,
6234 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006235 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006236 false, false, false, false, false,
6237 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006238 return;
6239 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006240
6241 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006242 if (OPT->getInterfaceDecl() &&
6243 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006244 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006245 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006246 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006247 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006248 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006249 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006250 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006251 S += '"';
6252 }
6253 return;
6254 }
Mike Stump11289f42009-09-09 15:08:12 +00006255
John McCalla9e6e8d2010-05-17 23:56:34 +00006256 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006257 // FIXME: we shoul do better than that. 'M' is available.
6258 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006259 // This matches gcc's encoding, even though technically it is insufficient.
6260 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006261 case Type::Vector:
6262 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006263 // Until we have a coherent encoding of these three types, issue warning.
6264 { if (NotEncodedT)
6265 *NotEncodedT = T;
6266 return;
6267 }
6268
6269 // We could see an undeduced auto type here during error recovery.
6270 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006271 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00006272 return;
6273
Xiuli Pan9c14e282016-01-09 12:53:17 +00006274 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006275#define ABSTRACT_TYPE(KIND, BASE)
6276#define TYPE(KIND, BASE)
6277#define DEPENDENT_TYPE(KIND, BASE) \
6278 case Type::KIND:
6279#define NON_CANONICAL_TYPE(KIND, BASE) \
6280 case Type::KIND:
6281#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6282 case Type::KIND:
6283#include "clang/AST/TypeNodes.def"
6284 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006285 }
John McCall393a78d2012-12-20 02:45:14 +00006286 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006287}
6288
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006289void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6290 std::string &S,
6291 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006292 bool includeVBases,
6293 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006294 assert(RDecl && "Expected non-null RecordDecl");
6295 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006296 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006297 return;
6298
6299 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6300 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6301 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6302
6303 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006304 for (const auto &BI : CXXRec->bases()) {
6305 if (!BI.isVirtual()) {
6306 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006307 if (base->isEmpty())
6308 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006309 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006310 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6311 std::make_pair(offs, base));
6312 }
6313 }
6314 }
6315
6316 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006317 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006318 uint64_t offs = layout.getFieldOffset(i);
6319 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006320 std::make_pair(offs, Field));
6321 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006322 }
6323
6324 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006325 for (const auto &BI : CXXRec->vbases()) {
6326 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006327 if (base->isEmpty())
6328 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006329 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006330 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6331 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006332 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6333 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006334 }
6335 }
6336
6337 CharUnits size;
6338 if (CXXRec) {
6339 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6340 } else {
6341 size = layout.getSize();
6342 }
6343
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006344#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006345 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006346#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006347 std::multimap<uint64_t, NamedDecl *>::iterator
6348 CurLayObj = FieldOrBaseOffsets.begin();
6349
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006350 if (CXXRec && CXXRec->isDynamicClass() &&
6351 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006352 if (FD) {
6353 S += "\"_vptr$";
6354 std::string recname = CXXRec->getNameAsString();
6355 if (recname.empty()) recname = "?";
6356 S += recname;
6357 S += '"';
6358 }
6359 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006360#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006361 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006362#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006363 }
6364
6365 if (!RDecl->hasFlexibleArrayMember()) {
6366 // Mark the end of the structure.
6367 uint64_t offs = toBits(size);
6368 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006369 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006370 }
6371
6372 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006373#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006374 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006375 if (CurOffs < CurLayObj->first) {
6376 uint64_t padding = CurLayObj->first - CurOffs;
6377 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6378 // packing/alignment of members is different that normal, in which case
6379 // the encoding will be out-of-sync with the real layout.
6380 // If the runtime switches to just consider the size of types without
6381 // taking into account alignment, we could make padding explicit in the
6382 // encoding (e.g. using arrays of chars). The encoding strings would be
6383 // longer then though.
6384 CurOffs += padding;
6385 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006386#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006387
6388 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006389 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006390 break; // reached end of structure.
6391
6392 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6393 // We expand the bases without their virtual bases since those are going
6394 // in the initial structure. Note that this differs from gcc which
6395 // expands virtual bases each time one is encountered in the hierarchy,
6396 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006397 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6398 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006399 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006400#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006401 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006402#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006403 } else {
6404 FieldDecl *field = cast<FieldDecl>(dcl);
6405 if (FD) {
6406 S += '"';
6407 S += field->getNameAsString();
6408 S += '"';
6409 }
6410
6411 if (field->isBitField()) {
6412 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006413#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006414 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006415#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006416 } else {
6417 QualType qt = field->getType();
6418 getLegacyIntegralTypeEncoding(qt);
6419 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6420 /*OutermostType*/false,
6421 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006422 /*StructField*/true,
6423 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006424#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006425 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006426#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006427 }
6428 }
6429 }
6430}
6431
Mike Stump11289f42009-09-09 15:08:12 +00006432void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006433 std::string& S) const {
6434 if (QT & Decl::OBJC_TQ_In)
6435 S += 'n';
6436 if (QT & Decl::OBJC_TQ_Inout)
6437 S += 'N';
6438 if (QT & Decl::OBJC_TQ_Out)
6439 S += 'o';
6440 if (QT & Decl::OBJC_TQ_Bycopy)
6441 S += 'O';
6442 if (QT & Decl::OBJC_TQ_Byref)
6443 S += 'R';
6444 if (QT & Decl::OBJC_TQ_Oneway)
6445 S += 'V';
6446}
6447
Douglas Gregor3ea72692011-08-12 05:46:01 +00006448TypedefDecl *ASTContext::getObjCIdDecl() const {
6449 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006450 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006451 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006452 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006453 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006454 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006455}
6456
Douglas Gregor52e02802011-08-12 06:17:30 +00006457TypedefDecl *ASTContext::getObjCSelDecl() const {
6458 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006459 QualType T = getPointerType(ObjCBuiltinSelTy);
6460 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006461 }
6462 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006463}
6464
Douglas Gregor0a586182011-08-12 05:59:41 +00006465TypedefDecl *ASTContext::getObjCClassDecl() const {
6466 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006467 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006468 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006469 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006470 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006471 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006472}
6473
Douglas Gregord53ae832012-01-17 18:09:05 +00006474ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6475 if (!ObjCProtocolClassDecl) {
6476 ObjCProtocolClassDecl
6477 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6478 SourceLocation(),
6479 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006480 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006481 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006482 SourceLocation(), true);
6483 }
6484
6485 return ObjCProtocolClassDecl;
6486}
6487
Meador Inge5d3fb222012-06-16 03:34:49 +00006488//===----------------------------------------------------------------------===//
6489// __builtin_va_list Construction Functions
6490//===----------------------------------------------------------------------===//
6491
Charles Davisc7d5c942015-09-17 20:55:33 +00006492static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6493 StringRef Name) {
6494 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006495 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006496 return Context->buildImplicitTypedef(T, Name);
6497}
6498
6499static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6500 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6501}
6502
6503static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6504 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006505}
6506
6507static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6508 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006509 QualType T = Context->getPointerType(Context->VoidTy);
6510 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006511}
6512
Tim Northover9bb857a2013-01-31 12:13:10 +00006513static TypedefDecl *
6514CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006515 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006516 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006517 if (Context->getLangOpts().CPlusPlus) {
6518 // namespace std { struct __va_list {
6519 NamespaceDecl *NS;
6520 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6521 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006522 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006523 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006524 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006525 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006526 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006527 }
6528
6529 VaListTagDecl->startDefinition();
6530
6531 const size_t NumFields = 5;
6532 QualType FieldTypes[NumFields];
6533 const char *FieldNames[NumFields];
6534
6535 // void *__stack;
6536 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6537 FieldNames[0] = "__stack";
6538
6539 // void *__gr_top;
6540 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6541 FieldNames[1] = "__gr_top";
6542
6543 // void *__vr_top;
6544 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6545 FieldNames[2] = "__vr_top";
6546
6547 // int __gr_offs;
6548 FieldTypes[3] = Context->IntTy;
6549 FieldNames[3] = "__gr_offs";
6550
6551 // int __vr_offs;
6552 FieldTypes[4] = Context->IntTy;
6553 FieldNames[4] = "__vr_offs";
6554
6555 // Create fields
6556 for (unsigned i = 0; i < NumFields; ++i) {
6557 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6558 VaListTagDecl,
6559 SourceLocation(),
6560 SourceLocation(),
6561 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006562 FieldTypes[i], /*TInfo=*/nullptr,
6563 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006564 /*Mutable=*/false,
6565 ICIS_NoInit);
6566 Field->setAccess(AS_public);
6567 VaListTagDecl->addDecl(Field);
6568 }
6569 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006570 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006571 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006572
6573 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006574 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006575}
6576
Meador Inge5d3fb222012-06-16 03:34:49 +00006577static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6578 // typedef struct __va_list_tag {
6579 RecordDecl *VaListTagDecl;
6580
Alp Toker2dea15b2013-12-17 01:22:38 +00006581 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006582 VaListTagDecl->startDefinition();
6583
6584 const size_t NumFields = 5;
6585 QualType FieldTypes[NumFields];
6586 const char *FieldNames[NumFields];
6587
6588 // unsigned char gpr;
6589 FieldTypes[0] = Context->UnsignedCharTy;
6590 FieldNames[0] = "gpr";
6591
6592 // unsigned char fpr;
6593 FieldTypes[1] = Context->UnsignedCharTy;
6594 FieldNames[1] = "fpr";
6595
6596 // unsigned short reserved;
6597 FieldTypes[2] = Context->UnsignedShortTy;
6598 FieldNames[2] = "reserved";
6599
6600 // void* overflow_arg_area;
6601 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6602 FieldNames[3] = "overflow_arg_area";
6603
6604 // void* reg_save_area;
6605 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6606 FieldNames[4] = "reg_save_area";
6607
6608 // Create fields
6609 for (unsigned i = 0; i < NumFields; ++i) {
6610 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6611 SourceLocation(),
6612 SourceLocation(),
6613 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006614 FieldTypes[i], /*TInfo=*/nullptr,
6615 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006616 /*Mutable=*/false,
6617 ICIS_NoInit);
6618 Field->setAccess(AS_public);
6619 VaListTagDecl->addDecl(Field);
6620 }
6621 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006622 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006623 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6624
6625 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006626 TypedefDecl *VaListTagTypedefDecl =
6627 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6628
Meador Inge5d3fb222012-06-16 03:34:49 +00006629 QualType VaListTagTypedefType =
6630 Context->getTypedefType(VaListTagTypedefDecl);
6631
6632 // typedef __va_list_tag __builtin_va_list[1];
6633 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6634 QualType VaListTagArrayType
6635 = Context->getConstantArrayType(VaListTagTypedefType,
6636 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006637 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006638}
6639
6640static TypedefDecl *
6641CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006642 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006643 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006644 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006645 VaListTagDecl->startDefinition();
6646
6647 const size_t NumFields = 4;
6648 QualType FieldTypes[NumFields];
6649 const char *FieldNames[NumFields];
6650
6651 // unsigned gp_offset;
6652 FieldTypes[0] = Context->UnsignedIntTy;
6653 FieldNames[0] = "gp_offset";
6654
6655 // unsigned fp_offset;
6656 FieldTypes[1] = Context->UnsignedIntTy;
6657 FieldNames[1] = "fp_offset";
6658
6659 // void* overflow_arg_area;
6660 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6661 FieldNames[2] = "overflow_arg_area";
6662
6663 // void* reg_save_area;
6664 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6665 FieldNames[3] = "reg_save_area";
6666
6667 // Create fields
6668 for (unsigned i = 0; i < NumFields; ++i) {
6669 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6670 VaListTagDecl,
6671 SourceLocation(),
6672 SourceLocation(),
6673 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006674 FieldTypes[i], /*TInfo=*/nullptr,
6675 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006676 /*Mutable=*/false,
6677 ICIS_NoInit);
6678 Field->setAccess(AS_public);
6679 VaListTagDecl->addDecl(Field);
6680 }
6681 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006682 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006683 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6684
Richard Smith9b88a4c2015-07-27 05:40:23 +00006685 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006686
Richard Smith9b88a4c2015-07-27 05:40:23 +00006687 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006688 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006689 QualType VaListTagArrayType =
6690 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006691 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006692}
6693
6694static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6695 // typedef int __builtin_va_list[4];
6696 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006697 QualType IntArrayType =
6698 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006699 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006700}
6701
Logan Chien57086ce2012-10-10 06:56:20 +00006702static TypedefDecl *
6703CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006704 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006705 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006706 if (Context->getLangOpts().CPlusPlus) {
6707 // namespace std { struct __va_list {
6708 NamespaceDecl *NS;
6709 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6710 Context->getTranslationUnitDecl(),
6711 /*Inline*/false, SourceLocation(),
6712 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006713 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006714 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006715 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006716 }
6717
6718 VaListDecl->startDefinition();
6719
6720 // void * __ap;
6721 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6722 VaListDecl,
6723 SourceLocation(),
6724 SourceLocation(),
6725 &Context->Idents.get("__ap"),
6726 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006727 /*TInfo=*/nullptr,
6728 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006729 /*Mutable=*/false,
6730 ICIS_NoInit);
6731 Field->setAccess(AS_public);
6732 VaListDecl->addDecl(Field);
6733
6734 // };
6735 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006736 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006737
6738 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006739 QualType T = Context->getRecordType(VaListDecl);
6740 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006741}
6742
Ulrich Weigand47445072013-05-06 16:26:41 +00006743static TypedefDecl *
6744CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006745 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006746 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006747 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006748 VaListTagDecl->startDefinition();
6749
6750 const size_t NumFields = 4;
6751 QualType FieldTypes[NumFields];
6752 const char *FieldNames[NumFields];
6753
6754 // long __gpr;
6755 FieldTypes[0] = Context->LongTy;
6756 FieldNames[0] = "__gpr";
6757
6758 // long __fpr;
6759 FieldTypes[1] = Context->LongTy;
6760 FieldNames[1] = "__fpr";
6761
6762 // void *__overflow_arg_area;
6763 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6764 FieldNames[2] = "__overflow_arg_area";
6765
6766 // void *__reg_save_area;
6767 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6768 FieldNames[3] = "__reg_save_area";
6769
6770 // Create fields
6771 for (unsigned i = 0; i < NumFields; ++i) {
6772 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6773 VaListTagDecl,
6774 SourceLocation(),
6775 SourceLocation(),
6776 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006777 FieldTypes[i], /*TInfo=*/nullptr,
6778 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006779 /*Mutable=*/false,
6780 ICIS_NoInit);
6781 Field->setAccess(AS_public);
6782 VaListTagDecl->addDecl(Field);
6783 }
6784 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006785 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006786 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006787
Richard Smith9b88a4c2015-07-27 05:40:23 +00006788 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006789
6790 // typedef __va_list_tag __builtin_va_list[1];
6791 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006792 QualType VaListTagArrayType =
6793 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006794
Alp Toker56b5cc92013-12-15 10:36:26 +00006795 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006796}
6797
Meador Inge5d3fb222012-06-16 03:34:49 +00006798static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6799 TargetInfo::BuiltinVaListKind Kind) {
6800 switch (Kind) {
6801 case TargetInfo::CharPtrBuiltinVaList:
6802 return CreateCharPtrBuiltinVaListDecl(Context);
6803 case TargetInfo::VoidPtrBuiltinVaList:
6804 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006805 case TargetInfo::AArch64ABIBuiltinVaList:
6806 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006807 case TargetInfo::PowerABIBuiltinVaList:
6808 return CreatePowerABIBuiltinVaListDecl(Context);
6809 case TargetInfo::X86_64ABIBuiltinVaList:
6810 return CreateX86_64ABIBuiltinVaListDecl(Context);
6811 case TargetInfo::PNaClABIBuiltinVaList:
6812 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006813 case TargetInfo::AAPCSABIBuiltinVaList:
6814 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006815 case TargetInfo::SystemZBuiltinVaList:
6816 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006817 }
6818
6819 llvm_unreachable("Unhandled __builtin_va_list type kind");
6820}
6821
6822TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006823 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006824 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006825 assert(BuiltinVaListDecl->isImplicit());
6826 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006827
6828 return BuiltinVaListDecl;
6829}
6830
Richard Smith9b88a4c2015-07-27 05:40:23 +00006831Decl *ASTContext::getVaListTagDecl() const {
6832 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006833 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006834 if (!VaListTagDecl)
6835 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006836
Richard Smith9b88a4c2015-07-27 05:40:23 +00006837 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006838}
6839
Charles Davisc7d5c942015-09-17 20:55:33 +00006840TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6841 if (!BuiltinMSVaListDecl)
6842 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6843
6844 return BuiltinMSVaListDecl;
6845}
6846
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006847void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006848 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006849 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006850
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006851 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006852}
6853
John McCalld28ae272009-12-02 08:04:21 +00006854/// \brief Retrieve the template name that corresponds to a non-empty
6855/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006856TemplateName
6857ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6858 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006859 unsigned size = End - Begin;
6860 assert(size > 1 && "set is not overloaded!");
6861
6862 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6863 size * sizeof(FunctionTemplateDecl*));
6864 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6865
6866 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006867 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006868 NamedDecl *D = *I;
6869 assert(isa<FunctionTemplateDecl>(D) ||
6870 (isa<UsingShadowDecl>(D) &&
6871 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6872 *Storage++ = D;
6873 }
6874
6875 return TemplateName(OT);
6876}
6877
Douglas Gregordc572a32009-03-30 22:58:21 +00006878/// \brief Retrieve the template name that represents a qualified
6879/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006880TemplateName
6881ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6882 bool TemplateKeyword,
6883 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006884 assert(NNS && "Missing nested-name-specifier in qualified template name");
6885
Douglas Gregorc42075a2010-02-04 18:10:26 +00006886 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006887 llvm::FoldingSetNodeID ID;
6888 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6889
Craig Topper36250ad2014-05-12 05:36:57 +00006890 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006891 QualifiedTemplateName *QTN =
6892 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6893 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006894 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006895 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006896 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6897 }
6898
6899 return TemplateName(QTN);
6900}
6901
6902/// \brief Retrieve the template name that represents a dependent
6903/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006904TemplateName
6905ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6906 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006907 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006908 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006909
6910 llvm::FoldingSetNodeID ID;
6911 DependentTemplateName::Profile(ID, NNS, Name);
6912
Craig Topper36250ad2014-05-12 05:36:57 +00006913 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006914 DependentTemplateName *QTN =
6915 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6916
6917 if (QTN)
6918 return TemplateName(QTN);
6919
6920 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6921 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006922 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006923 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006924 } else {
6925 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006926 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006927 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006928 DependentTemplateName *CheckQTN =
6929 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6930 assert(!CheckQTN && "Dependent type name canonicalization broken");
6931 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006932 }
6933
6934 DependentTemplateNames.InsertNode(QTN, InsertPos);
6935 return TemplateName(QTN);
6936}
6937
Douglas Gregor71395fa2009-11-04 00:56:37 +00006938/// \brief Retrieve the template name that represents a dependent
6939/// template name such as \c MetaFun::template operator+.
6940TemplateName
6941ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006942 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006943 assert((!NNS || NNS->isDependent()) &&
6944 "Nested name specifier must be dependent");
6945
6946 llvm::FoldingSetNodeID ID;
6947 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006948
6949 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006950 DependentTemplateName *QTN
6951 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006952
6953 if (QTN)
6954 return TemplateName(QTN);
6955
6956 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6957 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006958 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006959 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006960 } else {
6961 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006962 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006963 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006964
Douglas Gregorc42075a2010-02-04 18:10:26 +00006965 DependentTemplateName *CheckQTN
6966 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6967 assert(!CheckQTN && "Dependent template name canonicalization broken");
6968 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006969 }
6970
6971 DependentTemplateNames.InsertNode(QTN, InsertPos);
6972 return TemplateName(QTN);
6973}
6974
Douglas Gregor5590be02011-01-15 06:45:20 +00006975TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006976ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6977 TemplateName replacement) const {
6978 llvm::FoldingSetNodeID ID;
6979 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006980
6981 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006982 SubstTemplateTemplateParmStorage *subst
6983 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6984
6985 if (!subst) {
6986 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6987 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6988 }
6989
6990 return TemplateName(subst);
6991}
6992
6993TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006994ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6995 const TemplateArgument &ArgPack) const {
6996 ASTContext &Self = const_cast<ASTContext &>(*this);
6997 llvm::FoldingSetNodeID ID;
6998 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006999
7000 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007001 SubstTemplateTemplateParmPackStorage *Subst
7002 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7003
7004 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007005 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007006 ArgPack.pack_size(),
7007 ArgPack.pack_begin());
7008 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7009 }
7010
7011 return TemplateName(Subst);
7012}
7013
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007014/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007015/// TargetInfo, produce the corresponding type. The unsigned @p Type
7016/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007017CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007018 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007019 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007020 case TargetInfo::SignedChar: return SignedCharTy;
7021 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007022 case TargetInfo::SignedShort: return ShortTy;
7023 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7024 case TargetInfo::SignedInt: return IntTy;
7025 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7026 case TargetInfo::SignedLong: return LongTy;
7027 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7028 case TargetInfo::SignedLongLong: return LongLongTy;
7029 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7030 }
7031
David Blaikie83d382b2011-09-23 05:06:16 +00007032 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007033}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007034
7035//===----------------------------------------------------------------------===//
7036// Type Predicates.
7037//===----------------------------------------------------------------------===//
7038
Fariborz Jahanian96207692009-02-18 21:49:28 +00007039/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7040/// garbage collection attribute.
7041///
John McCall553d45a2011-01-12 00:34:59 +00007042Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007043 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007044 return Qualifiers::GCNone;
7045
David Blaikiebbafb8a2012-03-11 07:00:24 +00007046 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007047 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7048
7049 // Default behaviour under objective-C's gc is for ObjC pointers
7050 // (or pointers to them) be treated as though they were declared
7051 // as __strong.
7052 if (GCAttrs == Qualifiers::GCNone) {
7053 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7054 return Qualifiers::Strong;
7055 else if (Ty->isPointerType())
7056 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7057 } else {
7058 // It's not valid to set GC attributes on anything that isn't a
7059 // pointer.
7060#ifndef NDEBUG
7061 QualType CT = Ty->getCanonicalTypeInternal();
7062 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7063 CT = AT->getElementType();
7064 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7065#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007066 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007067 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007068}
7069
Chris Lattner49af6a42008-04-07 06:51:04 +00007070//===----------------------------------------------------------------------===//
7071// Type Compatibility Testing
7072//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007073
Mike Stump11289f42009-09-09 15:08:12 +00007074/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007075/// compatible.
7076static bool areCompatVectorTypes(const VectorType *LHS,
7077 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007078 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007079 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007080 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007081}
7082
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007083bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7084 QualType SecondVec) {
7085 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7086 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7087
7088 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7089 return true;
7090
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007091 // Treat Neon vector types and most AltiVec vector types as if they are the
7092 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007093 const VectorType *First = FirstVec->getAs<VectorType>();
7094 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007095 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007096 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007097 First->getVectorKind() != VectorType::AltiVecPixel &&
7098 First->getVectorKind() != VectorType::AltiVecBool &&
7099 Second->getVectorKind() != VectorType::AltiVecPixel &&
7100 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007101 return true;
7102
7103 return false;
7104}
7105
Steve Naroff8e6aee52009-07-23 01:01:38 +00007106//===----------------------------------------------------------------------===//
7107// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7108//===----------------------------------------------------------------------===//
7109
7110/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7111/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007112bool
7113ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7114 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007115 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007116 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007117 for (auto *PI : rProto->protocols())
7118 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007119 return true;
7120 return false;
7121}
7122
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007123/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7124/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007125bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7126 QualType rhs) {
7127 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7128 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7129 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7130
Aaron Ballman83731462014-03-17 16:14:00 +00007131 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007132 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007133 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007134 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7135 match = true;
7136 break;
7137 }
7138 }
7139 if (!match)
7140 return false;
7141 }
7142 return true;
7143}
7144
Steve Naroff8e6aee52009-07-23 01:01:38 +00007145/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7146/// ObjCQualifiedIDType.
7147bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7148 bool compare) {
7149 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007150 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007151 lhs->isObjCIdType() || lhs->isObjCClassType())
7152 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007153 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007154 rhs->isObjCIdType() || rhs->isObjCClassType())
7155 return true;
7156
7157 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007158 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007159
Steve Naroff8e6aee52009-07-23 01:01:38 +00007160 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007161
Steve Naroff8e6aee52009-07-23 01:01:38 +00007162 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007163 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007164 // make sure we check the class hierarchy.
7165 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007166 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007167 // when comparing an id<P> on lhs with a static type on rhs,
7168 // see if static class implements all of id's protocols, directly or
7169 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007170 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007171 return false;
7172 }
7173 }
7174 // If there are no qualifiers and no interface, we have an 'id'.
7175 return true;
7176 }
Mike Stump11289f42009-09-09 15:08:12 +00007177 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007178 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007179 bool match = false;
7180
7181 // when comparing an id<P> on lhs with a static type on rhs,
7182 // see if static class implements all of id's protocols, directly or
7183 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007184 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007185 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7186 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7187 match = true;
7188 break;
7189 }
7190 }
Mike Stump11289f42009-09-09 15:08:12 +00007191 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007192 // make sure we check the class hierarchy.
7193 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007194 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007195 // when comparing an id<P> on lhs with a static type on rhs,
7196 // see if static class implements all of id's protocols, directly or
7197 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007198 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007199 match = true;
7200 break;
7201 }
7202 }
7203 }
7204 if (!match)
7205 return false;
7206 }
Mike Stump11289f42009-09-09 15:08:12 +00007207
Steve Naroff8e6aee52009-07-23 01:01:38 +00007208 return true;
7209 }
Mike Stump11289f42009-09-09 15:08:12 +00007210
Steve Naroff8e6aee52009-07-23 01:01:38 +00007211 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7212 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7213
Mike Stump11289f42009-09-09 15:08:12 +00007214 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007215 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007216 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007217 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007218 bool match = false;
7219
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007220 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007221 // see if static class implements all of id's protocols, directly or
7222 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007223 // First, lhs protocols in the qualifier list must be found, direct
7224 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007225 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007226 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7227 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7228 match = true;
7229 break;
7230 }
7231 }
7232 if (!match)
7233 return false;
7234 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007235
7236 // Static class's protocols, or its super class or category protocols
7237 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7238 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7239 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7240 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7241 // This is rather dubious but matches gcc's behavior. If lhs has
7242 // no type qualifier and its class has no static protocol(s)
7243 // assume that it is mismatch.
7244 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7245 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007246 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007247 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007248 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007249 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7250 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7251 match = true;
7252 break;
7253 }
7254 }
7255 if (!match)
7256 return false;
7257 }
7258 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007259 return true;
7260 }
7261 return false;
7262}
7263
Eli Friedman47f77112008-08-22 00:56:42 +00007264/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007265/// compatible for assignment from RHS to LHS. This handles validation of any
7266/// protocol qualifiers on the LHS or RHS.
7267///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007268bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7269 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007270 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7271 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7272
Steve Naroff1329fa02009-07-15 18:40:39 +00007273 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007274 if (LHS->isObjCUnqualifiedIdOrClass() ||
7275 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007276 return true;
7277
Douglas Gregorab209d82015-07-07 03:58:42 +00007278 // Function object that propagates a successful result or handles
7279 // __kindof types.
7280 auto finish = [&](bool succeeded) -> bool {
7281 if (succeeded)
7282 return true;
7283
7284 if (!RHS->isKindOfType())
7285 return false;
7286
7287 // Strip off __kindof and protocol qualifiers, then check whether
7288 // we can assign the other way.
7289 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7290 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7291 };
7292
7293 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7294 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7295 QualType(RHSOPT,0),
7296 false));
7297 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007298
Douglas Gregorab209d82015-07-07 03:58:42 +00007299 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7300 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7301 QualType(RHSOPT,0)));
7302 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007303
John McCall8b07ec22010-05-15 11:32:37 +00007304 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007305 if (LHS->getInterface() && RHS->getInterface()) {
7306 return finish(canAssignObjCInterfaces(LHS, RHS));
7307 }
Mike Stump11289f42009-09-09 15:08:12 +00007308
Steve Naroff8e6aee52009-07-23 01:01:38 +00007309 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007310}
7311
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007312/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007313/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007314/// arguments in block literals. When passed as arguments, passing 'A*' where
7315/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7316/// not OK. For the return type, the opposite is not OK.
7317bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7318 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007319 const ObjCObjectPointerType *RHSOPT,
7320 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007321
7322 // Function object that propagates a successful result or handles
7323 // __kindof types.
7324 auto finish = [&](bool succeeded) -> bool {
7325 if (succeeded)
7326 return true;
7327
7328 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7329 if (!Expected->isKindOfType())
7330 return false;
7331
7332 // Strip off __kindof and protocol qualifiers, then check whether
7333 // we can assign the other way.
7334 return canAssignObjCInterfacesInBlockPointer(
7335 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7336 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7337 BlockReturnType);
7338 };
7339
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007340 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007341 return true;
7342
7343 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007344 return finish(RHSOPT->isObjCBuiltinType() ||
7345 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007346 }
7347
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007348 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007349 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7350 QualType(RHSOPT,0),
7351 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007352
7353 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7354 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7355 if (LHS && RHS) { // We have 2 user-defined types.
7356 if (LHS != RHS) {
7357 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007358 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007359 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007360 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007361 }
7362 else
7363 return true;
7364 }
7365 return false;
7366}
7367
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007368/// Comparison routine for Objective-C protocols to be used with
7369/// llvm::array_pod_sort.
7370static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7371 ObjCProtocolDecl * const *rhs) {
7372 return (*lhs)->getName().compare((*rhs)->getName());
7373
7374}
7375
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007376/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007377/// of protocols inherited from two distinct objective-c pointer objects with
7378/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007379/// It is used to build composite qualifier list of the composite type of
7380/// the conditional expression involving two objective-c pointer objects.
7381static
7382void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007383 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007384 const ObjCObjectPointerType *LHSOPT,
7385 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007386 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007387
John McCall8b07ec22010-05-15 11:32:37 +00007388 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7389 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7390 assert(LHS->getInterface() && "LHS must have an interface base");
7391 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007392
7393 // Add all of the protocols for the LHS.
7394 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7395
7396 // Start with the protocol qualifiers.
7397 for (auto proto : LHS->quals()) {
7398 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007399 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007400
7401 // Also add the protocols associated with the LHS interface.
7402 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7403
7404 // Add all of the protocls for the RHS.
7405 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7406
7407 // Start with the protocol qualifiers.
7408 for (auto proto : RHS->quals()) {
7409 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007410 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007411
7412 // Also add the protocols associated with the RHS interface.
7413 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7414
7415 // Compute the intersection of the collected protocol sets.
7416 for (auto proto : LHSProtocolSet) {
7417 if (RHSProtocolSet.count(proto))
7418 IntersectionSet.push_back(proto);
7419 }
7420
7421 // Compute the set of protocols that is implied by either the common type or
7422 // the protocols within the intersection.
7423 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7424 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7425
7426 // Remove any implied protocols from the list of inherited protocols.
7427 if (!ImpliedProtocols.empty()) {
7428 IntersectionSet.erase(
7429 std::remove_if(IntersectionSet.begin(),
7430 IntersectionSet.end(),
7431 [&](ObjCProtocolDecl *proto) -> bool {
7432 return ImpliedProtocols.count(proto) > 0;
7433 }),
7434 IntersectionSet.end());
7435 }
7436
7437 // Sort the remaining protocols by name.
7438 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7439 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007440}
7441
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007442/// Determine whether the first type is a subtype of the second.
7443static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7444 QualType rhs) {
7445 // Common case: two object pointers.
7446 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7447 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7448 if (lhsOPT && rhsOPT)
7449 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7450
7451 // Two block pointers.
7452 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7453 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7454 if (lhsBlock && rhsBlock)
7455 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7456
7457 // If either is an unqualified 'id' and the other is a block, it's
7458 // acceptable.
7459 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7460 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7461 return true;
7462
7463 return false;
7464}
7465
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007466// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007467static bool sameObjCTypeArgs(ASTContext &ctx,
7468 const ObjCInterfaceDecl *iface,
7469 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007470 ArrayRef<QualType> rhsArgs,
7471 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007472 if (lhsArgs.size() != rhsArgs.size())
7473 return false;
7474
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007475 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007476 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007477 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7478 continue;
7479
7480 switch (typeParams->begin()[i]->getVariance()) {
7481 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007482 if (!stripKindOf ||
7483 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7484 rhsArgs[i].stripObjCKindOfType(ctx))) {
7485 return false;
7486 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007487 break;
7488
7489 case ObjCTypeParamVariance::Covariant:
7490 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7491 return false;
7492 break;
7493
7494 case ObjCTypeParamVariance::Contravariant:
7495 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7496 return false;
7497 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007498 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007499 }
7500
7501 return true;
7502}
7503
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007504QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007505 const ObjCObjectPointerType *Lptr,
7506 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007507 const ObjCObjectType *LHS = Lptr->getObjectType();
7508 const ObjCObjectType *RHS = Rptr->getObjectType();
7509 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7510 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007511
7512 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007513 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007514
Manman Renc46f7d12016-05-06 19:35:02 +00007515 // When either LHS or RHS is a kindof type, we should return a kindof type.
7516 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7517 // kindof(A).
7518 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7519
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007520 // Follow the left-hand side up the class hierarchy until we either hit a
7521 // root or find the RHS. Record the ancestors in case we don't find it.
7522 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7523 LHSAncestors;
7524 while (true) {
7525 // Record this ancestor. We'll need this if the common type isn't in the
7526 // path from the LHS to the root.
7527 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007528
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007529 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7530 // Get the type arguments.
7531 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7532 bool anyChanges = false;
7533 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7534 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007535 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7536 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007537 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007538 return QualType();
7539 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7540 // If only one has type arguments, the result will not have type
7541 // arguments.
7542 LHSTypeArgs = { };
7543 anyChanges = true;
7544 }
7545
7546 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007547 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007548 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7549 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007550 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007551 anyChanges = true;
7552
7553 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007554 // If we need to return a kindof type but LHS is not a kindof type, we
7555 // build a new result type.
7556 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007557 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007558 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007559 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007560 return getObjCObjectPointerType(Result);
7561 }
7562
7563 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007564 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007565
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007566 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007567 QualType LHSSuperType = LHS->getSuperClassType();
7568 if (LHSSuperType.isNull())
7569 break;
7570
7571 LHS = LHSSuperType->castAs<ObjCObjectType>();
7572 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007573
7574 // We didn't find anything by following the LHS to its root; now check
7575 // the RHS against the cached set of ancestors.
7576 while (true) {
7577 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7578 if (KnownLHS != LHSAncestors.end()) {
7579 LHS = KnownLHS->second;
7580
7581 // Get the type arguments.
7582 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7583 bool anyChanges = false;
7584 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7585 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007586 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7587 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007588 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007589 return QualType();
7590 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7591 // If only one has type arguments, the result will not have type
7592 // arguments.
7593 RHSTypeArgs = { };
7594 anyChanges = true;
7595 }
7596
7597 // Compute the intersection of protocols.
7598 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7599 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7600 Protocols);
7601 if (!Protocols.empty())
7602 anyChanges = true;
7603
Manman Renc46f7d12016-05-06 19:35:02 +00007604 // If we need to return a kindof type but RHS is not a kindof type, we
7605 // build a new result type.
7606 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007607 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007608 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007609 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007610 return getObjCObjectPointerType(Result);
7611 }
7612
7613 return getObjCObjectPointerType(QualType(RHS, 0));
7614 }
7615
7616 // Find the superclass of the RHS.
7617 QualType RHSSuperType = RHS->getSuperClassType();
7618 if (RHSSuperType.isNull())
7619 break;
7620
7621 RHS = RHSSuperType->castAs<ObjCObjectType>();
7622 }
7623
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007624 return QualType();
7625}
7626
John McCall8b07ec22010-05-15 11:32:37 +00007627bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7628 const ObjCObjectType *RHS) {
7629 assert(LHS->getInterface() && "LHS is not an interface type");
7630 assert(RHS->getInterface() && "RHS is not an interface type");
7631
Chris Lattner49af6a42008-04-07 06:51:04 +00007632 // Verify that the base decls are compatible: the RHS must be a subclass of
7633 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007634 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7635 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7636 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007637 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007638
Douglas Gregore83b9562015-07-07 03:57:53 +00007639 // If the LHS has protocol qualifiers, determine whether all of them are
7640 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7641 // LHS).
7642 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007643 // OK if conversion of LHS to SuperClass results in narrowing of types
7644 // ; i.e., SuperClass may implement at least one of the protocols
7645 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7646 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7647 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7648 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7649 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7650 // qualifiers.
7651 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007652 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007653 // If there is no protocols associated with RHS, it is not a match.
7654 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007655 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007656
7657 for (const auto *LHSProto : LHS->quals()) {
7658 bool SuperImplementsProtocol = false;
7659 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7660 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7661 SuperImplementsProtocol = true;
7662 break;
7663 }
7664 if (!SuperImplementsProtocol)
7665 return false;
7666 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007667 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007668
7669 // If the LHS is specialized, we may need to check type arguments.
7670 if (LHS->isSpecialized()) {
7671 // Follow the superclass chain until we've matched the LHS class in the
7672 // hierarchy. This substitutes type arguments through.
7673 const ObjCObjectType *RHSSuper = RHS;
7674 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7675 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7676
7677 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007678 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007679 !sameObjCTypeArgs(*this, LHS->getInterface(),
7680 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007681 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007682 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007683 }
7684 }
7685
7686 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007687}
7688
Steve Naroffb7605152009-02-12 17:52:19 +00007689bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7690 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007691 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7692 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007693
Steve Naroff7cae42b2009-07-10 23:34:53 +00007694 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007695 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007696
7697 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7698 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007699}
7700
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007701bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7702 return canAssignObjCInterfaces(
7703 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7704 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7705}
7706
Mike Stump11289f42009-09-09 15:08:12 +00007707/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007708/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007709/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007710/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007711bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7712 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007713 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007714 return hasSameType(LHS, RHS);
7715
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007716 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007717}
7718
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007719bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007720 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007721}
7722
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007723bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7724 return !mergeTypes(LHS, RHS, true).isNull();
7725}
7726
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007727/// mergeTransparentUnionType - if T is a transparent union type and a member
7728/// of T is compatible with SubType, return the merged type, else return
7729/// QualType()
7730QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7731 bool OfBlockPointer,
7732 bool Unqualified) {
7733 if (const RecordType *UT = T->getAsUnionType()) {
7734 RecordDecl *UD = UT->getDecl();
7735 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007736 for (const auto *I : UD->fields()) {
7737 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007738 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7739 if (!MT.isNull())
7740 return MT;
7741 }
7742 }
7743 }
7744
7745 return QualType();
7746}
7747
Alp Toker9cacbab2014-01-20 20:26:09 +00007748/// mergeFunctionParameterTypes - merge two types which appear as function
7749/// parameter types
7750QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7751 bool OfBlockPointer,
7752 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007753 // GNU extension: two types are compatible if they appear as a function
7754 // argument, one of the types is a transparent union type and the other
7755 // type is compatible with a union member
7756 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7757 Unqualified);
7758 if (!lmerge.isNull())
7759 return lmerge;
7760
7761 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7762 Unqualified);
7763 if (!rmerge.isNull())
7764 return rmerge;
7765
7766 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7767}
7768
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007769QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007770 bool OfBlockPointer,
7771 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007772 const FunctionType *lbase = lhs->getAs<FunctionType>();
7773 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007774 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7775 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007776 bool allLTypes = true;
7777 bool allRTypes = true;
7778
7779 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007780 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007781 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007782 QualType RHS = rbase->getReturnType();
7783 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007784 bool UnqualifiedResult = Unqualified;
7785 if (!UnqualifiedResult)
7786 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007787 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007788 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007789 else
Alp Toker314cc812014-01-25 16:55:45 +00007790 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007791 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007792 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007793
7794 if (Unqualified)
7795 retType = retType.getUnqualifiedType();
7796
Alp Toker314cc812014-01-25 16:55:45 +00007797 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7798 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007799 if (Unqualified) {
7800 LRetType = LRetType.getUnqualifiedType();
7801 RRetType = RRetType.getUnqualifiedType();
7802 }
7803
7804 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007805 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007806 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007807 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007808
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007809 // FIXME: double check this
7810 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7811 // rbase->getRegParmAttr() != 0 &&
7812 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007813 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7814 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007815
Douglas Gregor8c940862010-01-18 17:14:39 +00007816 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007817 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007818 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007819
John McCall8c6b56f2010-12-15 01:06:38 +00007820 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007821 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7822 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007823 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7824 return QualType();
7825
John McCall31168b02011-06-15 23:02:42 +00007826 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7827 return QualType();
7828
John McCall8c6b56f2010-12-15 01:06:38 +00007829 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7830 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007831
Rafael Espindola8778c282012-11-29 16:09:03 +00007832 if (lbaseInfo.getNoReturn() != NoReturn)
7833 allLTypes = false;
7834 if (rbaseInfo.getNoReturn() != NoReturn)
7835 allRTypes = false;
7836
John McCall31168b02011-06-15 23:02:42 +00007837 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007838
Eli Friedman47f77112008-08-22 00:56:42 +00007839 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007840 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7841 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007842 // Compatible functions must have the same number of parameters
7843 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007844 return QualType();
7845
7846 // Variadic and non-variadic functions aren't compatible
7847 if (lproto->isVariadic() != rproto->isVariadic())
7848 return QualType();
7849
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007850 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7851 return QualType();
7852
John McCall18afab72016-03-01 00:49:02 +00007853 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007854 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007855
7856 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007857 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007858 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7859 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7860 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7861 QualType paramType = mergeFunctionParameterTypes(
7862 lParamType, rParamType, OfBlockPointer, Unqualified);
7863 if (paramType.isNull())
7864 return QualType();
7865
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007866 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007867 paramType = paramType.getUnqualifiedType();
7868
7869 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007870 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007871 lParamType = lParamType.getUnqualifiedType();
7872 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007873 }
Alp Toker601b22c2014-01-21 23:35:24 +00007874
7875 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007876 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007877 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007878 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007879 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007880
Eli Friedman47f77112008-08-22 00:56:42 +00007881 if (allLTypes) return lhs;
7882 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007883
7884 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7885 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007886 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007887 }
7888
7889 if (lproto) allRTypes = false;
7890 if (rproto) allLTypes = false;
7891
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007892 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007893 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007894 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007895 if (proto->isVariadic()) return QualType();
7896 // Check that the types are compatible with the types that
7897 // would result from default argument promotions (C99 6.7.5.3p15).
7898 // The only types actually affected are promotable integer
7899 // types and floats, which would be passed as a different
7900 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007901 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7902 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007903
Eli Friedman448ce402012-08-30 00:44:15 +00007904 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007905 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007906 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7907 paramTy = Enum->getDecl()->getIntegerType();
7908 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007909 return QualType();
7910 }
Alp Toker601b22c2014-01-21 23:35:24 +00007911
7912 if (paramTy->isPromotableIntegerType() ||
7913 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007914 return QualType();
7915 }
7916
7917 if (allLTypes) return lhs;
7918 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007919
7920 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7921 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007922 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007923 }
7924
7925 if (allLTypes) return lhs;
7926 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007927 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007928}
7929
John McCall433c2e62013-03-21 00:10:07 +00007930/// Given that we have an enum type and a non-enum type, try to merge them.
7931static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7932 QualType other, bool isBlockReturnType) {
7933 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7934 // a signed integer type, or an unsigned integer type.
7935 // Compatibility is based on the underlying type, not the promotion
7936 // type.
7937 QualType underlyingType = ET->getDecl()->getIntegerType();
7938 if (underlyingType.isNull()) return QualType();
7939 if (Context.hasSameType(underlyingType, other))
7940 return other;
7941
7942 // In block return types, we're more permissive and accept any
7943 // integral type of the same size.
7944 if (isBlockReturnType && other->isIntegerType() &&
7945 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7946 return other;
7947
7948 return QualType();
7949}
7950
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007951QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007952 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007953 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007954 // C++ [expr]: If an expression initially has the type "reference to T", the
7955 // type is adjusted to "T" prior to any further analysis, the expression
7956 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007957 // expression is an lvalue unless the reference is an rvalue reference and
7958 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007959 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7960 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007961
7962 if (Unqualified) {
7963 LHS = LHS.getUnqualifiedType();
7964 RHS = RHS.getUnqualifiedType();
7965 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007966
Eli Friedman47f77112008-08-22 00:56:42 +00007967 QualType LHSCan = getCanonicalType(LHS),
7968 RHSCan = getCanonicalType(RHS);
7969
7970 // If two types are identical, they are compatible.
7971 if (LHSCan == RHSCan)
7972 return LHS;
7973
John McCall8ccfcb52009-09-24 19:53:00 +00007974 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007975 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7976 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007977 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007978 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00007979 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007980 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7981 return QualType();
7982 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7983 return LHS;
7984 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7985 return RHS;
7986 }
John McCall8ccfcb52009-09-24 19:53:00 +00007987 // If any of these qualifiers are different, we have a type
7988 // mismatch.
7989 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007990 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7991 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007992 return QualType();
7993
7994 // Exactly one GC qualifier difference is allowed: __strong is
7995 // okay if the other type has no GC qualifier but is an Objective
7996 // C object pointer (i.e. implicitly strong by default). We fix
7997 // this by pretending that the unqualified type was actually
7998 // qualified __strong.
7999 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8000 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8001 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8002
8003 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8004 return QualType();
8005
8006 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8007 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8008 }
8009 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8010 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8011 }
Eli Friedman47f77112008-08-22 00:56:42 +00008012 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008013 }
8014
8015 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008016
Eli Friedmandcca6332009-06-01 01:22:52 +00008017 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8018 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008019
Chris Lattnerfd652912008-01-14 05:45:46 +00008020 // We want to consider the two function types to be the same for these
8021 // comparisons, just force one to the other.
8022 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8023 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008024
8025 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008026 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8027 LHSClass = Type::ConstantArray;
8028 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8029 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008030
John McCall8b07ec22010-05-15 11:32:37 +00008031 // ObjCInterfaces are just specialized ObjCObjects.
8032 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8033 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8034
Nate Begemance4d7fc2008-04-18 23:10:10 +00008035 // Canonicalize ExtVector -> Vector.
8036 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8037 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008038
Chris Lattner95554662008-04-07 05:43:21 +00008039 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008040 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008041 // Note that we only have special rules for turning block enum
8042 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008043 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008044 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008045 }
John McCall9dd450b2009-09-21 23:43:11 +00008046 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008047 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008048 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008049 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008050 if (OfBlockPointer && !BlockReturnType) {
8051 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8052 return LHS;
8053 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8054 return RHS;
8055 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008056
Eli Friedman47f77112008-08-22 00:56:42 +00008057 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008058 }
Eli Friedman47f77112008-08-22 00:56:42 +00008059
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008060 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008061 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008062#define TYPE(Class, Base)
8063#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008064#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008065#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8066#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8067#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008068 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008069
Richard Smith27d807c2013-04-30 13:56:41 +00008070 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008071 case Type::LValueReference:
8072 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008073 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008074 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008075
John McCall8b07ec22010-05-15 11:32:37 +00008076 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008077 case Type::IncompleteArray:
8078 case Type::VariableArray:
8079 case Type::FunctionProto:
8080 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008081 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008082
Chris Lattnerfd652912008-01-14 05:45:46 +00008083 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008084 {
8085 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008086 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8087 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008088 if (Unqualified) {
8089 LHSPointee = LHSPointee.getUnqualifiedType();
8090 RHSPointee = RHSPointee.getUnqualifiedType();
8091 }
8092 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8093 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008094 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008095 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008096 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008097 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008098 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008099 return getPointerType(ResultType);
8100 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008101 case Type::BlockPointer:
8102 {
8103 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008104 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8105 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008106 if (Unqualified) {
8107 LHSPointee = LHSPointee.getUnqualifiedType();
8108 RHSPointee = RHSPointee.getUnqualifiedType();
8109 }
8110 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8111 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008112 if (ResultType.isNull()) return QualType();
8113 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8114 return LHS;
8115 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8116 return RHS;
8117 return getBlockPointerType(ResultType);
8118 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008119 case Type::Atomic:
8120 {
8121 // Merge two pointer types, while trying to preserve typedef info
8122 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8123 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8124 if (Unqualified) {
8125 LHSValue = LHSValue.getUnqualifiedType();
8126 RHSValue = RHSValue.getUnqualifiedType();
8127 }
8128 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8129 Unqualified);
8130 if (ResultType.isNull()) return QualType();
8131 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8132 return LHS;
8133 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8134 return RHS;
8135 return getAtomicType(ResultType);
8136 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008137 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008138 {
8139 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8140 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8141 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8142 return QualType();
8143
8144 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8145 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008146 if (Unqualified) {
8147 LHSElem = LHSElem.getUnqualifiedType();
8148 RHSElem = RHSElem.getUnqualifiedType();
8149 }
8150
8151 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008152 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008153 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8154 return LHS;
8155 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8156 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008157 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8158 ArrayType::ArraySizeModifier(), 0);
8159 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8160 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008161 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8162 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008163 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8164 return LHS;
8165 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8166 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008167 if (LVAT) {
8168 // FIXME: This isn't correct! But tricky to implement because
8169 // the array's size has to be the size of LHS, but the type
8170 // has to be different.
8171 return LHS;
8172 }
8173 if (RVAT) {
8174 // FIXME: This isn't correct! But tricky to implement because
8175 // the array's size has to be the size of RHS, but the type
8176 // has to be different.
8177 return RHS;
8178 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008179 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8180 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008181 return getIncompleteArrayType(ResultType,
8182 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008183 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008184 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008185 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008186 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008187 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008188 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008189 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008190 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008191 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008192 case Type::Complex:
8193 // Distinct complex types are incompatible.
8194 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008195 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008196 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008197 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8198 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008199 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008200 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008201 case Type::ObjCObject: {
8202 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008203 // FIXME: This should be type compatibility, e.g. whether
8204 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008205 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8206 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8207 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008208 return LHS;
8209
Eli Friedman47f77112008-08-22 00:56:42 +00008210 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008211 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008212 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008213 if (OfBlockPointer) {
8214 if (canAssignObjCInterfacesInBlockPointer(
8215 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008216 RHS->getAs<ObjCObjectPointerType>(),
8217 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008218 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008219 return QualType();
8220 }
John McCall9dd450b2009-09-21 23:43:11 +00008221 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8222 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008223 return LHS;
8224
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008225 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008226 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008227 case Type::Pipe:
8228 {
8229 // Merge two pointer types, while trying to preserve typedef info
8230 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
8231 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
8232 if (Unqualified) {
8233 LHSValue = LHSValue.getUnqualifiedType();
8234 RHSValue = RHSValue.getUnqualifiedType();
8235 }
8236 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8237 Unqualified);
8238 if (ResultType.isNull()) return QualType();
8239 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8240 return LHS;
8241 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8242 return RHS;
8243 return getPipeType(ResultType);
8244 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008245 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008246
David Blaikie8a40f702012-01-17 06:56:22 +00008247 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008248}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008249
John McCall18afab72016-03-01 00:49:02 +00008250bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8251 const FunctionProtoType *firstFnType,
8252 const FunctionProtoType *secondFnType) {
8253 // Fast path: if the first type doesn't have ext parameter infos,
8254 // we match if and only if they second type also doesn't have them.
8255 if (!firstFnType->hasExtParameterInfos())
8256 return !secondFnType->hasExtParameterInfos();
8257
8258 // Otherwise, we can only match if the second type has them.
8259 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008260 return false;
John McCall18afab72016-03-01 00:49:02 +00008261
8262 auto firstEPI = firstFnType->getExtParameterInfos();
8263 auto secondEPI = secondFnType->getExtParameterInfos();
8264 assert(firstEPI.size() == secondEPI.size());
8265
8266 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8267 if (firstEPI[i] != secondEPI[i])
8268 return false;
8269 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008270 return true;
8271}
8272
Chandler Carruth21c90602015-12-30 03:24:14 +00008273void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8274 ObjCLayouts[CD] = nullptr;
8275}
8276
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008277/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8278/// 'RHS' attributes and returns the merged version; including for function
8279/// return types.
8280QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8281 QualType LHSCan = getCanonicalType(LHS),
8282 RHSCan = getCanonicalType(RHS);
8283 // If two types are identical, they are compatible.
8284 if (LHSCan == RHSCan)
8285 return LHS;
8286 if (RHSCan->isFunctionType()) {
8287 if (!LHSCan->isFunctionType())
8288 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008289 QualType OldReturnType =
8290 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008291 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008292 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008293 QualType ResReturnType =
8294 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8295 if (ResReturnType.isNull())
8296 return QualType();
8297 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8298 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8299 // In either case, use OldReturnType to build the new function type.
8300 const FunctionType *F = LHS->getAs<FunctionType>();
8301 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008302 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8303 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008304 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008305 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008306 return ResultType;
8307 }
8308 }
8309 return QualType();
8310 }
8311
8312 // If the qualifiers are different, the types can still be merged.
8313 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8314 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8315 if (LQuals != RQuals) {
8316 // If any of these qualifiers are different, we have a type mismatch.
8317 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8318 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8319 return QualType();
8320
8321 // Exactly one GC qualifier difference is allowed: __strong is
8322 // okay if the other type has no GC qualifier but is an Objective
8323 // C object pointer (i.e. implicitly strong by default). We fix
8324 // this by pretending that the unqualified type was actually
8325 // qualified __strong.
8326 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8327 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8328 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8329
8330 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8331 return QualType();
8332
8333 if (GC_L == Qualifiers::Strong)
8334 return LHS;
8335 if (GC_R == Qualifiers::Strong)
8336 return RHS;
8337 return QualType();
8338 }
8339
8340 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8341 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8342 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8343 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8344 if (ResQT == LHSBaseQT)
8345 return LHS;
8346 if (ResQT == RHSBaseQT)
8347 return RHS;
8348 }
8349 return QualType();
8350}
8351
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008352//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008353// Integer Predicates
8354//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008355
Jay Foad39c79802011-01-12 09:06:06 +00008356unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008357 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008358 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008359 if (T->isBooleanType())
8360 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008361 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008362 return (unsigned)getTypeSize(T);
8363}
8364
Abramo Bagnara13640492012-09-09 10:21:24 +00008365QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008366 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008367
8368 // Turn <4 x signed int> -> <4 x unsigned int>
8369 if (const VectorType *VTy = T->getAs<VectorType>())
8370 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008371 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008372
8373 // For enums, we return the unsigned version of the base type.
8374 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008375 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008376
8377 const BuiltinType *BTy = T->getAs<BuiltinType>();
8378 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008379 switch (BTy->getKind()) {
8380 case BuiltinType::Char_S:
8381 case BuiltinType::SChar:
8382 return UnsignedCharTy;
8383 case BuiltinType::Short:
8384 return UnsignedShortTy;
8385 case BuiltinType::Int:
8386 return UnsignedIntTy;
8387 case BuiltinType::Long:
8388 return UnsignedLongTy;
8389 case BuiltinType::LongLong:
8390 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008391 case BuiltinType::Int128:
8392 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008393 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008394 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008395 }
8396}
8397
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008398ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008399
Richard Smith1fa5d642013-05-11 05:45:24 +00008400void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8401 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008402
8403//===----------------------------------------------------------------------===//
8404// Builtin Type Computation
8405//===----------------------------------------------------------------------===//
8406
8407/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008408/// pointer over the consumed characters. This returns the resultant type. If
8409/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8410/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8411/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008412///
8413/// RequiresICE is filled in on return to indicate whether the value is required
8414/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008415static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008416 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008417 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008418 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008419 // Modifiers.
8420 int HowLong = 0;
8421 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008422 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008423
Chris Lattnerdc226c22010-10-01 22:42:38 +00008424 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008425 bool Done = false;
8426 while (!Done) {
8427 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008428 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008429 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008430 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008431 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008432 case 'S':
8433 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8434 assert(!Signed && "Can't use 'S' modifier multiple times!");
8435 Signed = true;
8436 break;
8437 case 'U':
8438 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008439 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008440 Unsigned = true;
8441 break;
8442 case 'L':
8443 assert(HowLong <= 2 && "Can't have LLLL modifier");
8444 ++HowLong;
8445 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008446 case 'W':
8447 // This modifier represents int64 type.
8448 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8449 switch (Context.getTargetInfo().getInt64Type()) {
8450 default:
8451 llvm_unreachable("Unexpected integer type");
8452 case TargetInfo::SignedLong:
8453 HowLong = 1;
8454 break;
8455 case TargetInfo::SignedLongLong:
8456 HowLong = 2;
8457 break;
8458 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008459 }
8460 }
8461
8462 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008463
Chris Lattnerecd79c62009-06-14 00:45:47 +00008464 // Read the base type.
8465 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008466 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008467 case 'v':
8468 assert(HowLong == 0 && !Signed && !Unsigned &&
8469 "Bad modifiers used with 'v'!");
8470 Type = Context.VoidTy;
8471 break;
Jack Carter24bef982013-08-15 15:16:57 +00008472 case 'h':
8473 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008474 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008475 Type = Context.HalfTy;
8476 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008477 case 'f':
8478 assert(HowLong == 0 && !Signed && !Unsigned &&
8479 "Bad modifiers used with 'f'!");
8480 Type = Context.FloatTy;
8481 break;
8482 case 'd':
8483 assert(HowLong < 2 && !Signed && !Unsigned &&
8484 "Bad modifiers used with 'd'!");
8485 if (HowLong)
8486 Type = Context.LongDoubleTy;
8487 else
8488 Type = Context.DoubleTy;
8489 break;
8490 case 's':
8491 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8492 if (Unsigned)
8493 Type = Context.UnsignedShortTy;
8494 else
8495 Type = Context.ShortTy;
8496 break;
8497 case 'i':
8498 if (HowLong == 3)
8499 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8500 else if (HowLong == 2)
8501 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8502 else if (HowLong == 1)
8503 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8504 else
8505 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8506 break;
8507 case 'c':
8508 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8509 if (Signed)
8510 Type = Context.SignedCharTy;
8511 else if (Unsigned)
8512 Type = Context.UnsignedCharTy;
8513 else
8514 Type = Context.CharTy;
8515 break;
8516 case 'b': // boolean
8517 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8518 Type = Context.BoolTy;
8519 break;
8520 case 'z': // size_t.
8521 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8522 Type = Context.getSizeType();
8523 break;
8524 case 'F':
8525 Type = Context.getCFConstantStringType();
8526 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008527 case 'G':
8528 Type = Context.getObjCIdType();
8529 break;
8530 case 'H':
8531 Type = Context.getObjCSelType();
8532 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008533 case 'M':
8534 Type = Context.getObjCSuperType();
8535 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008536 case 'a':
8537 Type = Context.getBuiltinVaListType();
8538 assert(!Type.isNull() && "builtin va list type not initialized!");
8539 break;
8540 case 'A':
8541 // This is a "reference" to a va_list; however, what exactly
8542 // this means depends on how va_list is defined. There are two
8543 // different kinds of va_list: ones passed by value, and ones
8544 // passed by reference. An example of a by-value va_list is
8545 // x86, where va_list is a char*. An example of by-ref va_list
8546 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8547 // we want this argument to be a char*&; for x86-64, we want
8548 // it to be a __va_list_tag*.
8549 Type = Context.getBuiltinVaListType();
8550 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008551 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008552 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008553 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008554 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008555 break;
8556 case 'V': {
8557 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008558 unsigned NumElements = strtoul(Str, &End, 10);
8559 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008560 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008561
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008562 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8563 RequiresICE, false);
8564 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008565
8566 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008567 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008568 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008569 break;
8570 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008571 case 'E': {
8572 char *End;
8573
8574 unsigned NumElements = strtoul(Str, &End, 10);
8575 assert(End != Str && "Missing vector size");
8576
8577 Str = End;
8578
8579 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8580 false);
8581 Type = Context.getExtVectorType(ElementType, NumElements);
8582 break;
8583 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008584 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008585 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8586 false);
8587 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008588 Type = Context.getComplexType(ElementType);
8589 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008590 }
8591 case 'Y' : {
8592 Type = Context.getPointerDiffType();
8593 break;
8594 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008595 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008596 Type = Context.getFILEType();
8597 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008598 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008599 return QualType();
8600 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008601 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008602 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008603 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008604 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008605 else
8606 Type = Context.getjmp_bufType();
8607
Mike Stump2adb4da2009-07-28 23:47:15 +00008608 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008609 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008610 return QualType();
8611 }
8612 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008613 case 'K':
8614 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8615 Type = Context.getucontext_tType();
8616
8617 if (Type.isNull()) {
8618 Error = ASTContext::GE_Missing_ucontext;
8619 return QualType();
8620 }
8621 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008622 case 'p':
8623 Type = Context.getProcessIDType();
8624 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008625 }
Mike Stump11289f42009-09-09 15:08:12 +00008626
Chris Lattnerdc226c22010-10-01 22:42:38 +00008627 // If there are modifiers and if we're allowed to parse them, go for it.
8628 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008629 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008630 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008631 default: Done = true; --Str; break;
8632 case '*':
8633 case '&': {
8634 // Both pointers and references can have their pointee types
8635 // qualified with an address space.
8636 char *End;
8637 unsigned AddrSpace = strtoul(Str, &End, 10);
8638 if (End != Str && AddrSpace != 0) {
8639 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8640 Str = End;
8641 }
8642 if (c == '*')
8643 Type = Context.getPointerType(Type);
8644 else
8645 Type = Context.getLValueReferenceType(Type);
8646 break;
8647 }
8648 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8649 case 'C':
8650 Type = Type.withConst();
8651 break;
8652 case 'D':
8653 Type = Context.getVolatileType(Type);
8654 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008655 case 'R':
8656 Type = Type.withRestrict();
8657 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008658 }
8659 }
Chris Lattner84733392010-10-01 07:13:18 +00008660
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008661 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008662 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008663
Chris Lattnerecd79c62009-06-14 00:45:47 +00008664 return Type;
8665}
8666
8667/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008668QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008669 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008670 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008671 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008672
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008673 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008674
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008675 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008676 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008677 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8678 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008679 if (Error != GE_None)
8680 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008681
8682 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8683
Chris Lattnerecd79c62009-06-14 00:45:47 +00008684 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008685 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008686 if (Error != GE_None)
8687 return QualType();
8688
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008689 // If this argument is required to be an IntegerConstantExpression and the
8690 // caller cares, fill in the bitmask we return.
8691 if (RequiresICE && IntegerConstantArgs)
8692 *IntegerConstantArgs |= 1 << ArgTypes.size();
8693
Chris Lattnerecd79c62009-06-14 00:45:47 +00008694 // Do array -> pointer decay. The builtin should use the decayed type.
8695 if (Ty->isArrayType())
8696 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008697
Chris Lattnerecd79c62009-06-14 00:45:47 +00008698 ArgTypes.push_back(Ty);
8699 }
8700
David Majnemerba3e5ec2015-03-13 18:26:17 +00008701 if (Id == Builtin::BI__GetExceptionInfo)
8702 return QualType();
8703
Chris Lattnerecd79c62009-06-14 00:45:47 +00008704 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8705 "'.' should only occur at end of builtin type list!");
8706
Reid Kleckner78af0702013-08-27 23:08:25 +00008707 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008708 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8709
8710 bool Variadic = (TypeStr[0] == '.');
8711
8712 // We really shouldn't be making a no-proto type here, especially in C++.
8713 if (ArgTypes.empty() && Variadic)
8714 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008715
John McCalldb40c7f2010-12-14 08:05:40 +00008716 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008717 EPI.ExtInfo = EI;
8718 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008719 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8720 EPI.ExceptionSpec.Type =
8721 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008722
Jordan Rose5c382722013-03-08 21:51:21 +00008723 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008724}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008725
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008726static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8727 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008728 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008729 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008730
Rafael Espindola3ae00052013-05-13 00:12:11 +00008731 GVALinkage External = GVA_StrongExternal;
8732 switch (FD->getTemplateSpecializationKind()) {
8733 case TSK_Undeclared:
8734 case TSK_ExplicitSpecialization:
8735 External = GVA_StrongExternal;
8736 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008737
Rafael Espindola3ae00052013-05-13 00:12:11 +00008738 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008739 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008740
David Majnemerc3d07332014-05-15 06:25:57 +00008741 // C++11 [temp.explicit]p10:
8742 // [ Note: The intent is that an inline function that is the subject of
8743 // an explicit instantiation declaration will still be implicitly
8744 // instantiated when used so that the body can be considered for
8745 // inlining, but that no out-of-line copy of the inline function would be
8746 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008747 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008748 return GVA_AvailableExternally;
8749
Rafael Espindola3ae00052013-05-13 00:12:11 +00008750 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008751 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008752 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008753 }
8754
8755 if (!FD->isInlined())
8756 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008757
David Majnemer3f021502015-10-08 04:53:31 +00008758 if ((!Context.getLangOpts().CPlusPlus &&
8759 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008760 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008761 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008762 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8763
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008764 // GNU or C99 inline semantics. Determine whether this symbol should be
8765 // externally visible.
8766 if (FD->isInlineDefinitionExternallyVisible())
8767 return External;
8768
8769 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008770 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008771 }
8772
David Majnemer54e3ba52014-04-02 23:17:29 +00008773 // Functions specified with extern and inline in -fms-compatibility mode
8774 // forcibly get emitted. While the body of the function cannot be later
8775 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008776 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008777 return GVA_StrongODR;
8778
David Majnemer27d69db2014-04-28 22:17:59 +00008779 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008780}
8781
Artem Belevichca2b9512016-05-02 20:30:03 +00008782static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8783 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008784 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8785 // dllexport/dllimport on inline functions.
8786 if (D->hasAttr<DLLImportAttr>()) {
8787 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8788 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008789 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008790 if (L == GVA_DiscardableODR)
8791 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008792 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8793 D->hasAttr<CUDAGlobalAttr>()) {
8794 // Device-side functions with __global__ attribute must always be
8795 // visible externally so they can be launched from host.
8796 if (L == GVA_DiscardableODR || L == GVA_Internal)
8797 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008798 }
8799 return L;
8800}
8801
8802GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008803 return adjustGVALinkageForAttributes(
8804 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008805}
8806
8807static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8808 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008809 if (!VD->isExternallyVisible())
8810 return GVA_Internal;
8811
David Majnemer27d69db2014-04-28 22:17:59 +00008812 if (VD->isStaticLocal()) {
8813 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8814 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8815 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8816 LexicalContext = LexicalContext->getLexicalParent();
8817
Richard Smith9e2341d2015-03-23 03:25:59 +00008818 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008819 // enclosing function.
8820 if (LexicalContext)
8821 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008822 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008823
8824 // GVA_StrongODR function linkage is stronger than what we need,
8825 // downgrade to GVA_DiscardableODR.
8826 // This allows us to discard the variable if we never end up needing it.
8827 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8828 : StaticLocalLinkage;
8829 }
8830
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008831 // MSVC treats in-class initialized static data members as definitions.
8832 // By giving them non-strong linkage, out-of-line definitions won't
8833 // cause link errors.
8834 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8835 return GVA_DiscardableODR;
8836
Richard Smithd9b90092016-07-02 01:32:16 +00008837 // Most non-template variables have strong linkage; inline variables are
8838 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8839 GVALinkage StrongLinkage;
8840 switch (Context.getInlineVariableDefinitionKind(VD)) {
8841 case ASTContext::InlineVariableDefinitionKind::None:
8842 StrongLinkage = GVA_StrongExternal;
8843 break;
8844 case ASTContext::InlineVariableDefinitionKind::Weak:
8845 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008846 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008847 break;
8848 case ASTContext::InlineVariableDefinitionKind::Strong:
8849 StrongLinkage = GVA_StrongODR;
8850 break;
8851 }
Richard Smith62f19e72016-06-25 00:15:56 +00008852
Richard Smith8809a0c2013-09-27 20:14:12 +00008853 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008854 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008855 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008856
David Majnemer6d1780c2015-07-17 23:36:49 +00008857 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008858 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8859 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008860 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008861 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008862
Rafael Espindola3ae00052013-05-13 00:12:11 +00008863 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008864 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008865
David Majnemer27d69db2014-04-28 22:17:59 +00008866 case TSK_ExplicitInstantiationDeclaration:
8867 return GVA_AvailableExternally;
8868
Rafael Espindola3ae00052013-05-13 00:12:11 +00008869 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008870 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008871 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008872
8873 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008874}
8875
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008876GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008877 return adjustGVALinkageForAttributes(
8878 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008879}
8880
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008881bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008882 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8883 if (!VD->isFileVarDecl())
8884 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008885 // Global named register variables (GNU extension) are never emitted.
8886 if (VD->getStorageClass() == SC_Register)
8887 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008888 if (VD->getDescribedVarTemplate() ||
8889 isa<VarTemplatePartialSpecializationDecl>(VD))
8890 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008891 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8892 // We never need to emit an uninstantiated function template.
8893 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8894 return false;
Nico Weber66220292016-03-02 17:28:48 +00008895 } else if (isa<PragmaCommentDecl>(D))
8896 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008897 else if (isa<OMPThreadPrivateDecl>(D) ||
8898 D->hasAttr<OMPDeclareTargetDeclAttr>())
8899 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008900 else if (isa<PragmaDetectMismatchDecl>(D))
8901 return true;
Nico Weber66220292016-03-02 17:28:48 +00008902 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008903 return !D->getDeclContext()->isDependentContext();
8904 else if (isa<OMPDeclareReductionDecl>(D))
8905 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00008906 else if (isa<ImportDecl>(D))
8907 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00008908 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008909 return false;
8910
8911 // If this is a member of a class template, we do not need to emit it.
8912 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008913 return false;
8914
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008915 // Weak references don't produce any output by themselves.
8916 if (D->hasAttr<WeakRefAttr>())
8917 return false;
8918
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008919 // Aliases and used decls are required.
8920 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8921 return true;
8922
8923 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8924 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008925 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008926 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008927
8928 // Constructors and destructors are required.
8929 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8930 return true;
8931
John McCall6bd2a892013-01-25 22:31:03 +00008932 // The key function for a class is required. This rule only comes
8933 // into play when inline functions can be key functions, though.
8934 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8935 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8936 const CXXRecordDecl *RD = MD->getParent();
8937 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8938 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8939 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8940 return true;
8941 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008942 }
8943 }
8944
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008945 // static, static inline, always_inline, and extern inline functions can
8946 // always be deferred. Normal inline functions can be deferred in C99/C++.
8947 // Implicit template instantiations can also be deferred in C++.
Justin Lebar606f01f2016-10-13 20:52:17 +00008948 return !isDiscardableGVALinkage(GetGVALinkageForFunction(FD));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008949 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008950
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008951 const VarDecl *VD = cast<VarDecl>(D);
8952 assert(VD->isFileVarDecl() && "Expected file scoped var");
8953
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008954 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8955 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008956 return false;
8957
Richard Smitha0e5e542012-11-12 21:38:00 +00008958 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00008959 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00008960 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008961
Richard Smitha0e5e542012-11-12 21:38:00 +00008962 // Variables that have destruction with side-effects are required.
8963 if (VD->getType().isDestructedType())
8964 return true;
8965
8966 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008967 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8968 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008969 return true;
8970
Richard Smithda383632016-08-15 01:33:41 +00008971 // Likewise, variables with tuple-like bindings are required if their
8972 // bindings have side-effects.
8973 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
8974 for (auto *BD : DD->bindings())
8975 if (auto *BindingVD = BD->getHoldingVar())
8976 if (DeclMustBeEmitted(BindingVD))
8977 return true;
8978
Richard Smitha0e5e542012-11-12 21:38:00 +00008979 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008980}
Charles Davis53c59df2010-08-16 03:33:14 +00008981
Reid Kleckner78af0702013-08-27 23:08:25 +00008982CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8983 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008984 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008985 if (IsCXXMethod)
8986 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008987
Alexey Bataeva7547182016-05-18 09:06:38 +00008988 switch (LangOpts.getDefaultCallingConv()) {
8989 case LangOptions::DCC_None:
8990 break;
8991 case LangOptions::DCC_CDecl:
8992 return CC_C;
8993 case LangOptions::DCC_FastCall:
8994 if (getTargetInfo().hasFeature("sse2"))
8995 return CC_X86FastCall;
8996 break;
8997 case LangOptions::DCC_StdCall:
8998 if (!IsVariadic)
8999 return CC_X86StdCall;
9000 break;
9001 case LangOptions::DCC_VectorCall:
9002 // __vectorcall cannot be applied to variadic functions.
9003 if (!IsVariadic)
9004 return CC_X86VectorCall;
9005 break;
9006 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009007 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009008}
9009
Jay Foad39c79802011-01-12 09:06:06 +00009010bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009011 // Pass through to the C++ ABI object
9012 return ABI->isNearlyEmpty(RD);
9013}
9014
Reid Kleckner96f8f932014-02-05 17:27:08 +00009015VTableContextBase *ASTContext::getVTableContext() {
9016 if (!VTContext.get()) {
9017 if (Target->getCXXABI().isMicrosoft())
9018 VTContext.reset(new MicrosoftVTableContext(*this));
9019 else
9020 VTContext.reset(new ItaniumVTableContext(*this));
9021 }
9022 return VTContext.get();
9023}
9024
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009025MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009026 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009027 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009028 case TargetCXXABI::GenericItanium:
9029 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009030 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009031 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009032 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009033 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009034 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009035 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009036 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009037 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009038 }
David Blaikie83d382b2011-09-23 05:06:16 +00009039 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009040}
9041
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009042CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009043
9044size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009045 return ASTRecordLayouts.getMemorySize() +
9046 llvm::capacity_in_bytes(ObjCLayouts) +
9047 llvm::capacity_in_bytes(KeyFunctions) +
9048 llvm::capacity_in_bytes(ObjCImpls) +
9049 llvm::capacity_in_bytes(BlockVarCopyInits) +
9050 llvm::capacity_in_bytes(DeclAttrs) +
9051 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9052 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9053 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9054 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9055 llvm::capacity_in_bytes(OverriddenMethods) +
9056 llvm::capacity_in_bytes(Types) +
9057 llvm::capacity_in_bytes(VariableArrayTypes) +
9058 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009059}
Ted Kremenek540017e2011-10-06 05:00:56 +00009060
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009061/// getIntTypeForBitwidth -
9062/// sets integer QualTy according to specified details:
9063/// bitwidth, signed/unsigned.
9064/// Returns empty type if there is no appropriate target types.
9065QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9066 unsigned Signed) const {
9067 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9068 CanQualType QualTy = getFromTargetType(Ty);
9069 if (!QualTy && DestWidth == 128)
9070 return Signed ? Int128Ty : UnsignedInt128Ty;
9071 return QualTy;
9072}
9073
9074/// getRealTypeForBitwidth -
9075/// sets floating point QualTy according to specified bitwidth.
9076/// Returns empty type if there is no appropriate target types.
9077QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9078 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9079 switch (Ty) {
9080 case TargetInfo::Float:
9081 return FloatTy;
9082 case TargetInfo::Double:
9083 return DoubleTy;
9084 case TargetInfo::LongDouble:
9085 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009086 case TargetInfo::Float128:
9087 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009088 case TargetInfo::NoFloat:
9089 return QualType();
9090 }
9091
9092 llvm_unreachable("Unhandled TargetInfo::RealType value");
9093}
9094
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009095void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9096 if (Number > 1)
9097 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009098}
9099
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009100unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009101 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009102 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009103}
9104
David Majnemer2206bf52014-03-05 08:57:59 +00009105void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9106 if (Number > 1)
9107 StaticLocalNumbers[VD] = Number;
9108}
9109
9110unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009111 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009112 return I != StaticLocalNumbers.end() ? I->second : 1;
9113}
9114
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009115MangleNumberingContext &
9116ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009117 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009118 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009119 if (!MCtx)
9120 MCtx = createMangleNumberingContext();
9121 return *MCtx;
9122}
9123
Justin Lebar20ebffc2016-10-10 16:26:19 +00009124std::unique_ptr<MangleNumberingContext>
9125ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009126 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009127}
9128
David Majnemere7a818f2015-03-06 18:53:55 +00009129const CXXConstructorDecl *
9130ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9131 return ABI->getCopyConstructorForExceptionObject(
9132 cast<CXXRecordDecl>(RD->getFirstDecl()));
9133}
9134
9135void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9136 CXXConstructorDecl *CD) {
9137 return ABI->addCopyConstructorForExceptionObject(
9138 cast<CXXRecordDecl>(RD->getFirstDecl()),
9139 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9140}
9141
David Majnemerdfa6d202015-03-11 18:36:39 +00009142void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
9143 unsigned ParmIdx, Expr *DAE) {
9144 ABI->addDefaultArgExprForConstructor(
9145 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
9146}
9147
9148Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
9149 unsigned ParmIdx) {
9150 return ABI->getDefaultArgExprForConstructor(
9151 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
9152}
9153
David Majnemer00350522015-08-31 18:48:39 +00009154void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9155 TypedefNameDecl *DD) {
9156 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9157}
9158
9159TypedefNameDecl *
9160ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9161 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9162}
9163
9164void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9165 DeclaratorDecl *DD) {
9166 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9167}
9168
9169DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9170 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9171}
9172
Ted Kremenek540017e2011-10-06 05:00:56 +00009173void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9174 ParamIndices[D] = index;
9175}
9176
9177unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9178 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9179 assert(I != ParamIndices.end() &&
9180 "ParmIndices lacks entry set by ParmVarDecl");
9181 return I->second;
9182}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009183
Richard Smithe6c01442013-06-05 00:46:14 +00009184APValue *
9185ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9186 bool MayCreate) {
9187 assert(E && E->getStorageDuration() == SD_Static &&
9188 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009189 if (MayCreate) {
9190 APValue *&MTVI = MaterializedTemporaryValues[E];
9191 if (!MTVI)
9192 MTVI = new (*this) APValue;
9193 return MTVI;
9194 }
Richard Smithe6c01442013-06-05 00:46:14 +00009195
David Majnemer2dcef9e2015-08-13 23:50:15 +00009196 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009197}
9198
Fariborz Jahanian615de762013-05-28 17:37:39 +00009199bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9200 const llvm::Triple &T = getTargetInfo().getTriple();
9201 if (!T.isOSDarwin())
9202 return false;
9203
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009204 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9205 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9206 return false;
9207
Fariborz Jahanian615de762013-05-28 17:37:39 +00009208 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9209 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9210 uint64_t Size = sizeChars.getQuantity();
9211 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9212 unsigned Align = alignChars.getQuantity();
9213 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9214 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9215}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009216
9217namespace {
9218
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009219ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9220 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009221 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009222 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009223 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009224 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009225 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009226}
9227
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009228/// Template specializations to abstract away from pointers and TypeLocs.
9229/// @{
9230template <typename T>
9231ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9232 return ast_type_traits::DynTypedNode::create(*Node);
9233}
9234template <>
9235ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9236 return ast_type_traits::DynTypedNode::create(Node);
9237}
9238template <>
9239ast_type_traits::DynTypedNode
9240createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9241 return ast_type_traits::DynTypedNode::create(Node);
9242}
9243/// @}
9244
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009245 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9246 /// parents as defined by the \c RecursiveASTVisitor.
9247 ///
9248 /// Note that the relationship described here is purely in terms of AST
9249 /// traversal - there are other relationships (for example declaration context)
9250 /// in the AST that are better modeled by special matchers.
9251 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009252 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009253 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009254 public:
9255 /// \brief Builds and returns the translation unit's parent map.
9256 ///
9257 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009258 static std::pair<ASTContext::ParentMapPointers *,
9259 ASTContext::ParentMapOtherNodes *>
9260 buildMap(TranslationUnitDecl &TU) {
9261 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9262 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009263 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009264 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009265 }
9266
9267 private:
9268 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9269
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009270 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9271 ASTContext::ParentMapOtherNodes *OtherParents)
9272 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009273
9274 bool shouldVisitTemplateInstantiations() const {
9275 return true;
9276 }
9277 bool shouldVisitImplicitCode() const {
9278 return true;
9279 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009280
Richard Smith85838722015-11-24 03:09:01 +00009281 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9282 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009283 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009284 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009285 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009286 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009287 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009288 // FIXME: Currently we add the same parent multiple times, but only
9289 // when no memoization data is available for the type.
9290 // For example when we visit all subexpressions of template
9291 // instantiations; this is suboptimal, but benign: the only way to
9292 // visit those is with hasAncestor / hasParent, and those do not create
9293 // new matches.
9294 // The plan is to enable DynTypedNode to be storable in a map or hash
9295 // map. The main problem there is to implement hash functions /
9296 // comparison operators for all types that DynTypedNode supports that
9297 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009298 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009299 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009300 if (const auto *D = ParentStack.back().get<Decl>())
9301 NodeOrVector = D;
9302 else if (const auto *S = ParentStack.back().get<Stmt>())
9303 NodeOrVector = S;
9304 else
9305 NodeOrVector =
9306 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009307 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009308 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9309 auto *Vector = new ASTContext::ParentVector(
9310 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009311 if (auto *Node =
9312 NodeOrVector
9313 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9314 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009315 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009316 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009317
9318 auto *Vector =
9319 NodeOrVector.template get<ASTContext::ParentVector *>();
9320 // Skip duplicates for types that have memoization data.
9321 // We must check that the type has memoization data before calling
9322 // std::find() because DynTypedNode::operator== can't compare all
9323 // types.
9324 bool Found = ParentStack.back().getMemoizationData() &&
9325 std::find(Vector->begin(), Vector->end(),
9326 ParentStack.back()) != Vector->end();
9327 if (!Found)
9328 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009329 }
9330 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009331 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009332 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009333 ParentStack.pop_back();
9334 return Result;
9335 }
9336
9337 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009338 return TraverseNode(DeclNode, DeclNode,
9339 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009340 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009341 }
9342
9343 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009344 return TraverseNode(StmtNode, StmtNode,
9345 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009346 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009347 }
9348
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009349 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009350 return TraverseNode(
9351 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9352 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9353 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009354 }
9355
9356 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9357 return TraverseNode(
9358 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009359 [&] {
9360 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9361 },
9362 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009363 }
9364
9365 ASTContext::ParentMapPointers *Parents;
9366 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009367 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9368
9369 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9370 };
9371
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009372} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009373
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009374template <typename NodeTy, typename MapTy>
9375static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9376 const MapTy &Map) {
9377 auto I = Map.find(Node);
9378 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009379 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009380 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009381 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009382 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009383 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009384 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009385}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009386
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009387ASTContext::DynTypedNodeList
9388ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9389 if (!PointerParents) {
9390 // We always need to run over the whole translation unit, as
9391 // hasAncestor can escape any subtree.
9392 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9393 PointerParents.reset(Maps.first);
9394 OtherParents.reset(Maps.second);
9395 }
9396 if (Node.getNodeKind().hasPointerIdentity())
9397 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9398 return getDynNodeFromMap(Node, *OtherParents);
9399}
9400
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009401bool
9402ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9403 const ObjCMethodDecl *MethodImpl) {
9404 // No point trying to match an unavailable/deprecated mothod.
9405 if (MethodDecl->hasAttr<UnavailableAttr>()
9406 || MethodDecl->hasAttr<DeprecatedAttr>())
9407 return false;
9408 if (MethodDecl->getObjCDeclQualifier() !=
9409 MethodImpl->getObjCDeclQualifier())
9410 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009411 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009412 return false;
9413
9414 if (MethodDecl->param_size() != MethodImpl->param_size())
9415 return false;
9416
9417 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9418 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9419 EF = MethodDecl->param_end();
9420 IM != EM && IF != EF; ++IM, ++IF) {
9421 const ParmVarDecl *DeclVar = (*IF);
9422 const ParmVarDecl *ImplVar = (*IM);
9423 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9424 return false;
9425 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9426 return false;
9427 }
9428 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9429
9430}
Richard Smith053f6c62014-05-16 23:01:30 +00009431
9432// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9433// doesn't include ASTContext.h
9434template
9435clang::LazyGenerationalUpdatePtr<
9436 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9437clang::LazyGenerationalUpdatePtr<
9438 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9439 const clang::ASTContext &Ctx, Decl *Value);