blob: 709de4368d8b241f4574da7b0b1a4345a2e70972 [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
Richard Smithb50df912016-10-13 23:04:14 +0000891 auto *Merged = &MergedDefModules[ND];
892 if (auto *CanonDef = Merged->CanonicalDef) {
893 ND = CanonDef;
894 Merged = &MergedDefModules[ND];
895 }
896 assert(!Merged->CanonicalDef && "canonical def not canonical");
897
898 Merged->MergedModules.push_back(M);
899
900 if (!getLangOpts().ModulesLocalVisibility)
Richard Smith42413142015-05-15 20:05:43 +0000901 ND->setHidden(false);
902}
903
Richard Smithb50df912016-10-13 23:04:14 +0000904void ASTContext::mergeDefinitionIntoModulesOf(NamedDecl *Def,
905 NamedDecl *Other) {
906 // We need to know the owning module of the merge source.
907 assert(Other->isFromASTFile() && "merge of non-imported decl not supported");
908 assert(Def != Other && "merging definition into itself");
909
Richard Smith33d88ea2016-10-14 02:35:11 +0000910 if (!Other->isHidden()) {
Richard Smithb50df912016-10-13 23:04:14 +0000911 Def->setHidden(false);
Richard Smith33d88ea2016-10-14 02:35:11 +0000912 return;
913 }
914
915 assert(Other->getImportedOwningModule() &&
916 "hidden, imported declaration has no owning module");
Richard Smithb50df912016-10-13 23:04:14 +0000917
918 // Mark Def as the canonical definition of merged definition Other.
919 {
920 auto &OtherMerged = MergedDefModules[Other];
921 assert((!OtherMerged.CanonicalDef || OtherMerged.CanonicalDef == Def) &&
922 "mismatched canonical definitions for declaration");
923 OtherMerged.CanonicalDef = Def;
924 }
925
926 auto &Merged = MergedDefModules[Def];
927 // Grab this again, we potentially just invalidated our reference.
928 auto &OtherMerged = MergedDefModules[Other];
929
930 if (Module *M = Other->getImportedOwningModule())
931 Merged.MergedModules.push_back(M);
932
933 // If this definition had any others merged into it, they're now merged into
934 // the canonical definition instead.
935 if (!OtherMerged.MergedModules.empty()) {
936 assert(!Merged.CanonicalDef && "canonical definition not canonical");
937 if (Merged.MergedModules.empty())
938 Merged.MergedModules = std::move(OtherMerged.MergedModules);
939 else
940 Merged.MergedModules.insert(Merged.MergedModules.end(),
941 OtherMerged.MergedModules.begin(),
942 OtherMerged.MergedModules.end());
943 OtherMerged.MergedModules.clear();
944 }
945}
946
Richard Smith42413142015-05-15 20:05:43 +0000947void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
948 auto It = MergedDefModules.find(ND);
949 if (It == MergedDefModules.end())
950 return;
951
Richard Smithb50df912016-10-13 23:04:14 +0000952 if (auto *CanonDef = It->second.CanonicalDef) {
953 It = MergedDefModules.find(CanonDef);
954 if (It == MergedDefModules.end())
955 return;
956 }
957
958 auto &Merged = It->second.MergedModules;
Richard Smith42413142015-05-15 20:05:43 +0000959 llvm::DenseSet<Module*> Found;
960 for (Module *&M : Merged)
961 if (!Found.insert(M).second)
962 M = nullptr;
963 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
964}
965
Richard Smithdc1f0422016-07-20 19:10:16 +0000966void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
967 if (LazyInitializers.empty())
968 return;
969
970 auto *Source = Ctx.getExternalSource();
971 assert(Source && "lazy initializers but no external source");
972
973 auto LazyInits = std::move(LazyInitializers);
974 LazyInitializers.clear();
975
976 for (auto ID : LazyInits)
977 Initializers.push_back(Source->GetExternalDecl(ID));
978
979 assert(LazyInitializers.empty() &&
980 "GetExternalDecl for lazy module initializer added more inits");
981}
982
983void ASTContext::addModuleInitializer(Module *M, Decl *D) {
984 // One special case: if we add a module initializer that imports another
985 // module, and that module's only initializer is an ImportDecl, simplify.
986 if (auto *ID = dyn_cast<ImportDecl>(D)) {
987 auto It = ModuleInitializers.find(ID->getImportedModule());
988
989 // Maybe the ImportDecl does nothing at all. (Common case.)
990 if (It == ModuleInitializers.end())
991 return;
992
993 // Maybe the ImportDecl only imports another ImportDecl.
994 auto &Imported = *It->second;
995 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
996 Imported.resolve(*this);
997 auto *OnlyDecl = Imported.Initializers.front();
998 if (isa<ImportDecl>(OnlyDecl))
999 D = OnlyDecl;
1000 }
1001 }
1002
1003 auto *&Inits = ModuleInitializers[M];
1004 if (!Inits)
1005 Inits = new (*this) PerModuleInitializers;
1006 Inits->Initializers.push_back(D);
1007}
1008
1009void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1010 auto *&Inits = ModuleInitializers[M];
1011 if (!Inits)
1012 Inits = new (*this) PerModuleInitializers;
1013 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1014 IDs.begin(), IDs.end());
1015}
1016
1017ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
1018 auto It = ModuleInitializers.find(M);
1019 if (It == ModuleInitializers.end())
1020 return None;
1021
1022 auto *Inits = It->second;
1023 Inits->resolve(*this);
1024 return Inits->Initializers;
1025}
1026
Richard Smithf19e1272015-03-07 00:04:49 +00001027ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1028 if (!ExternCContext)
1029 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1030
1031 return ExternCContext;
1032}
1033
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001034BuiltinTemplateDecl *
1035ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1036 const IdentifierInfo *II) const {
1037 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1038 BuiltinTemplate->setImplicit();
1039 TUDecl->addDecl(BuiltinTemplate);
1040
1041 return BuiltinTemplate;
1042}
1043
1044BuiltinTemplateDecl *
1045ASTContext::getMakeIntegerSeqDecl() const {
1046 if (!MakeIntegerSeqDecl)
1047 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1048 getMakeIntegerSeqName());
1049 return MakeIntegerSeqDecl;
1050}
1051
Eric Fiselier6ad68552016-07-01 01:24:09 +00001052BuiltinTemplateDecl *
1053ASTContext::getTypePackElementDecl() const {
1054 if (!TypePackElementDecl)
1055 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1056 getTypePackElementName());
1057 return TypePackElementDecl;
1058}
1059
Alp Toker2dea15b2013-12-17 01:22:38 +00001060RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1061 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001062 SourceLocation Loc;
1063 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001064 if (getLangOpts().CPlusPlus)
1065 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1066 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001067 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001068 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1069 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001070 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001071 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1072 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001073 return NewDecl;
1074}
1075
1076TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1077 StringRef Name) const {
1078 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1079 TypedefDecl *NewDecl = TypedefDecl::Create(
1080 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1081 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1082 NewDecl->setImplicit();
1083 return NewDecl;
1084}
1085
Douglas Gregor801c99d2011-08-12 06:49:56 +00001086TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001087 if (!Int128Decl)
1088 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001089 return Int128Decl;
1090}
1091
1092TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001093 if (!UInt128Decl)
1094 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001095 return UInt128Decl;
1096}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001097
John McCall48f2d582009-10-23 23:03:21 +00001098void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001099 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001100 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001101 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001102}
1103
Artem Belevichb5bc9232015-09-22 17:23:22 +00001104void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1105 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001106 assert((!this->Target || this->Target == &Target) &&
1107 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001108 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001109
Douglas Gregore8bbc122011-09-02 00:18:52 +00001110 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001111 this->AuxTarget = AuxTarget;
1112
Douglas Gregore8bbc122011-09-02 00:18:52 +00001113 ABI.reset(createCXXABI(Target));
1114 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001115 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001116
Chris Lattner970e54e2006-11-12 00:37:36 +00001117 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001118 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001119
Chris Lattner970e54e2006-11-12 00:37:36 +00001120 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001121 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001122 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001123 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001124 InitBuiltinType(CharTy, BuiltinType::Char_S);
1125 else
1126 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001127 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001128 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1129 InitBuiltinType(ShortTy, BuiltinType::Short);
1130 InitBuiltinType(IntTy, BuiltinType::Int);
1131 InitBuiltinType(LongTy, BuiltinType::Long);
1132 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattner970e54e2006-11-12 00:37:36 +00001134 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001135 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1136 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1137 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1138 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1139 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattner970e54e2006-11-12 00:37:36 +00001141 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001142 InitBuiltinType(FloatTy, BuiltinType::Float);
1143 InitBuiltinType(DoubleTy, BuiltinType::Double);
1144 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001145
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001146 // GNU extension, __float128 for IEEE quadruple precision
1147 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1148
Chris Lattnerf122cef2009-04-30 02:43:43 +00001149 // GNU extension, 128-bit integers.
1150 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1151 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1152
Hans Wennborg0d81e012013-05-10 10:08:40 +00001153 // C++ 3.9.1p5
1154 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1155 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1156 else // -fshort-wchar makes wchar_t be unsigned.
1157 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1158 if (LangOpts.CPlusPlus && LangOpts.WChar)
1159 WideCharTy = WCharTy;
1160 else {
1161 // C99 (or C++ using -fno-wchar).
1162 WideCharTy = getFromTargetType(Target.getWCharType());
1163 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001164
James Molloy36365542012-05-04 10:55:22 +00001165 WIntTy = getFromTargetType(Target.getWIntType());
1166
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001167 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1168 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1169 else // C99
1170 Char16Ty = getFromTargetType(Target.getChar16Type());
1171
1172 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1173 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1174 else // C99
1175 Char32Ty = getFromTargetType(Target.getChar32Type());
1176
Douglas Gregor4619e432008-12-05 23:32:09 +00001177 // Placeholder type for type-dependent expressions whose type is
1178 // completely unknown. No code should ever check a type against
1179 // DependentTy and users should never see it; however, it is here to
1180 // help diagnose failures to properly check for type-dependent
1181 // expressions.
1182 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001183
John McCall36e7fe32010-10-12 00:20:44 +00001184 // Placeholder type for functions.
1185 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1186
John McCall0009fcc2011-04-26 20:42:42 +00001187 // Placeholder type for bound members.
1188 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1189
John McCall526ab472011-10-25 17:37:35 +00001190 // Placeholder type for pseudo-objects.
1191 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1192
John McCall31996342011-04-07 08:22:57 +00001193 // "any" type; useful for debugger-like clients.
1194 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1195
John McCall8a6b59a2011-10-17 18:09:15 +00001196 // Placeholder type for unbridged ARC casts.
1197 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1198
Eli Friedman34866c72012-08-31 00:14:07 +00001199 // Placeholder type for builtin functions.
1200 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1201
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001202 // Placeholder type for OMP array sections.
1203 if (LangOpts.OpenMP)
1204 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1205
Chris Lattner970e54e2006-11-12 00:37:36 +00001206 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001207 FloatComplexTy = getComplexType(FloatTy);
1208 DoubleComplexTy = getComplexType(DoubleTy);
1209 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001210 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001211
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001212 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001213 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1214 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001215 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001216
Alexey Bader954ba212016-04-08 13:40:33 +00001217 if (LangOpts.OpenCL) {
1218#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1219 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001220#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001221
Guy Benyei61054192013-02-07 10:55:47 +00001222 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001223 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001224 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1225 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1226 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1227 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001228 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001229
1230 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001231 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1232 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001233
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001234 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001235
1236 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001237
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001238 // void * type
1239 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001240
1241 // nullptr type (C++0x 2.14.7)
1242 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001243
1244 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1245 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001246
1247 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001248 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001249}
1250
David Blaikie9c902b52011-09-25 23:23:43 +00001251DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001252 return SourceMgr.getDiagnostics();
1253}
1254
Douglas Gregor561eceb2010-08-30 16:49:28 +00001255AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1256 AttrVec *&Result = DeclAttrs[D];
1257 if (!Result) {
1258 void *Mem = Allocate(sizeof(AttrVec));
1259 Result = new (Mem) AttrVec;
1260 }
1261
1262 return *Result;
1263}
1264
1265/// \brief Erase the attributes corresponding to the given declaration.
1266void ASTContext::eraseDeclAttrs(const Decl *D) {
1267 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1268 if (Pos != DeclAttrs.end()) {
1269 Pos->second->~AttrVec();
1270 DeclAttrs.erase(Pos);
1271 }
1272}
1273
Larisse Voufo39a1e502013-08-06 01:03:05 +00001274// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001275MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001276ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001277 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001278 return getTemplateOrSpecializationInfo(Var)
1279 .dyn_cast<MemberSpecializationInfo *>();
1280}
1281
1282ASTContext::TemplateOrSpecializationInfo
1283ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1284 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1285 TemplateOrInstantiation.find(Var);
1286 if (Pos == TemplateOrInstantiation.end())
1287 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001288
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001289 return Pos->second;
1290}
1291
Mike Stump11289f42009-09-09 15:08:12 +00001292void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001293ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001294 TemplateSpecializationKind TSK,
1295 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001296 assert(Inst->isStaticDataMember() && "Not a static data member");
1297 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001298 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1299 Tmpl, TSK, PointOfInstantiation));
1300}
1301
1302void
1303ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1304 TemplateOrSpecializationInfo TSI) {
1305 assert(!TemplateOrInstantiation[Inst] &&
1306 "Already noted what the variable was instantiated from");
1307 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001308}
1309
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001310FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1311 const FunctionDecl *FD){
1312 assert(FD && "Specialization is 0");
1313 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001314 = ClassScopeSpecializationPattern.find(FD);
1315 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001316 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001317
1318 return Pos->second;
1319}
1320
1321void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1322 FunctionDecl *Pattern) {
1323 assert(FD && "Specialization is 0");
1324 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001325 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001326}
1327
John McCalle61f2ba2009-11-18 02:36:19 +00001328NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001329ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001330 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001331 = InstantiatedFromUsingDecl.find(UUD);
1332 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001333 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001335 return Pos->second;
1336}
1337
1338void
John McCallb96ec562009-12-04 22:46:56 +00001339ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1340 assert((isa<UsingDecl>(Pattern) ||
1341 isa<UnresolvedUsingValueDecl>(Pattern) ||
1342 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1343 "pattern decl is not a using decl");
1344 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1345 InstantiatedFromUsingDecl[Inst] = Pattern;
1346}
1347
1348UsingShadowDecl *
1349ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1350 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1351 = InstantiatedFromUsingShadowDecl.find(Inst);
1352 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001353 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001354
1355 return Pos->second;
1356}
1357
1358void
1359ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1360 UsingShadowDecl *Pattern) {
1361 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1362 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001363}
1364
Anders Carlsson5da84842009-09-01 04:26:58 +00001365FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1366 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1367 = InstantiatedFromUnnamedFieldDecl.find(Field);
1368 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001369 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001370
Anders Carlsson5da84842009-09-01 04:26:58 +00001371 return Pos->second;
1372}
1373
1374void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1375 FieldDecl *Tmpl) {
1376 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1377 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1378 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1379 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001380
Anders Carlsson5da84842009-09-01 04:26:58 +00001381 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1382}
1383
Douglas Gregor832940b2010-03-02 23:58:15 +00001384ASTContext::overridden_cxx_method_iterator
1385ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001386 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1387 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001388 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001389 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001390 return Pos->second.begin();
1391}
1392
1393ASTContext::overridden_cxx_method_iterator
1394ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001395 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1396 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001397 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001398 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001399 return Pos->second.end();
1400}
1401
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001402unsigned
1403ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001404 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1405 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001406 if (Pos == OverriddenMethods.end())
1407 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001408 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001409}
1410
Clement Courbet6ecaec82016-07-05 07:49:31 +00001411ASTContext::overridden_method_range
1412ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1413 return overridden_method_range(overridden_methods_begin(Method),
1414 overridden_methods_end(Method));
1415}
1416
Douglas Gregor832940b2010-03-02 23:58:15 +00001417void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1418 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001419 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001420 OverriddenMethods[Method].push_back(Overridden);
1421}
1422
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001423void ASTContext::getOverriddenMethods(
1424 const NamedDecl *D,
1425 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001426 assert(D);
1427
1428 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001429 Overridden.append(overridden_methods_begin(CXXMethod),
1430 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001431 return;
1432 }
1433
1434 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1435 if (!Method)
1436 return;
1437
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001438 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1439 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001440 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001441}
1442
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001443void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1444 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1445 assert(!Import->isFromASTFile() && "Non-local import declaration");
1446 if (!FirstLocalImport) {
1447 FirstLocalImport = Import;
1448 LastLocalImport = Import;
1449 return;
1450 }
1451
1452 LastLocalImport->NextLocalImport = Import;
1453 LastLocalImport = Import;
1454}
1455
Chris Lattner53cfe802007-07-18 17:52:12 +00001456//===----------------------------------------------------------------------===//
1457// Type Sizing and Analysis
1458//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001459
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001460/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1461/// scalar floating point type.
1462const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001463 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001464 assert(BT && "Not a floating point type!");
1465 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001466 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001467 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001468 case BuiltinType::Float: return Target->getFloatFormat();
1469 case BuiltinType::Double: return Target->getDoubleFormat();
1470 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001471 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001472 }
1473}
1474
Rafael Espindola71eccb32013-08-08 19:53:46 +00001475CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001476 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001477
John McCall94268702010-10-08 18:24:19 +00001478 bool UseAlignAttrOnly = false;
1479 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1480 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001481
John McCall94268702010-10-08 18:24:19 +00001482 // __attribute__((aligned)) can increase or decrease alignment
1483 // *except* on a struct or struct member, where it only increases
1484 // alignment unless 'packed' is also specified.
1485 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001486 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001487 // ignore that possibility; Sema should diagnose it.
1488 if (isa<FieldDecl>(D)) {
1489 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1490 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1491 } else {
1492 UseAlignAttrOnly = true;
1493 }
1494 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001495 else if (isa<FieldDecl>(D))
1496 UseAlignAttrOnly =
1497 D->hasAttr<PackedAttr>() ||
1498 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001499
John McCall4e819612011-01-20 07:57:12 +00001500 // If we're using the align attribute only, just ignore everything
1501 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001502 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001503 // do nothing
1504
John McCall94268702010-10-08 18:24:19 +00001505 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001506 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001507 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001508 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001509 T = RT->getPointeeType();
1510 else
1511 T = getPointerType(RT->getPointeeType());
1512 }
Richard Smithf6d70302014-06-10 23:34:28 +00001513 QualType BaseT = getBaseElementType(T);
1514 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001515 // Adjust alignments of declarations with array type by the
1516 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001517 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001518 unsigned MinWidth = Target->getLargeArrayMinWidth();
1519 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001520 if (isa<VariableArrayType>(arrayType))
1521 Align = std::max(Align, Target->getLargeArrayAlign());
1522 else if (isa<ConstantArrayType>(arrayType) &&
1523 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1524 Align = std::max(Align, Target->getLargeArrayAlign());
1525 }
John McCall33ddac02011-01-19 10:06:00 +00001526 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001527 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001528 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001529 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001530 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1531 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001532 }
John McCall4e819612011-01-20 07:57:12 +00001533
1534 // Fields can be subject to extra alignment constraints, like if
1535 // the field is packed, the struct is packed, or the struct has a
1536 // a max-field-alignment constraint (#pragma pack). So calculate
1537 // the actual alignment of the field within the struct, and then
1538 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001539 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1540 const RecordDecl *Parent = Field->getParent();
1541 // We can only produce a sensible answer if the record is valid.
1542 if (!Parent->isInvalidDecl()) {
1543 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001544
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001545 // Start with the record's overall alignment.
1546 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001547
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001548 // Use the GCD of that and the offset within the record.
1549 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1550 if (Offset > 0) {
1551 // Alignment is always a power of 2, so the GCD will be a power of 2,
1552 // which means we get to do this crazy thing instead of Euclid's.
1553 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1554 if (LowBitOfOffset < FieldAlign)
1555 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1556 }
1557
1558 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001559 }
Charles Davis3fc51072010-02-23 04:52:00 +00001560 }
Chris Lattner68061312009-01-24 21:53:27 +00001561 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001562
Ken Dyckcc56c542011-01-15 18:38:59 +00001563 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001564}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001565
John McCallf1249922012-08-21 04:10:00 +00001566// getTypeInfoDataSizeInChars - Return the size of a type, in
1567// chars. If the type is a record, its data size is returned. This is
1568// the size of the memcpy that's performed when assigning this type
1569// using a trivial copy/move assignment operator.
1570std::pair<CharUnits, CharUnits>
1571ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1572 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1573
1574 // In C++, objects can sometimes be allocated into the tail padding
1575 // of a base-class subobject. We decide whether that's possible
1576 // during class layout, so here we can just trust the layout results.
1577 if (getLangOpts().CPlusPlus) {
1578 if (const RecordType *RT = T->getAs<RecordType>()) {
1579 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1580 sizeAndAlign.first = layout.getDataSize();
1581 }
1582 }
1583
1584 return sizeAndAlign;
1585}
1586
Richard Trieu04d2d942013-05-14 21:59:17 +00001587/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1588/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1589std::pair<CharUnits, CharUnits>
1590static getConstantArrayInfoInChars(const ASTContext &Context,
1591 const ConstantArrayType *CAT) {
1592 std::pair<CharUnits, CharUnits> EltInfo =
1593 Context.getTypeInfoInChars(CAT->getElementType());
1594 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001595 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1596 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001597 "Overflow in array type char size evaluation");
1598 uint64_t Width = EltInfo.first.getQuantity() * Size;
1599 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001600 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1601 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001602 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001603 return std::make_pair(CharUnits::fromQuantity(Width),
1604 CharUnits::fromQuantity(Align));
1605}
1606
John McCall87fe5d52010-05-20 01:18:31 +00001607std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001608ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001609 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1610 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001611 TypeInfo Info = getTypeInfo(T);
1612 return std::make_pair(toCharUnitsFromBits(Info.Width),
1613 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001614}
1615
1616std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001617ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001618 return getTypeInfoInChars(T.getTypePtr());
1619}
1620
David Majnemer34b57492014-07-30 01:30:47 +00001621bool ASTContext::isAlignmentRequired(const Type *T) const {
1622 return getTypeInfo(T).AlignIsRequired;
1623}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001624
David Majnemer34b57492014-07-30 01:30:47 +00001625bool ASTContext::isAlignmentRequired(QualType T) const {
1626 return isAlignmentRequired(T.getTypePtr());
1627}
1628
Richard Smithb2f0f052016-10-10 18:54:32 +00001629unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1630 // An alignment on a typedef overrides anything else.
1631 if (auto *TT = T->getAs<TypedefType>())
1632 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1633 return Align;
1634
1635 // If we have an (array of) complete type, we're done.
1636 T = getBaseElementType(T);
1637 if (!T->isIncompleteType())
1638 return getTypeAlign(T);
1639
1640 // If we had an array type, its element type might be a typedef
1641 // type with an alignment attribute.
1642 if (auto *TT = T->getAs<TypedefType>())
1643 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1644 return Align;
1645
1646 // Otherwise, see if the declaration of the type had an attribute.
1647 if (auto *TT = T->getAs<TagType>())
1648 return TT->getDecl()->getMaxAlignment();
1649
1650 return 0;
1651}
1652
David Majnemer34b57492014-07-30 01:30:47 +00001653TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001654 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1655 if (I != MemoizedTypeInfo.end())
1656 return I->second;
1657
1658 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1659 TypeInfo TI = getTypeInfoImpl(T);
1660 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001661 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001662}
1663
1664/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1665/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001666///
1667/// FIXME: Pointers into different addr spaces could have different sizes and
1668/// alignment requirements: getPointerInfo should take an AddrSpace, this
1669/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001670TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1671 uint64_t Width = 0;
1672 unsigned Align = 8;
1673 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001674 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001675#define TYPE(Class, Base)
1676#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001677#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001678#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001679#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1680 case Type::Class: \
1681 assert(!T->isDependentType() && "should not see dependent types here"); \
1682 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001683#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001684 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001685
Chris Lattner355332d2007-07-13 22:27:08 +00001686 case Type::FunctionNoProto:
1687 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001688 // GCC extension: alignof(function) = 32 bits
1689 Width = 0;
1690 Align = 32;
1691 break;
1692
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001693 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001694 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001695 Width = 0;
1696 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1697 break;
1698
Steve Naroff5c131802007-08-30 01:06:46 +00001699 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001700 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001701
David Majnemer34b57492014-07-30 01:30:47 +00001702 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001703 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001704 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001705 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001706 Width = EltInfo.Width * Size;
1707 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001708 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1709 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001710 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001711 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001712 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001713 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001714 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001715 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001716 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1717 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001718 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001719 // If the alignment is not a power of 2, round up to the next power of 2.
1720 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001721 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001722 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001723 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001724 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001725 // Adjust the alignment based on the target max.
1726 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1727 if (TargetVectorAlign && TargetVectorAlign < Align)
1728 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001729 break;
1730 }
Chris Lattner647fb222007-07-18 18:26:58 +00001731
Chris Lattner7570e9c2008-03-08 08:52:55 +00001732 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001733 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001734 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001735 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001736 // GCC extension: alignof(void) = 8 bits.
1737 Width = 0;
1738 Align = 8;
1739 break;
1740
Chris Lattner6a4f7452007-12-19 19:23:28 +00001741 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001742 Width = Target->getBoolWidth();
1743 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001744 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001745 case BuiltinType::Char_S:
1746 case BuiltinType::Char_U:
1747 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001748 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001749 Width = Target->getCharWidth();
1750 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001751 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001752 case BuiltinType::WChar_S:
1753 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001754 Width = Target->getWCharWidth();
1755 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001756 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001757 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001758 Width = Target->getChar16Width();
1759 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001760 break;
1761 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001762 Width = Target->getChar32Width();
1763 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001764 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001765 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001766 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001767 Width = Target->getShortWidth();
1768 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001769 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001770 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001771 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001772 Width = Target->getIntWidth();
1773 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001774 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001775 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001776 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001777 Width = Target->getLongWidth();
1778 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001779 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001780 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001781 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001782 Width = Target->getLongLongWidth();
1783 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001784 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001785 case BuiltinType::Int128:
1786 case BuiltinType::UInt128:
1787 Width = 128;
1788 Align = 128; // int128_t is 128-bit aligned on all targets.
1789 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001790 case BuiltinType::Half:
1791 Width = Target->getHalfWidth();
1792 Align = Target->getHalfAlign();
1793 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001794 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001795 Width = Target->getFloatWidth();
1796 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001797 break;
1798 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001799 Width = Target->getDoubleWidth();
1800 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001801 break;
1802 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001803 Width = Target->getLongDoubleWidth();
1804 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001805 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001806 case BuiltinType::Float128:
1807 Width = Target->getFloat128Width();
1808 Align = Target->getFloat128Align();
1809 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001810 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001811 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1812 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001813 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001814 case BuiltinType::ObjCId:
1815 case BuiltinType::ObjCClass:
1816 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001817 Width = Target->getPointerWidth(0);
1818 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001819 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001820 case BuiltinType::OCLSampler: {
1821 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1822 Width = Target->getPointerWidth(AS);
1823 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001824 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001825 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001826 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001827 case BuiltinType::OCLClkEvent:
1828 case BuiltinType::OCLQueue:
1829 case BuiltinType::OCLNDRange:
1830 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001831 // Currently these types are pointers to opaque types.
1832 Width = Target->getPointerWidth(0);
1833 Align = Target->getPointerAlign(0);
1834 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001835#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1836 case BuiltinType::Id:
1837#include "clang/Basic/OpenCLImageTypes.def"
1838 {
1839 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1840 Width = Target->getPointerWidth(AS);
1841 Align = Target->getPointerAlign(AS);
1842 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001843 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001844 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001845 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001846 Width = Target->getPointerWidth(0);
1847 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001848 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001849 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001850 unsigned AS = getTargetAddressSpace(
1851 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001852 Width = Target->getPointerWidth(AS);
1853 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001854 break;
1855 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001856 case Type::LValueReference:
1857 case Type::RValueReference: {
1858 // alignof and sizeof should never enter this code path here, so we go
1859 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001860 unsigned AS = getTargetAddressSpace(
1861 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001862 Width = Target->getPointerWidth(AS);
1863 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001864 break;
1865 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001866 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001867 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001868 Width = Target->getPointerWidth(AS);
1869 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001870 break;
1871 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001872 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001873 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001874 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001875 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001876 }
Chris Lattner647fb222007-07-18 18:26:58 +00001877 case Type::Complex: {
1878 // Complex types have the same alignment as their elements, but twice the
1879 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001880 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1881 Width = EltInfo.Width * 2;
1882 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001883 break;
1884 }
John McCall8b07ec22010-05-15 11:32:37 +00001885 case Type::ObjCObject:
1886 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001887 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001888 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001889 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001890 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001891 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001892 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001893 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001894 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001895 break;
1896 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001897 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001898 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001899 const TagType *TT = cast<TagType>(T);
1900
1901 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001902 Width = 8;
1903 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001904 break;
1905 }
Mike Stump11289f42009-09-09 15:08:12 +00001906
David Majnemer475b25e2015-01-21 10:54:38 +00001907 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1908 const EnumDecl *ED = ET->getDecl();
1909 TypeInfo Info =
1910 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1911 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1912 Info.Align = AttrAlign;
1913 Info.AlignIsRequired = true;
1914 }
1915 return Info;
1916 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001917
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001918 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001919 const RecordDecl *RD = RT->getDecl();
1920 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001921 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001922 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001923 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001924 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001925 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001926
Chris Lattner63d2b362009-10-22 05:17:15 +00001927 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001928 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1929 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001930
Richard Smith30482bc2011-02-20 03:19:35 +00001931 case Type::Auto: {
1932 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001933 assert(!A->getDeducedType().isNull() &&
1934 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001935 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001936 }
1937
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001938 case Type::Paren:
1939 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1940
Manman Rene6be26c2016-09-13 17:25:08 +00001941 case Type::ObjCTypeParam:
1942 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1943
Douglas Gregoref462e62009-04-30 17:32:17 +00001944 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001945 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001946 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001947 // If the typedef has an aligned attribute on it, it overrides any computed
1948 // alignment we have. This violates the GCC documentation (which says that
1949 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001950 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001951 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001952 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001953 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001954 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001955 AlignIsRequired = Info.AlignIsRequired;
1956 }
David Majnemer34b57492014-07-30 01:30:47 +00001957 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001958 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001959 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001960
Abramo Bagnara6150c882010-05-11 21:36:43 +00001961 case Type::Elaborated:
1962 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001963
John McCall81904512011-01-06 01:58:22 +00001964 case Type::Attributed:
1965 return getTypeInfo(
1966 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1967
Eli Friedman0dfb8892011-10-06 23:00:33 +00001968 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001969 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001970 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1971 Width = Info.Width;
1972 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001973
1974 // If the size of the type doesn't exceed the platform's max
1975 // atomic promotion width, make the size and alignment more
1976 // favorable to atomic operations:
1977 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1978 // Round the size up to a power of 2.
1979 if (!llvm::isPowerOf2_64(Width))
1980 Width = llvm::NextPowerOf2(Width);
1981
1982 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001983 Align = static_cast<unsigned>(Width);
1984 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001985 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001986 break;
1987
1988 case Type::Pipe: {
1989 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1990 Width = Info.Width;
1991 Align = Info.Align;
1992 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001993
Douglas Gregoref462e62009-04-30 17:32:17 +00001994 }
Mike Stump11289f42009-09-09 15:08:12 +00001995
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001996 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001997 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001998}
1999
Alexey Bataev00396512015-07-02 03:40:19 +00002000unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2001 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2002 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2003 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2004 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2005 getTargetInfo().getABI() == "elfv1-qpx" &&
2006 T->isSpecificBuiltinType(BuiltinType::Double))
2007 SimdAlign = 256;
2008 return SimdAlign;
2009}
2010
Ken Dyckcc56c542011-01-15 18:38:59 +00002011/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2012CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2013 return CharUnits::fromQuantity(BitSize / getCharWidth());
2014}
2015
Ken Dyckb0fcc592011-02-11 01:54:29 +00002016/// toBits - Convert a size in characters to a size in characters.
2017int64_t ASTContext::toBits(CharUnits CharSize) const {
2018 return CharSize.getQuantity() * getCharWidth();
2019}
2020
Ken Dyck8c89d592009-12-22 14:23:30 +00002021/// getTypeSizeInChars - Return the size of the specified type, in characters.
2022/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002023CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002024 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002025}
Jay Foad39c79802011-01-12 09:06:06 +00002026CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002027 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002028}
2029
Ken Dycka6046ab2010-01-26 17:25:18 +00002030/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002031/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002032CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002033 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002034}
Jay Foad39c79802011-01-12 09:06:06 +00002035CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002036 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002037}
2038
Chris Lattnera3402cd2009-01-27 18:08:34 +00002039/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2040/// type for the current target in bits. This can be different than the ABI
2041/// alignment in cases where it is beneficial for performance to overalign
2042/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002043unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002044 TypeInfo TI = getTypeInfo(T);
2045 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002046
David Majnemere1544562015-04-24 01:25:05 +00002047 T = T->getBaseElementTypeUnsafe();
2048
2049 // The preferred alignment of member pointers is that of a pointer.
2050 if (T->isMemberPointerType())
2051 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2052
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002053 if (!Target->allowsLargerPreferedTypeAlignment())
2054 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002055
Eli Friedman7ab09572009-05-25 21:27:19 +00002056 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002057 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002058 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002059 if (const EnumType *ET = T->getAs<EnumType>())
2060 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002061 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002062 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2063 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002064 // Don't increase the alignment if an alignment attribute was specified on a
2065 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002066 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002067 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002068
Chris Lattnera3402cd2009-01-27 18:08:34 +00002069 return ABIAlign;
2070}
2071
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002072/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2073/// for __attribute__((aligned)) on this target, to be used if no alignment
2074/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002075unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002076 return getTargetInfo().getDefaultAlignForAttributeAligned();
2077}
2078
Ulrich Weigandfa806422013-05-06 16:23:57 +00002079/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2080/// to a global variable of the specified type.
2081unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2082 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2083}
2084
2085/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2086/// should be given to a global variable of the specified type.
2087CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2088 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2089}
2090
David Majnemer08ef2ba2015-06-23 20:34:18 +00002091CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2092 CharUnits Offset = CharUnits::Zero();
2093 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2094 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2095 Offset += Layout->getBaseClassOffset(Base);
2096 Layout = &getASTRecordLayout(Base);
2097 }
2098 return Offset;
2099}
2100
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002101/// DeepCollectObjCIvars -
2102/// This routine first collects all declared, but not synthesized, ivars in
2103/// super class and then collects all ivars, including those synthesized for
2104/// current class. This routine is used for implementation of current class
2105/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002106///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002107void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2108 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002109 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002110 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2111 DeepCollectObjCIvars(SuperClass, false, Ivars);
2112 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002113 for (const auto *I : OI->ivars())
2114 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002115 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002116 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002117 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002118 Iv= Iv->getNextIvar())
2119 Ivars.push_back(Iv);
2120 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002121}
2122
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002123/// CollectInheritedProtocols - Collect all protocols in current class and
2124/// those inherited by it.
2125void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002126 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002127 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002128 // We can use protocol_iterator here instead of
2129 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002130 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002131 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002132 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002133
2134 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002135 for (const auto *Cat : OI->visible_categories())
2136 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002137
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002138 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2139 while (SD) {
2140 CollectInheritedProtocols(SD, Protocols);
2141 SD = SD->getSuperClass();
2142 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002143 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002144 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002145 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002146 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002147 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002148 // Insert the protocol.
2149 if (!Protocols.insert(
2150 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2151 return;
2152
2153 for (auto *Proto : OP->protocols())
2154 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002155 }
2156}
2157
Jay Foad39c79802011-01-12 09:06:06 +00002158unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002159 unsigned count = 0;
2160 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002161 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002162 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002163
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002164 // Count ivar defined in this class's implementation. This
2165 // includes synthesized ivars.
2166 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002167 count += ImplDecl->ivar_size();
2168
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002169 return count;
2170}
2171
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002172bool ASTContext::isSentinelNullExpr(const Expr *E) {
2173 if (!E)
2174 return false;
2175
2176 // nullptr_t is always treated as null.
2177 if (E->getType()->isNullPtrType()) return true;
2178
2179 if (E->getType()->isAnyPointerType() &&
2180 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2181 Expr::NPC_ValueDependentIsNull))
2182 return true;
2183
2184 // Unfortunately, __null has type 'int'.
2185 if (isa<GNUNullExpr>(E)) return true;
2186
2187 return false;
2188}
2189
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002190/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2191ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2192 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2193 I = ObjCImpls.find(D);
2194 if (I != ObjCImpls.end())
2195 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002196 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002197}
2198/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2199ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2200 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2201 I = ObjCImpls.find(D);
2202 if (I != ObjCImpls.end())
2203 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002204 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002205}
2206
2207/// \brief Set the implementation of ObjCInterfaceDecl.
2208void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2209 ObjCImplementationDecl *ImplD) {
2210 assert(IFaceD && ImplD && "Passed null params");
2211 ObjCImpls[IFaceD] = ImplD;
2212}
2213/// \brief Set the implementation of ObjCCategoryDecl.
2214void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2215 ObjCCategoryImplDecl *ImplD) {
2216 assert(CatD && ImplD && "Passed null params");
2217 ObjCImpls[CatD] = ImplD;
2218}
2219
Chandler Carruth21c90602015-12-30 03:24:14 +00002220const ObjCMethodDecl *
2221ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2222 return ObjCMethodRedecls.lookup(MD);
2223}
2224
2225void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2226 const ObjCMethodDecl *Redecl) {
2227 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2228 ObjCMethodRedecls[MD] = Redecl;
2229}
2230
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002231const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2232 const NamedDecl *ND) const {
2233 if (const ObjCInterfaceDecl *ID =
2234 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002235 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002236 if (const ObjCCategoryDecl *CD =
2237 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002238 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002239 if (const ObjCImplDecl *IMD =
2240 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002241 return IMD->getClassInterface();
2242
Craig Topper36250ad2014-05-12 05:36:57 +00002243 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002244}
2245
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002246/// \brief Get the copy initialization expression of VarDecl,or NULL if
2247/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002248Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002249 assert(VD && "Passed null params");
2250 assert(VD->hasAttr<BlocksAttr>() &&
2251 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002252 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002253 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002254 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002255}
2256
2257/// \brief Set the copy inialization expression of a block var decl.
2258void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2259 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002260 assert(VD->hasAttr<BlocksAttr>() &&
2261 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002262 BlockVarCopyInits[VD] = Init;
2263}
2264
John McCallbcd03502009-12-07 02:54:59 +00002265TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002266 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002267 if (!DataSize)
2268 DataSize = TypeLoc::getFullDataSizeForType(T);
2269 else
2270 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002271 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002272
John McCallbcd03502009-12-07 02:54:59 +00002273 TypeSourceInfo *TInfo =
2274 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2275 new (TInfo) TypeSourceInfo(T);
2276 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002277}
2278
John McCallbcd03502009-12-07 02:54:59 +00002279TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002280 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002281 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002282 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002283 return DI;
2284}
2285
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002286const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002287ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002288 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002289}
2290
2291const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002292ASTContext::getASTObjCImplementationLayout(
2293 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002294 return getObjCLayout(D->getClassInterface(), D);
2295}
2296
Chris Lattner983a8bb2007-07-13 22:13:22 +00002297//===----------------------------------------------------------------------===//
2298// Type creation/memoization methods
2299//===----------------------------------------------------------------------===//
2300
Jay Foad39c79802011-01-12 09:06:06 +00002301QualType
John McCall33ddac02011-01-19 10:06:00 +00002302ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2303 unsigned fastQuals = quals.getFastQualifiers();
2304 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002305
2306 // Check if we've already instantiated this type.
2307 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002308 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002309 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002310 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2311 assert(eq->getQualifiers() == quals);
2312 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002313 }
2314
John McCall33ddac02011-01-19 10:06:00 +00002315 // If the base type is not canonical, make the appropriate canonical type.
2316 QualType canon;
2317 if (!baseType->isCanonicalUnqualified()) {
2318 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002319 canonSplit.Quals.addConsistentQualifiers(quals);
2320 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002321
2322 // Re-find the insert position.
2323 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2324 }
2325
2326 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2327 ExtQualNodes.InsertNode(eq, insertPos);
2328 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002329}
2330
Jay Foad39c79802011-01-12 09:06:06 +00002331QualType
2332ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002333 QualType CanT = getCanonicalType(T);
2334 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002335 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002336
John McCall8ccfcb52009-09-24 19:53:00 +00002337 // If we are composing extended qualifiers together, merge together
2338 // into one ExtQuals node.
2339 QualifierCollector Quals;
2340 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002341
John McCall8ccfcb52009-09-24 19:53:00 +00002342 // If this type already has an address space specified, it cannot get
2343 // another one.
2344 assert(!Quals.hasAddressSpace() &&
2345 "Type cannot be in multiple addr spaces!");
2346 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002347
John McCall8ccfcb52009-09-24 19:53:00 +00002348 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002349}
2350
Chris Lattnerd60183d2009-02-18 22:53:11 +00002351QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002352 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002353 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002354 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002355 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002356
John McCall53fa7142010-12-24 02:08:15 +00002357 if (const PointerType *ptr = T->getAs<PointerType>()) {
2358 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002359 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002360 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2361 return getPointerType(ResultType);
2362 }
2363 }
Mike Stump11289f42009-09-09 15:08:12 +00002364
John McCall8ccfcb52009-09-24 19:53:00 +00002365 // If we are composing extended qualifiers together, merge together
2366 // into one ExtQuals node.
2367 QualifierCollector Quals;
2368 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002369
John McCall8ccfcb52009-09-24 19:53:00 +00002370 // If this type already has an ObjCGC specified, it cannot get
2371 // another one.
2372 assert(!Quals.hasObjCGCAttr() &&
2373 "Type cannot have multiple ObjCGCs!");
2374 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002375
John McCall8ccfcb52009-09-24 19:53:00 +00002376 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002377}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002378
John McCall4f5019e2010-12-19 02:44:49 +00002379const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2380 FunctionType::ExtInfo Info) {
2381 if (T->getExtInfo() == Info)
2382 return T;
2383
2384 QualType Result;
2385 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002386 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002387 } else {
2388 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2389 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2390 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002391 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002392 }
2393
2394 return cast<FunctionType>(Result.getTypePtr());
2395}
2396
Richard Smith2a7d4812013-05-04 07:00:32 +00002397void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2398 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002399 FD = FD->getMostRecentDecl();
2400 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002401 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2402 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002403 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002404 if (FunctionDecl *Next = FD->getPreviousDecl())
2405 FD = Next;
2406 else
2407 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002408 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002409 if (ASTMutationListener *L = getASTMutationListener())
2410 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002411}
2412
Richard Smith0b3a4622014-11-13 20:01:57 +00002413/// Get a function type and produce the equivalent function type with the
2414/// specified exception specification. Type sugar that can be present on a
2415/// declaration of a function with an exception specification is permitted
2416/// and preserved. Other type sugar (for instance, typedefs) is not.
2417static QualType getFunctionTypeWithExceptionSpec(
2418 ASTContext &Context, QualType Orig,
2419 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2420 // Might have some parens.
2421 if (auto *PT = dyn_cast<ParenType>(Orig))
2422 return Context.getParenType(
2423 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2424
2425 // Might have a calling-convention attribute.
2426 if (auto *AT = dyn_cast<AttributedType>(Orig))
2427 return Context.getAttributedType(
2428 AT->getAttrKind(),
2429 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2430 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2431 ESI));
2432
2433 // Anything else must be a function type. Rebuild it with the new exception
2434 // specification.
2435 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2436 return Context.getFunctionType(
2437 Proto->getReturnType(), Proto->getParamTypes(),
2438 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2439}
2440
2441void ASTContext::adjustExceptionSpec(
2442 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2443 bool AsWritten) {
2444 // Update the type.
2445 QualType Updated =
2446 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2447 FD->setType(Updated);
2448
2449 if (!AsWritten)
2450 return;
2451
2452 // Update the type in the type source information too.
2453 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2454 // If the type and the type-as-written differ, we may need to update
2455 // the type-as-written too.
2456 if (TSInfo->getType() != FD->getType())
2457 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2458
2459 // FIXME: When we get proper type location information for exceptions,
2460 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2461 // up the TypeSourceInfo;
2462 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2463 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2464 "TypeLoc size mismatch from updating exception specification");
2465 TSInfo->overrideType(Updated);
2466 }
2467}
2468
Chris Lattnerc6395932007-06-22 20:56:16 +00002469/// getComplexType - Return the uniqued reference to the type for a complex
2470/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002471QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002472 // Unique pointers, to guarantee there is only one pointer of a particular
2473 // structure.
2474 llvm::FoldingSetNodeID ID;
2475 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002476
Craig Topper36250ad2014-05-12 05:36:57 +00002477 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002478 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2479 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002480
Chris Lattnerc6395932007-06-22 20:56:16 +00002481 // If the pointee type isn't canonical, this won't be a canonical type either,
2482 // so fill in the canonical type field.
2483 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002484 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002485 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002486
Chris Lattnerc6395932007-06-22 20:56:16 +00002487 // Get the new insert position for the node we care about.
2488 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002489 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002490 }
John McCall90d1c2d2009-09-24 23:30:46 +00002491 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002492 Types.push_back(New);
2493 ComplexTypes.InsertNode(New, InsertPos);
2494 return QualType(New, 0);
2495}
2496
Chris Lattner970e54e2006-11-12 00:37:36 +00002497/// getPointerType - Return the uniqued reference to the type for a pointer to
2498/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002499QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002500 // Unique pointers, to guarantee there is only one pointer of a particular
2501 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002502 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002503 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002504
Craig Topper36250ad2014-05-12 05:36:57 +00002505 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002506 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002507 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002508
Chris Lattner7ccecb92006-11-12 08:50:50 +00002509 // If the pointee type isn't canonical, this won't be a canonical type either,
2510 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002511 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002512 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002513 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002514
Bob Wilsonc8541f22013-03-15 17:12:43 +00002515 // Get the new insert position for the node we care about.
2516 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002517 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002518 }
John McCall90d1c2d2009-09-24 23:30:46 +00002519 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002520 Types.push_back(New);
2521 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002522 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002523}
2524
Reid Kleckner0503a872013-12-05 01:23:43 +00002525QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2526 llvm::FoldingSetNodeID ID;
2527 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002528 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002529 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2530 if (AT)
2531 return QualType(AT, 0);
2532
2533 QualType Canonical = getCanonicalType(New);
2534
2535 // Get the new insert position for the node we care about.
2536 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002537 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002538
2539 AT = new (*this, TypeAlignment)
2540 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2541 Types.push_back(AT);
2542 AdjustedTypes.InsertNode(AT, InsertPos);
2543 return QualType(AT, 0);
2544}
2545
Reid Kleckner8a365022013-06-24 17:51:48 +00002546QualType ASTContext::getDecayedType(QualType T) const {
2547 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2548
Reid Kleckner8a365022013-06-24 17:51:48 +00002549 QualType Decayed;
2550
2551 // C99 6.7.5.3p7:
2552 // A declaration of a parameter as "array of type" shall be
2553 // adjusted to "qualified pointer to type", where the type
2554 // qualifiers (if any) are those specified within the [ and ] of
2555 // the array type derivation.
2556 if (T->isArrayType())
2557 Decayed = getArrayDecayedType(T);
2558
2559 // C99 6.7.5.3p8:
2560 // A declaration of a parameter as "function returning type"
2561 // shall be adjusted to "pointer to function returning type", as
2562 // in 6.3.2.1.
2563 if (T->isFunctionType())
2564 Decayed = getPointerType(T);
2565
Reid Kleckner0503a872013-12-05 01:23:43 +00002566 llvm::FoldingSetNodeID ID;
2567 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002568 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002569 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2570 if (AT)
2571 return QualType(AT, 0);
2572
Reid Kleckner8a365022013-06-24 17:51:48 +00002573 QualType Canonical = getCanonicalType(Decayed);
2574
2575 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002576 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002577 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002578
Reid Kleckner0503a872013-12-05 01:23:43 +00002579 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2580 Types.push_back(AT);
2581 AdjustedTypes.InsertNode(AT, InsertPos);
2582 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002583}
2584
Mike Stump11289f42009-09-09 15:08:12 +00002585/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002586/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002587QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002588 assert(T->isFunctionType() && "block of function types only");
2589 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002590 // structure.
2591 llvm::FoldingSetNodeID ID;
2592 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002593
Craig Topper36250ad2014-05-12 05:36:57 +00002594 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002595 if (BlockPointerType *PT =
2596 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2597 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002598
2599 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002600 // type either so fill in the canonical type field.
2601 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002602 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002603 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002604
Steve Naroffec33ed92008-08-27 16:04:49 +00002605 // Get the new insert position for the node we care about.
2606 BlockPointerType *NewIP =
2607 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002608 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002609 }
John McCall90d1c2d2009-09-24 23:30:46 +00002610 BlockPointerType *New
2611 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002612 Types.push_back(New);
2613 BlockPointerTypes.InsertNode(New, InsertPos);
2614 return QualType(New, 0);
2615}
2616
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002617/// getLValueReferenceType - Return the uniqued reference to the type for an
2618/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002619QualType
2620ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002621 assert(getCanonicalType(T) != OverloadTy &&
2622 "Unresolved overloaded function type");
2623
Bill Wendling3708c182007-05-27 10:15:43 +00002624 // Unique pointers, to guarantee there is only one pointer of a particular
2625 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002626 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002627 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002628
Craig Topper36250ad2014-05-12 05:36:57 +00002629 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002630 if (LValueReferenceType *RT =
2631 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002632 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002633
John McCallfc93cf92009-10-22 22:37:11 +00002634 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2635
Bill Wendling3708c182007-05-27 10:15:43 +00002636 // If the referencee type isn't canonical, this won't be a canonical type
2637 // either, so fill in the canonical type field.
2638 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002639 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2640 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2641 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002642
Bill Wendling3708c182007-05-27 10:15:43 +00002643 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002644 LValueReferenceType *NewIP =
2645 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002646 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002647 }
2648
John McCall90d1c2d2009-09-24 23:30:46 +00002649 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002650 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2651 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002652 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002653 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002654
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002655 return QualType(New, 0);
2656}
2657
2658/// getRValueReferenceType - Return the uniqued reference to the type for an
2659/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002660QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002661 // Unique pointers, to guarantee there is only one pointer of a particular
2662 // structure.
2663 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002664 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002665
Craig Topper36250ad2014-05-12 05:36:57 +00002666 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002667 if (RValueReferenceType *RT =
2668 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2669 return QualType(RT, 0);
2670
John McCallfc93cf92009-10-22 22:37:11 +00002671 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2672
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002673 // If the referencee type isn't canonical, this won't be a canonical type
2674 // either, so fill in the canonical type field.
2675 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002676 if (InnerRef || !T.isCanonical()) {
2677 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2678 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002679
2680 // Get the new insert position for the node we care about.
2681 RValueReferenceType *NewIP =
2682 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002683 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002684 }
2685
John McCall90d1c2d2009-09-24 23:30:46 +00002686 RValueReferenceType *New
2687 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002688 Types.push_back(New);
2689 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002690 return QualType(New, 0);
2691}
2692
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002693/// getMemberPointerType - Return the uniqued reference to the type for a
2694/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002695QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002696 // Unique pointers, to guarantee there is only one pointer of a particular
2697 // structure.
2698 llvm::FoldingSetNodeID ID;
2699 MemberPointerType::Profile(ID, T, Cls);
2700
Craig Topper36250ad2014-05-12 05:36:57 +00002701 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002702 if (MemberPointerType *PT =
2703 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2704 return QualType(PT, 0);
2705
2706 // If the pointee or class type isn't canonical, this won't be a canonical
2707 // type either, so fill in the canonical type field.
2708 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002709 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002710 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2711
2712 // Get the new insert position for the node we care about.
2713 MemberPointerType *NewIP =
2714 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002715 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002716 }
John McCall90d1c2d2009-09-24 23:30:46 +00002717 MemberPointerType *New
2718 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002719 Types.push_back(New);
2720 MemberPointerTypes.InsertNode(New, InsertPos);
2721 return QualType(New, 0);
2722}
2723
Mike Stump11289f42009-09-09 15:08:12 +00002724/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002725/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002726QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002727 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002728 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002729 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002730 assert((EltTy->isDependentType() ||
2731 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002732 "Constant array of VLAs is illegal!");
2733
Chris Lattnere2df3f92009-05-13 04:12:56 +00002734 // Convert the array size into a canonical width matching the pointer size for
2735 // the target.
2736 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002737 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002738 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002739
Chris Lattner23b7eb62007-06-15 23:05:46 +00002740 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002741 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002742
Craig Topper36250ad2014-05-12 05:36:57 +00002743 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002744 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002745 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002746 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002747
John McCall33ddac02011-01-19 10:06:00 +00002748 // If the element type isn't canonical or has qualifiers, this won't
2749 // be a canonical type either, so fill in the canonical type field.
2750 QualType Canon;
2751 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2752 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002753 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002754 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002755 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002756
Chris Lattner36f8e652007-01-27 08:31:04 +00002757 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002758 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002759 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002760 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002761 }
Mike Stump11289f42009-09-09 15:08:12 +00002762
John McCall90d1c2d2009-09-24 23:30:46 +00002763 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002764 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002765 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002766 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002767 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002768}
2769
John McCall06549462011-01-18 08:40:38 +00002770/// getVariableArrayDecayedType - Turns the given type, which may be
2771/// variably-modified, into the corresponding type with all the known
2772/// sizes replaced with [*].
2773QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2774 // Vastly most common case.
2775 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002776
John McCall06549462011-01-18 08:40:38 +00002777 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002778
John McCall06549462011-01-18 08:40:38 +00002779 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002780 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002781 switch (ty->getTypeClass()) {
2782#define TYPE(Class, Base)
2783#define ABSTRACT_TYPE(Class, Base)
2784#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2785#include "clang/AST/TypeNodes.def"
2786 llvm_unreachable("didn't desugar past all non-canonical types?");
2787
2788 // These types should never be variably-modified.
2789 case Type::Builtin:
2790 case Type::Complex:
2791 case Type::Vector:
2792 case Type::ExtVector:
2793 case Type::DependentSizedExtVector:
2794 case Type::ObjCObject:
2795 case Type::ObjCInterface:
2796 case Type::ObjCObjectPointer:
2797 case Type::Record:
2798 case Type::Enum:
2799 case Type::UnresolvedUsing:
2800 case Type::TypeOfExpr:
2801 case Type::TypeOf:
2802 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002803 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002804 case Type::DependentName:
2805 case Type::InjectedClassName:
2806 case Type::TemplateSpecialization:
2807 case Type::DependentTemplateSpecialization:
2808 case Type::TemplateTypeParm:
2809 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002810 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002811 case Type::PackExpansion:
2812 llvm_unreachable("type should never be variably-modified");
2813
2814 // These types can be variably-modified but should never need to
2815 // further decay.
2816 case Type::FunctionNoProto:
2817 case Type::FunctionProto:
2818 case Type::BlockPointer:
2819 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002820 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002821 return type;
2822
2823 // These types can be variably-modified. All these modifications
2824 // preserve structure except as noted by comments.
2825 // TODO: if we ever care about optimizing VLAs, there are no-op
2826 // optimizations available here.
2827 case Type::Pointer:
2828 result = getPointerType(getVariableArrayDecayedType(
2829 cast<PointerType>(ty)->getPointeeType()));
2830 break;
2831
2832 case Type::LValueReference: {
2833 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2834 result = getLValueReferenceType(
2835 getVariableArrayDecayedType(lv->getPointeeType()),
2836 lv->isSpelledAsLValue());
2837 break;
2838 }
2839
2840 case Type::RValueReference: {
2841 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2842 result = getRValueReferenceType(
2843 getVariableArrayDecayedType(lv->getPointeeType()));
2844 break;
2845 }
2846
Eli Friedman0dfb8892011-10-06 23:00:33 +00002847 case Type::Atomic: {
2848 const AtomicType *at = cast<AtomicType>(ty);
2849 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2850 break;
2851 }
2852
John McCall06549462011-01-18 08:40:38 +00002853 case Type::ConstantArray: {
2854 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2855 result = getConstantArrayType(
2856 getVariableArrayDecayedType(cat->getElementType()),
2857 cat->getSize(),
2858 cat->getSizeModifier(),
2859 cat->getIndexTypeCVRQualifiers());
2860 break;
2861 }
2862
2863 case Type::DependentSizedArray: {
2864 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2865 result = getDependentSizedArrayType(
2866 getVariableArrayDecayedType(dat->getElementType()),
2867 dat->getSizeExpr(),
2868 dat->getSizeModifier(),
2869 dat->getIndexTypeCVRQualifiers(),
2870 dat->getBracketsRange());
2871 break;
2872 }
2873
2874 // Turn incomplete types into [*] types.
2875 case Type::IncompleteArray: {
2876 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2877 result = getVariableArrayType(
2878 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002879 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002880 ArrayType::Normal,
2881 iat->getIndexTypeCVRQualifiers(),
2882 SourceRange());
2883 break;
2884 }
2885
2886 // Turn VLA types into [*] types.
2887 case Type::VariableArray: {
2888 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2889 result = getVariableArrayType(
2890 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002891 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002892 ArrayType::Star,
2893 vat->getIndexTypeCVRQualifiers(),
2894 vat->getBracketsRange());
2895 break;
2896 }
2897 }
2898
2899 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002900 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002901}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002902
Steve Naroffcadebd02007-08-30 18:14:25 +00002903/// getVariableArrayType - Returns a non-unique reference to the type for a
2904/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002905QualType ASTContext::getVariableArrayType(QualType EltTy,
2906 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002907 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002908 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002909 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002910 // Since we don't unique expressions, it isn't possible to unique VLA's
2911 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002912 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002913
John McCall33ddac02011-01-19 10:06:00 +00002914 // Be sure to pull qualifiers off the element type.
2915 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2916 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002917 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002918 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002919 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002920 }
2921
John McCall90d1c2d2009-09-24 23:30:46 +00002922 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002923 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002924
2925 VariableArrayTypes.push_back(New);
2926 Types.push_back(New);
2927 return QualType(New, 0);
2928}
2929
Douglas Gregor4619e432008-12-05 23:32:09 +00002930/// getDependentSizedArrayType - Returns a non-unique reference to
2931/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002932/// type.
John McCall33ddac02011-01-19 10:06:00 +00002933QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2934 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002935 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002936 unsigned elementTypeQuals,
2937 SourceRange brackets) const {
2938 assert((!numElements || numElements->isTypeDependent() ||
2939 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002940 "Size must be type- or value-dependent!");
2941
John McCall33ddac02011-01-19 10:06:00 +00002942 // Dependently-sized array types that do not have a specified number
2943 // of elements will have their sizes deduced from a dependent
2944 // initializer. We do no canonicalization here at all, which is okay
2945 // because they can't be used in most locations.
2946 if (!numElements) {
2947 DependentSizedArrayType *newType
2948 = new (*this, TypeAlignment)
2949 DependentSizedArrayType(*this, elementType, QualType(),
2950 numElements, ASM, elementTypeQuals,
2951 brackets);
2952 Types.push_back(newType);
2953 return QualType(newType, 0);
2954 }
2955
2956 // Otherwise, we actually build a new type every time, but we
2957 // also build a canonical type.
2958
2959 SplitQualType canonElementType = getCanonicalType(elementType).split();
2960
Craig Topper36250ad2014-05-12 05:36:57 +00002961 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002962 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002963 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002964 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002965 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002966
John McCall33ddac02011-01-19 10:06:00 +00002967 // Look for an existing type with these properties.
2968 DependentSizedArrayType *canonTy =
2969 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002970
John McCall33ddac02011-01-19 10:06:00 +00002971 // If we don't have one, build one.
2972 if (!canonTy) {
2973 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002974 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002975 QualType(), numElements, ASM, elementTypeQuals,
2976 brackets);
2977 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2978 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002979 }
2980
John McCall33ddac02011-01-19 10:06:00 +00002981 // Apply qualifiers from the element type to the array.
2982 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002983 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002984
David Majnemer16a74702015-07-24 05:54:19 +00002985 // If we didn't need extra canonicalization for the element type or the size
2986 // expression, then just use that as our result.
2987 if (QualType(canonElementType.Ty, 0) == elementType &&
2988 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002989 return canon;
2990
2991 // Otherwise, we need to build a type which follows the spelling
2992 // of the element type.
2993 DependentSizedArrayType *sugaredType
2994 = new (*this, TypeAlignment)
2995 DependentSizedArrayType(*this, elementType, canon, numElements,
2996 ASM, elementTypeQuals, brackets);
2997 Types.push_back(sugaredType);
2998 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002999}
3000
John McCall33ddac02011-01-19 10:06:00 +00003001QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003002 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003003 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003004 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003005 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003006
Craig Topper36250ad2014-05-12 05:36:57 +00003007 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003008 if (IncompleteArrayType *iat =
3009 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3010 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003011
3012 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003013 // either, so fill in the canonical type field. We also have to pull
3014 // qualifiers off the element type.
3015 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003016
John McCall33ddac02011-01-19 10:06:00 +00003017 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3018 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003019 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003020 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003021 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003022
3023 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003024 IncompleteArrayType *existing =
3025 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3026 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003027 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003028
John McCall33ddac02011-01-19 10:06:00 +00003029 IncompleteArrayType *newType = new (*this, TypeAlignment)
3030 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003031
John McCall33ddac02011-01-19 10:06:00 +00003032 IncompleteArrayTypes.InsertNode(newType, insertPos);
3033 Types.push_back(newType);
3034 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003035}
3036
Steve Naroff91fcddb2007-07-18 18:00:27 +00003037/// getVectorType - Return the unique reference to a vector type of
3038/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003039QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003040 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003041 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003042
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003043 // Check if we've already instantiated a vector of this type.
3044 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003045 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003046
Craig Topper36250ad2014-05-12 05:36:57 +00003047 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003048 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3049 return QualType(VTP, 0);
3050
3051 // If the element type isn't canonical, this won't be a canonical type either,
3052 // so fill in the canonical type field.
3053 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003054 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003055 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003056
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003057 // Get the new insert position for the node we care about.
3058 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003059 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003060 }
John McCall90d1c2d2009-09-24 23:30:46 +00003061 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003062 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003063 VectorTypes.InsertNode(New, InsertPos);
3064 Types.push_back(New);
3065 return QualType(New, 0);
3066}
3067
Nate Begemance4d7fc2008-04-18 23:10:10 +00003068/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003069/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003070QualType
3071ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003072 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003073
Steve Naroff91fcddb2007-07-18 18:00:27 +00003074 // Check if we've already instantiated a vector of this type.
3075 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003076 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003077 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003078 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003079 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3080 return QualType(VTP, 0);
3081
3082 // If the element type isn't canonical, this won't be a canonical type either,
3083 // so fill in the canonical type field.
3084 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003085 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003086 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003087
Steve Naroff91fcddb2007-07-18 18:00:27 +00003088 // Get the new insert position for the node we care about.
3089 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003090 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003091 }
John McCall90d1c2d2009-09-24 23:30:46 +00003092 ExtVectorType *New = new (*this, TypeAlignment)
3093 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003094 VectorTypes.InsertNode(New, InsertPos);
3095 Types.push_back(New);
3096 return QualType(New, 0);
3097}
3098
Jay Foad39c79802011-01-12 09:06:06 +00003099QualType
3100ASTContext::getDependentSizedExtVectorType(QualType vecType,
3101 Expr *SizeExpr,
3102 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003103 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003104 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003105 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003106
Craig Topper36250ad2014-05-12 05:36:57 +00003107 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003108 DependentSizedExtVectorType *Canon
3109 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3110 DependentSizedExtVectorType *New;
3111 if (Canon) {
3112 // We already have a canonical version of this array type; use it as
3113 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003114 New = new (*this, TypeAlignment)
3115 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3116 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003117 } else {
3118 QualType CanonVecTy = getCanonicalType(vecType);
3119 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003120 New = new (*this, TypeAlignment)
3121 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3122 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003123
3124 DependentSizedExtVectorType *CanonCheck
3125 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3126 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3127 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003128 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3129 } else {
3130 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3131 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003132 New = new (*this, TypeAlignment)
3133 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003134 }
3135 }
Mike Stump11289f42009-09-09 15:08:12 +00003136
Douglas Gregor758a8692009-06-17 21:51:59 +00003137 Types.push_back(New);
3138 return QualType(New, 0);
3139}
3140
John McCall18afab72016-03-01 00:49:02 +00003141/// \brief Determine whether \p T is canonical as the result type of a function.
3142static bool isCanonicalResultType(QualType T) {
3143 return T.isCanonical() &&
3144 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3145 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3146}
3147
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003148/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003149///
Jay Foad39c79802011-01-12 09:06:06 +00003150QualType
3151ASTContext::getFunctionNoProtoType(QualType ResultTy,
3152 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003153 // Unique functions, to guarantee there is only one function of a particular
3154 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003155 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003156 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003157
Craig Topper36250ad2014-05-12 05:36:57 +00003158 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003159 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003160 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003161 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003162
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003163 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003164 if (!isCanonicalResultType(ResultTy)) {
3165 Canonical =
3166 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003167
Chris Lattner47955de2007-01-27 08:37:20 +00003168 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003169 FunctionNoProtoType *NewIP =
3170 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003171 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003172 }
Mike Stump11289f42009-09-09 15:08:12 +00003173
John McCall90d1c2d2009-09-24 23:30:46 +00003174 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003175 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003176 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003177 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003178 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003179}
3180
Douglas Gregora602a152015-10-01 20:20:47 +00003181CanQualType
3182ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3183 CanQualType CanResultType = getCanonicalType(ResultType);
3184
3185 // Canonical result types do not have ARC lifetime qualifiers.
3186 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3187 Qualifiers Qs = CanResultType.getQualifiers();
3188 Qs.removeObjCLifetime();
3189 return CanQualType::CreateUnsafe(
3190 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3191 }
3192
3193 return CanResultType;
3194}
3195
Jay Foad39c79802011-01-12 09:06:06 +00003196QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003197ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003198 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003199 size_t NumArgs = ArgArray.size();
3200
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003201 // Unique functions, to guarantee there is only one function of a particular
3202 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003203 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003204 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3205 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003206
Craig Topper36250ad2014-05-12 05:36:57 +00003207 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003208 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003209 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003210 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003211
3212 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003213 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003214 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003215 !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
3220 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003221 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003222 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003223 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003224 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003225 CanonicalArgs.reserve(NumArgs);
3226 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003227 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003228
John McCalldb40c7f2010-12-14 08:05:40 +00003229 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003230 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003231 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003232
Douglas Gregora602a152015-10-01 20:20:47 +00003233 // Adjust the canonical function result type.
3234 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003235 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003236
Chris Lattnerfd4de792007-01-27 01:15:32 +00003237 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003238 FunctionProtoType *NewIP =
3239 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003240 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003241 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003242
John McCall31168b02011-06-15 23:02:42 +00003243 // FunctionProtoType objects are allocated with extra bytes after
3244 // them for three variable size arrays at the end:
3245 // - parameter types
3246 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003247 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003248 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003249 // expression, or information used to resolve the exception
3250 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003251 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003252 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003253
Richard Smith8acb4282014-07-31 21:57:55 +00003254 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3255 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3256 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003257 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003258 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003259 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003260 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003261 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003262 }
John McCall18afab72016-03-01 00:49:02 +00003263
3264 // Put the ExtParameterInfos last. If all were equal, it would make
3265 // more sense to put these before the exception specification, because
3266 // it's much easier to skip past them compared to the elaborate switch
3267 // required to skip the exception specification. However, all is not
3268 // equal; ExtParameterInfos are used to model very uncommon features,
3269 // and it's better not to burden the more common paths.
3270 if (EPI.ExtParameterInfos) {
3271 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3272 }
John McCall31168b02011-06-15 23:02:42 +00003273
John McCalldb40c7f2010-12-14 08:05:40 +00003274 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003275 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003276 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003277 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003278 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003279 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003280}
Chris Lattneref51c202006-11-10 07:17:23 +00003281
Xiuli Pan9c14e282016-01-09 12:53:17 +00003282/// Return pipe type for the specified type.
3283QualType ASTContext::getPipeType(QualType T) const {
3284 llvm::FoldingSetNodeID ID;
3285 PipeType::Profile(ID, T);
3286
3287 void *InsertPos = 0;
3288 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3289 return QualType(PT, 0);
3290
3291 // If the pipe element type isn't canonical, this won't be a canonical type
3292 // either, so fill in the canonical type field.
3293 QualType Canonical;
3294 if (!T.isCanonical()) {
3295 Canonical = getPipeType(getCanonicalType(T));
3296
3297 // Get the new insert position for the node we care about.
3298 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3299 assert(!NewIP && "Shouldn't be in the map!");
3300 (void)NewIP;
3301 }
3302 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3303 Types.push_back(New);
3304 PipeTypes.InsertNode(New, InsertPos);
3305 return QualType(New, 0);
3306}
3307
John McCalle78aac42010-03-10 03:28:59 +00003308#ifndef NDEBUG
3309static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3310 if (!isa<CXXRecordDecl>(D)) return false;
3311 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3312 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3313 return true;
3314 if (RD->getDescribedClassTemplate() &&
3315 !isa<ClassTemplateSpecializationDecl>(RD))
3316 return true;
3317 return false;
3318}
3319#endif
3320
3321/// getInjectedClassNameType - Return the unique reference to the
3322/// injected class name type for the specified templated declaration.
3323QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003324 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003325 assert(NeedsInjectedClassNameType(Decl));
3326 if (Decl->TypeForDecl) {
3327 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003328 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003329 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3330 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3331 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3332 } else {
John McCall424cec92011-01-19 06:33:43 +00003333 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003334 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003335 Decl->TypeForDecl = newType;
3336 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003337 }
3338 return QualType(Decl->TypeForDecl, 0);
3339}
3340
Douglas Gregor83a586e2008-04-13 21:07:44 +00003341/// getTypeDeclType - Return the unique reference to the type for the
3342/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003343QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003344 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003345 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003346
Richard Smithdda56e42011-04-15 14:24:37 +00003347 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003348 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003349
John McCall96f0b5f2010-03-10 06:48:02 +00003350 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3351 "Template type parameter types are always available.");
3352
John McCall81e38502010-02-16 03:57:14 +00003353 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003354 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003355 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003356 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003357 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003358 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003359 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003360 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003361 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003362 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3363 Decl->TypeForDecl = newType;
3364 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003365 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003366 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003367
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003368 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003369}
3370
Chris Lattner32d920b2007-01-26 02:01:53 +00003371/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003372/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003373QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003374ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3375 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003376 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003377
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003378 if (Canonical.isNull())
3379 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003380 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003381 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003382 Decl->TypeForDecl = newType;
3383 Types.push_back(newType);
3384 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003385}
3386
Jay Foad39c79802011-01-12 09:06:06 +00003387QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003388 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3389
Douglas Gregorec9fd132012-01-14 16:38:05 +00003390 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003391 if (PrevDecl->TypeForDecl)
3392 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3393
John McCall424cec92011-01-19 06:33:43 +00003394 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3395 Decl->TypeForDecl = newType;
3396 Types.push_back(newType);
3397 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003398}
3399
Jay Foad39c79802011-01-12 09:06:06 +00003400QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003401 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3402
Douglas Gregorec9fd132012-01-14 16:38:05 +00003403 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003404 if (PrevDecl->TypeForDecl)
3405 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3406
John McCall424cec92011-01-19 06:33:43 +00003407 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3408 Decl->TypeForDecl = newType;
3409 Types.push_back(newType);
3410 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003411}
3412
John McCall81904512011-01-06 01:58:22 +00003413QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3414 QualType modifiedType,
3415 QualType equivalentType) {
3416 llvm::FoldingSetNodeID id;
3417 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3418
Craig Topper36250ad2014-05-12 05:36:57 +00003419 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003420 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3421 if (type) return QualType(type, 0);
3422
3423 QualType canon = getCanonicalType(equivalentType);
3424 type = new (*this, TypeAlignment)
3425 AttributedType(canon, attrKind, modifiedType, equivalentType);
3426
3427 Types.push_back(type);
3428 AttributedTypes.InsertNode(type, insertPos);
3429
3430 return QualType(type, 0);
3431}
3432
John McCallcebee162009-10-18 09:09:24 +00003433/// \brief Retrieve a substitution-result type.
3434QualType
3435ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003436 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003437 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003438 && "replacement types must always be canonical");
3439
3440 llvm::FoldingSetNodeID ID;
3441 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003442 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003443 SubstTemplateTypeParmType *SubstParm
3444 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3445
3446 if (!SubstParm) {
3447 SubstParm = new (*this, TypeAlignment)
3448 SubstTemplateTypeParmType(Parm, Replacement);
3449 Types.push_back(SubstParm);
3450 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3451 }
3452
3453 return QualType(SubstParm, 0);
3454}
3455
Douglas Gregorada4b792011-01-14 02:55:32 +00003456/// \brief Retrieve a
3457QualType ASTContext::getSubstTemplateTypeParmPackType(
3458 const TemplateTypeParmType *Parm,
3459 const TemplateArgument &ArgPack) {
3460#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003461 for (const auto &P : ArgPack.pack_elements()) {
3462 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3463 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003464 }
3465#endif
3466
3467 llvm::FoldingSetNodeID ID;
3468 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003469 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003470 if (SubstTemplateTypeParmPackType *SubstParm
3471 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3472 return QualType(SubstParm, 0);
3473
3474 QualType Canon;
3475 if (!Parm->isCanonicalUnqualified()) {
3476 Canon = getCanonicalType(QualType(Parm, 0));
3477 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3478 ArgPack);
3479 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3480 }
3481
3482 SubstTemplateTypeParmPackType *SubstParm
3483 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3484 ArgPack);
3485 Types.push_back(SubstParm);
3486 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3487 return QualType(SubstParm, 0);
3488}
3489
Douglas Gregoreff93e02009-02-05 23:33:38 +00003490/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003491/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003492/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003493QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003494 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003495 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003496 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003497 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003498 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003499 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003500 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3501
3502 if (TypeParm)
3503 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003504
Chandler Carruth08836322011-05-01 00:51:33 +00003505 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003506 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003507 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003508
3509 TemplateTypeParmType *TypeCheck
3510 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3511 assert(!TypeCheck && "Template type parameter canonical type broken");
3512 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003513 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003514 TypeParm = new (*this, TypeAlignment)
3515 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003516
3517 Types.push_back(TypeParm);
3518 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3519
3520 return QualType(TypeParm, 0);
3521}
3522
John McCalle78aac42010-03-10 03:28:59 +00003523TypeSourceInfo *
3524ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3525 SourceLocation NameLoc,
3526 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003527 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003528 assert(!Name.getAsDependentTemplateName() &&
3529 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003530 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003531
3532 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003533 TemplateSpecializationTypeLoc TL =
3534 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003535 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003536 TL.setTemplateNameLoc(NameLoc);
3537 TL.setLAngleLoc(Args.getLAngleLoc());
3538 TL.setRAngleLoc(Args.getRAngleLoc());
3539 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3540 TL.setArgLocInfo(i, Args[i].getLocInfo());
3541 return DI;
3542}
3543
Mike Stump11289f42009-09-09 15:08:12 +00003544QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003545ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003546 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003547 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003548 assert(!Template.getAsDependentTemplateName() &&
3549 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003550
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003551 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003552 ArgVec.reserve(Args.size());
3553 for (const TemplateArgumentLoc &Arg : Args.arguments())
3554 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003555
David Majnemer6fbeee32016-07-07 04:43:07 +00003556 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003557}
3558
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003559#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003560static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3561 for (const TemplateArgument &Arg : Args)
3562 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003563 return true;
3564
3565 return true;
3566}
3567#endif
3568
John McCall0ad16662009-10-29 08:12:44 +00003569QualType
3570ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003571 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003572 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003573 assert(!Template.getAsDependentTemplateName() &&
3574 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003575 // Look through qualified template names.
3576 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3577 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003578
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003579 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003580 Template.getAsTemplateDecl() &&
3581 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003582 QualType CanonType;
3583 if (!Underlying.isNull())
3584 CanonType = getCanonicalType(Underlying);
3585 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003586 // We can get here with an alias template when the specialization contains
3587 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003588 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003589 "Caller must compute aliased type");
3590 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003591 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003592 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003593
Douglas Gregora8e02e72009-07-28 23:00:59 +00003594 // Allocate the (non-canonical) template specialization type, but don't
3595 // try to unique it: these types typically have location information that
3596 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003597 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003598 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003599 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003600 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003601 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003602 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003603 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003604
Douglas Gregor8bf42052009-02-09 18:46:07 +00003605 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003606 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003607}
3608
David Majnemer6fbeee32016-07-07 04:43:07 +00003609QualType ASTContext::getCanonicalTemplateSpecializationType(
3610 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003611 assert(!Template.getAsDependentTemplateName() &&
3612 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003613
Douglas Gregore29139c2011-03-03 17:04:51 +00003614 // Look through qualified template names.
3615 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3616 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003617
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003618 // Build the canonical template specialization type.
3619 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003620 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003621 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003622 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003623 for (const TemplateArgument &Arg : Args)
3624 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003625
3626 // Determine whether this canonical template specialization type already
3627 // exists.
3628 llvm::FoldingSetNodeID ID;
3629 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003630 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003631
Craig Topper36250ad2014-05-12 05:36:57 +00003632 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003633 TemplateSpecializationType *Spec
3634 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3635
3636 if (!Spec) {
3637 // Allocate a new canonical template specialization type.
3638 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3639 sizeof(TemplateArgument) * NumArgs),
3640 TypeAlignment);
3641 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003642 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003643 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003644 Types.push_back(Spec);
3645 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3646 }
3647
3648 assert(Spec->isDependentType() &&
3649 "Non-dependent template-id type must have a canonical type");
3650 return QualType(Spec, 0);
3651}
3652
3653QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003654ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3655 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003656 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003657 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003658 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003659
Craig Topper36250ad2014-05-12 05:36:57 +00003660 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003661 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003662 if (T)
3663 return QualType(T, 0);
3664
Douglas Gregorc42075a2010-02-04 18:10:26 +00003665 QualType Canon = NamedType;
3666 if (!Canon.isCanonical()) {
3667 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003668 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3669 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003670 (void)CheckT;
3671 }
3672
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003673 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003674 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003675 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003676 return QualType(T, 0);
3677}
3678
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003679QualType
Jay Foad39c79802011-01-12 09:06:06 +00003680ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003681 llvm::FoldingSetNodeID ID;
3682 ParenType::Profile(ID, InnerType);
3683
Craig Topper36250ad2014-05-12 05:36:57 +00003684 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003685 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3686 if (T)
3687 return QualType(T, 0);
3688
3689 QualType Canon = InnerType;
3690 if (!Canon.isCanonical()) {
3691 Canon = getCanonicalType(InnerType);
3692 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3693 assert(!CheckT && "Paren canonical type broken");
3694 (void)CheckT;
3695 }
3696
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003697 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003698 Types.push_back(T);
3699 ParenTypes.InsertNode(T, InsertPos);
3700 return QualType(T, 0);
3701}
3702
Douglas Gregor02085352010-03-31 20:19:30 +00003703QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3704 NestedNameSpecifier *NNS,
3705 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003706 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003707 if (Canon.isNull()) {
3708 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003709 ElaboratedTypeKeyword CanonKeyword = Keyword;
3710 if (Keyword == ETK_None)
3711 CanonKeyword = ETK_Typename;
3712
3713 if (CanonNNS != NNS || CanonKeyword != Keyword)
3714 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003715 }
3716
3717 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003718 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003719
Craig Topper36250ad2014-05-12 05:36:57 +00003720 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003721 DependentNameType *T
3722 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003723 if (T)
3724 return QualType(T, 0);
3725
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003726 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003727 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003728 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003729 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003730}
3731
Mike Stump11289f42009-09-09 15:08:12 +00003732QualType
John McCallc392f372010-06-11 00:33:02 +00003733ASTContext::getDependentTemplateSpecializationType(
3734 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003735 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003736 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003737 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003738 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003739 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003740 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3741 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003742 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003743}
3744
3745QualType
3746ASTContext::getDependentTemplateSpecializationType(
3747 ElaboratedTypeKeyword Keyword,
3748 NestedNameSpecifier *NNS,
3749 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003750 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003751 assert((!NNS || NNS->isDependent()) &&
3752 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003753
Douglas Gregorc42075a2010-02-04 18:10:26 +00003754 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003755 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003756 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003757
Craig Topper36250ad2014-05-12 05:36:57 +00003758 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003759 DependentTemplateSpecializationType *T
3760 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003761 if (T)
3762 return QualType(T, 0);
3763
John McCallc392f372010-06-11 00:33:02 +00003764 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003765
John McCallc392f372010-06-11 00:33:02 +00003766 ElaboratedTypeKeyword CanonKeyword = Keyword;
3767 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3768
3769 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003770 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003771 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003772 for (unsigned I = 0; I != NumArgs; ++I) {
3773 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3774 if (!CanonArgs[I].structurallyEquals(Args[I]))
3775 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003776 }
3777
John McCallc392f372010-06-11 00:33:02 +00003778 QualType Canon;
3779 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3780 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003781 Name,
3782 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003783
3784 // Find the insert position again.
3785 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3786 }
3787
3788 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3789 sizeof(TemplateArgument) * NumArgs),
3790 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003791 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003792 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003793 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003794 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003795 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003796}
3797
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003798QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003799 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003800 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003801 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003802
3803 assert(Pattern->containsUnexpandedParameterPack() &&
3804 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003805 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003806 PackExpansionType *T
3807 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3808 if (T)
3809 return QualType(T, 0);
3810
3811 QualType Canon;
3812 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003813 Canon = getCanonicalType(Pattern);
3814 // The canonical type might not contain an unexpanded parameter pack, if it
3815 // contains an alias template specialization which ignores one of its
3816 // parameters.
3817 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003818 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003819
Richard Smith68eea502012-07-16 00:20:35 +00003820 // Find the insert position again, in case we inserted an element into
3821 // PackExpansionTypes and invalidated our insert position.
3822 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3823 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003824 }
3825
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003826 T = new (*this, TypeAlignment)
3827 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003828 Types.push_back(T);
3829 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003830 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003831}
3832
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003833/// CmpProtocolNames - Comparison predicate for sorting protocols
3834/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003835static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3836 ObjCProtocolDecl *const *RHS) {
3837 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003838}
3839
Craig Topper1f26d5b2016-01-03 19:43:23 +00003840static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3841 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003842
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003843 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3844 return false;
3845
Craig Topper1f26d5b2016-01-03 19:43:23 +00003846 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003847 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003848 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003849 return false;
3850 return true;
3851}
3852
Craig Topper6a8c1512015-10-22 01:56:18 +00003853static void
3854SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003855 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003856 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003857
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003858 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003859 for (ObjCProtocolDecl *&P : Protocols)
3860 P = P->getCanonicalDecl();
3861
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003862 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003863 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3864 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003865}
3866
John McCall8b07ec22010-05-15 11:32:37 +00003867QualType ASTContext::getObjCObjectType(QualType BaseType,
3868 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003869 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003870 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003871 llvm::makeArrayRef(Protocols, NumProtocols),
3872 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003873}
3874
3875QualType ASTContext::getObjCObjectType(
3876 QualType baseType,
3877 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003878 ArrayRef<ObjCProtocolDecl *> protocols,
3879 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003880 // If the base type is an interface and there aren't any protocols or
3881 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003882 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3883 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003884 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003885
3886 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003887 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003888 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003889 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003890 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3891 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003892
Douglas Gregore9d95f12015-07-07 03:57:35 +00003893 // Determine the type arguments to be used for canonicalization,
3894 // which may be explicitly specified here or written on the base
3895 // type.
3896 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3897 if (effectiveTypeArgs.empty()) {
3898 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3899 effectiveTypeArgs = baseObject->getTypeArgs();
3900 }
John McCallfc93cf92009-10-22 22:37:11 +00003901
Douglas Gregore9d95f12015-07-07 03:57:35 +00003902 // Build the canonical type, which has the canonical base type and a
3903 // sorted-and-uniqued list of protocols and the type arguments
3904 // canonicalized.
3905 QualType canonical;
3906 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3907 effectiveTypeArgs.end(),
3908 [&](QualType type) {
3909 return type.isCanonical();
3910 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003911 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003912 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3913 // Determine the canonical type arguments.
3914 ArrayRef<QualType> canonTypeArgs;
3915 SmallVector<QualType, 4> canonTypeArgsVec;
3916 if (!typeArgsAreCanonical) {
3917 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3918 for (auto typeArg : effectiveTypeArgs)
3919 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3920 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003921 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003922 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003923 }
3924
Douglas Gregore9d95f12015-07-07 03:57:35 +00003925 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3926 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3927 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003928 canonProtocolsVec.append(protocols.begin(), protocols.end());
3929 SortAndUniqueProtocols(canonProtocolsVec);
3930 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003931 } else {
3932 canonProtocols = protocols;
3933 }
3934
3935 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003936 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003937
John McCallfc93cf92009-10-22 22:37:11 +00003938 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003939 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3940 }
3941
Douglas Gregore9d95f12015-07-07 03:57:35 +00003942 unsigned size = sizeof(ObjCObjectTypeImpl);
3943 size += typeArgs.size() * sizeof(QualType);
3944 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3945 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003946 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003947 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3948 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003949
3950 Types.push_back(T);
3951 ObjCObjectTypes.InsertNode(T, InsertPos);
3952 return QualType(T, 0);
3953}
3954
Manman Ren3569eb52016-09-13 17:03:12 +00003955/// Apply Objective-C protocol qualifiers to the given type.
3956/// If this is for the canonical type of a type parameter, we can apply
3957/// protocol qualifiers on the ObjCObjectPointerType.
3958QualType
3959ASTContext::applyObjCProtocolQualifiers(QualType type,
3960 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
3961 bool allowOnPointerType) const {
3962 hasError = false;
3963
Manman Renc5705ba2016-09-13 17:41:05 +00003964 if (const ObjCTypeParamType *objT =
3965 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
3966 return getObjCTypeParamType(objT->getDecl(), protocols);
3967 }
3968
Manman Ren3569eb52016-09-13 17:03:12 +00003969 // Apply protocol qualifiers to ObjCObjectPointerType.
3970 if (allowOnPointerType) {
3971 if (const ObjCObjectPointerType *objPtr =
3972 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
3973 const ObjCObjectType *objT = objPtr->getObjectType();
3974 // Merge protocol lists and construct ObjCObjectType.
3975 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
3976 protocolsVec.append(objT->qual_begin(),
3977 objT->qual_end());
3978 protocolsVec.append(protocols.begin(), protocols.end());
3979 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
3980 type = getObjCObjectType(
3981 objT->getBaseType(),
3982 objT->getTypeArgsAsWritten(),
3983 protocols,
3984 objT->isKindOfTypeAsWritten());
3985 return getObjCObjectPointerType(type);
3986 }
3987 }
3988
3989 // Apply protocol qualifiers to ObjCObjectType.
3990 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
3991 // FIXME: Check for protocols to which the class type is already
3992 // known to conform.
3993
3994 return getObjCObjectType(objT->getBaseType(),
3995 objT->getTypeArgsAsWritten(),
3996 protocols,
3997 objT->isKindOfTypeAsWritten());
3998 }
3999
4000 // If the canonical type is ObjCObjectType, ...
4001 if (type->isObjCObjectType()) {
4002 // Silently overwrite any existing protocol qualifiers.
4003 // TODO: determine whether that's the right thing to do.
4004
4005 // FIXME: Check for protocols to which the class type is already
4006 // known to conform.
4007 return getObjCObjectType(type, { }, protocols, false);
4008 }
4009
4010 // id<protocol-list>
4011 if (type->isObjCIdType()) {
4012 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4013 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4014 objPtr->isKindOfType());
4015 return getObjCObjectPointerType(type);
4016 }
4017
4018 // Class<protocol-list>
4019 if (type->isObjCClassType()) {
4020 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4021 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4022 objPtr->isKindOfType());
4023 return getObjCObjectPointerType(type);
4024 }
4025
4026 hasError = true;
4027 return type;
4028}
4029
Manman Rene6be26c2016-09-13 17:25:08 +00004030QualType
4031ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4032 ArrayRef<ObjCProtocolDecl *> protocols,
4033 QualType Canonical) const {
4034 // Look in the folding set for an existing type.
4035 llvm::FoldingSetNodeID ID;
4036 ObjCTypeParamType::Profile(ID, Decl, protocols);
4037 void *InsertPos = nullptr;
4038 if (ObjCTypeParamType *TypeParam =
4039 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4040 return QualType(TypeParam, 0);
4041
4042 if (Canonical.isNull()) {
4043 // We canonicalize to the underlying type.
4044 Canonical = getCanonicalType(Decl->getUnderlyingType());
4045 if (!protocols.empty()) {
4046 // Apply the protocol qualifers.
4047 bool hasError;
4048 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4049 true/*allowOnPointerType*/);
4050 assert(!hasError && "Error when apply protocol qualifier to bound type");
4051 }
4052 }
4053
4054 unsigned size = sizeof(ObjCTypeParamType);
4055 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4056 void *mem = Allocate(size, TypeAlignment);
4057 ObjCTypeParamType *newType = new (mem)
4058 ObjCTypeParamType(Decl, Canonical, protocols);
4059
4060 Types.push_back(newType);
4061 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4062 return QualType(newType, 0);
4063}
4064
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004065/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4066/// protocol list adopt all protocols in QT's qualified-id protocol
4067/// list.
4068bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4069 ObjCInterfaceDecl *IC) {
4070 if (!QT->isObjCQualifiedIdType())
4071 return false;
4072
4073 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4074 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004075 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004076 if (!IC->ClassImplementsProtocol(Proto, false))
4077 return false;
4078 }
4079 return true;
4080 }
4081 return false;
4082}
4083
4084/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4085/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4086/// of protocols.
4087bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4088 ObjCInterfaceDecl *IDecl) {
4089 if (!QT->isObjCQualifiedIdType())
4090 return false;
4091 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4092 if (!OPT)
4093 return false;
4094 if (!IDecl->hasDefinition())
4095 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004096 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4097 CollectInheritedProtocols(IDecl, InheritedProtocols);
4098 if (InheritedProtocols.empty())
4099 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004100 // Check that if every protocol in list of id<plist> conforms to a protcol
4101 // of IDecl's, then bridge casting is ok.
4102 bool Conforms = false;
4103 for (auto *Proto : OPT->quals()) {
4104 Conforms = false;
4105 for (auto *PI : InheritedProtocols) {
4106 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4107 Conforms = true;
4108 break;
4109 }
4110 }
4111 if (!Conforms)
4112 break;
4113 }
4114 if (Conforms)
4115 return true;
4116
Aaron Ballman83731462014-03-17 16:14:00 +00004117 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004118 // If both the right and left sides have qualifiers.
4119 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004120 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004121 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004122 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004123 break;
4124 }
4125 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004126 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004127 }
4128 return true;
4129}
4130
John McCall8b07ec22010-05-15 11:32:37 +00004131/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4132/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004133QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004134 llvm::FoldingSetNodeID ID;
4135 ObjCObjectPointerType::Profile(ID, ObjectT);
4136
Craig Topper36250ad2014-05-12 05:36:57 +00004137 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004138 if (ObjCObjectPointerType *QT =
4139 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4140 return QualType(QT, 0);
4141
4142 // Find the canonical object type.
4143 QualType Canonical;
4144 if (!ObjectT.isCanonical()) {
4145 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4146
4147 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004148 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4149 }
4150
Douglas Gregorf85bee62010-02-08 22:59:26 +00004151 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004152 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4153 ObjCObjectPointerType *QType =
4154 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004155
Steve Narofffb4330f2009-06-17 22:40:22 +00004156 Types.push_back(QType);
4157 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004158 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004159}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004160
Douglas Gregor1c283312010-08-11 12:19:30 +00004161/// getObjCInterfaceType - Return the unique reference to the type for the
4162/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004163QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4164 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004165 if (Decl->TypeForDecl)
4166 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004167
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004168 if (PrevDecl) {
4169 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4170 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4171 return QualType(PrevDecl->TypeForDecl, 0);
4172 }
4173
Douglas Gregor7671e532011-12-16 16:34:57 +00004174 // Prefer the definition, if there is one.
4175 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4176 Decl = Def;
4177
Douglas Gregor1c283312010-08-11 12:19:30 +00004178 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4179 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4180 Decl->TypeForDecl = T;
4181 Types.push_back(T);
4182 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004183}
4184
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004185/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4186/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004187/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004188/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004189/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004190QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004191 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004192 if (tofExpr->isTypeDependent()) {
4193 llvm::FoldingSetNodeID ID;
4194 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004195
Craig Topper36250ad2014-05-12 05:36:57 +00004196 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004197 DependentTypeOfExprType *Canon
4198 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4199 if (Canon) {
4200 // We already have a "canonical" version of an identical, dependent
4201 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004202 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004203 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004204 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004205 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004206 Canon
4207 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004208 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4209 toe = Canon;
4210 }
4211 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004212 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004213 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004214 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004215 Types.push_back(toe);
4216 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004217}
4218
Steve Naroffa773cd52007-08-01 18:02:17 +00004219/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004220/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004221/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004222/// an issue. This doesn't affect the type checker, since it operates
4223/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004224QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004225 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004226 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004227 Types.push_back(tot);
4228 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004229}
4230
Richard Smith8eb1d322014-06-05 20:13:13 +00004231/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4232/// nodes. This would never be helpful, since each such type has its own
4233/// expression, and would not give a significant memory saving, since there
4234/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004235QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004236 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004237
4238 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004239 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004240 // unique dependent type. Two such decltype-specifiers refer to the same
4241 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004242 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004243 llvm::FoldingSetNodeID ID;
4244 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004245
Craig Topper36250ad2014-05-12 05:36:57 +00004246 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004247 DependentDecltypeType *Canon
4248 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004249 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004250 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004251 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004252 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004253 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004254 dt = new (*this, TypeAlignment)
4255 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004256 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004257 dt = new (*this, TypeAlignment)
4258 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004259 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004260 Types.push_back(dt);
4261 return QualType(dt, 0);
4262}
4263
Alexis Hunte852b102011-05-24 22:41:36 +00004264/// getUnaryTransformationType - We don't unique these, since the memory
4265/// savings are minimal and these are rare.
4266QualType ASTContext::getUnaryTransformType(QualType BaseType,
4267 QualType UnderlyingType,
4268 UnaryTransformType::UTTKind Kind)
4269 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004270 UnaryTransformType *ut = nullptr;
4271
4272 if (BaseType->isDependentType()) {
4273 // Look in the folding set for an existing type.
4274 llvm::FoldingSetNodeID ID;
4275 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4276
4277 void *InsertPos = nullptr;
4278 DependentUnaryTransformType *Canon
4279 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4280
4281 if (!Canon) {
4282 // Build a new, canonical __underlying_type(type) type.
4283 Canon = new (*this, TypeAlignment)
4284 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4285 Kind);
4286 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4287 }
4288 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4289 QualType(), Kind,
4290 QualType(Canon, 0));
4291 } else {
4292 QualType CanonType = getCanonicalType(UnderlyingType);
4293 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4294 UnderlyingType, Kind,
4295 CanonType);
4296 }
4297 Types.push_back(ut);
4298 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004299}
4300
Richard Smith2a7d4812013-05-04 07:00:32 +00004301/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4302/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4303/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004304QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004305 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004306 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004307 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004308
Richard Smith2a7d4812013-05-04 07:00:32 +00004309 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004310 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004311 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004312 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004313 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4314 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004315
Richard Smith74aeef52013-04-26 16:15:35 +00004316 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004317 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004318 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004319 Types.push_back(AT);
4320 if (InsertPos)
4321 AutoTypes.InsertNode(AT, InsertPos);
4322 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004323}
4324
Eli Friedman0dfb8892011-10-06 23:00:33 +00004325/// getAtomicType - Return the uniqued reference to the atomic type for
4326/// the given value type.
4327QualType ASTContext::getAtomicType(QualType T) const {
4328 // Unique pointers, to guarantee there is only one pointer of a particular
4329 // structure.
4330 llvm::FoldingSetNodeID ID;
4331 AtomicType::Profile(ID, T);
4332
Craig Topper36250ad2014-05-12 05:36:57 +00004333 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004334 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4335 return QualType(AT, 0);
4336
4337 // If the atomic value type isn't canonical, this won't be a canonical type
4338 // either, so fill in the canonical type field.
4339 QualType Canonical;
4340 if (!T.isCanonical()) {
4341 Canonical = getAtomicType(getCanonicalType(T));
4342
4343 // Get the new insert position for the node we care about.
4344 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004345 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004346 }
4347 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4348 Types.push_back(New);
4349 AtomicTypes.InsertNode(New, InsertPos);
4350 return QualType(New, 0);
4351}
4352
Richard Smith02e85f32011-04-14 22:09:26 +00004353/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4354QualType ASTContext::getAutoDeductType() const {
4355 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004356 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004357 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004358 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004359 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004360 return AutoDeductTy;
4361}
4362
4363/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4364QualType ASTContext::getAutoRRefDeductType() const {
4365 if (AutoRRefDeductTy.isNull())
4366 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4367 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4368 return AutoRRefDeductTy;
4369}
4370
Chris Lattnerfb072462007-01-23 05:45:31 +00004371/// getTagDeclType - Return the unique reference to the type for the
4372/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004373QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004374 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004375 // FIXME: What is the design on getTagDeclType when it requires casting
4376 // away const? mutable?
4377 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004378}
4379
Mike Stump11289f42009-09-09 15:08:12 +00004380/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4381/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4382/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004383CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004384 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004385}
Chris Lattnerfb072462007-01-23 05:45:31 +00004386
Hans Wennborg27541db2011-10-27 08:29:09 +00004387/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4388CanQualType ASTContext::getIntMaxType() const {
4389 return getFromTargetType(Target->getIntMaxType());
4390}
4391
4392/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4393CanQualType ASTContext::getUIntMaxType() const {
4394 return getFromTargetType(Target->getUIntMaxType());
4395}
4396
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004397/// getSignedWCharType - Return the type of "signed wchar_t".
4398/// Used when in C++, as a GCC extension.
4399QualType ASTContext::getSignedWCharType() const {
4400 // FIXME: derive from "Target" ?
4401 return WCharTy;
4402}
4403
4404/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4405/// Used when in C++, as a GCC extension.
4406QualType ASTContext::getUnsignedWCharType() const {
4407 // FIXME: derive from "Target" ?
4408 return UnsignedIntTy;
4409}
4410
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004411QualType ASTContext::getIntPtrType() const {
4412 return getFromTargetType(Target->getIntPtrType());
4413}
4414
4415QualType ASTContext::getUIntPtrType() const {
4416 return getCorrespondingUnsignedType(getIntPtrType());
4417}
4418
Hans Wennborg27541db2011-10-27 08:29:09 +00004419/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004420/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4421QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004422 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004423}
4424
Eli Friedman4e91899e2012-11-27 02:58:24 +00004425/// \brief Return the unique type for "pid_t" defined in
4426/// <sys/types.h>. We need this to compute the correct type for vfork().
4427QualType ASTContext::getProcessIDType() const {
4428 return getFromTargetType(Target->getProcessIDType());
4429}
4430
Chris Lattnera21ad802008-04-02 05:18:44 +00004431//===----------------------------------------------------------------------===//
4432// Type Operators
4433//===----------------------------------------------------------------------===//
4434
Jay Foad39c79802011-01-12 09:06:06 +00004435CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004436 // Push qualifiers into arrays, and then discard any remaining
4437 // qualifiers.
4438 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004439 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004440 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004441 QualType Result;
4442 if (isa<ArrayType>(Ty)) {
4443 Result = getArrayDecayedType(QualType(Ty,0));
4444 } else if (isa<FunctionType>(Ty)) {
4445 Result = getPointerType(QualType(Ty, 0));
4446 } else {
4447 Result = QualType(Ty, 0);
4448 }
4449
4450 return CanQualType::CreateUnsafe(Result);
4451}
4452
John McCall6c9dd522011-01-18 07:41:22 +00004453QualType ASTContext::getUnqualifiedArrayType(QualType type,
4454 Qualifiers &quals) {
4455 SplitQualType splitType = type.getSplitUnqualifiedType();
4456
4457 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4458 // the unqualified desugared type and then drops it on the floor.
4459 // We then have to strip that sugar back off with
4460 // getUnqualifiedDesugaredType(), which is silly.
4461 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004462 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004463
4464 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004465 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004466 quals = splitType.Quals;
4467 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004468 }
4469
John McCall6c9dd522011-01-18 07:41:22 +00004470 // Otherwise, recurse on the array's element type.
4471 QualType elementType = AT->getElementType();
4472 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4473
4474 // If that didn't change the element type, AT has no qualifiers, so we
4475 // can just use the results in splitType.
4476 if (elementType == unqualElementType) {
4477 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004478 quals = splitType.Quals;
4479 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004480 }
4481
4482 // Otherwise, add in the qualifiers from the outermost type, then
4483 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004484 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004485
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004486 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004487 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004488 CAT->getSizeModifier(), 0);
4489 }
4490
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004491 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004492 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004493 }
4494
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004495 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004496 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004497 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004498 VAT->getSizeModifier(),
4499 VAT->getIndexTypeCVRQualifiers(),
4500 VAT->getBracketsRange());
4501 }
4502
4503 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004504 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004505 DSAT->getSizeModifier(), 0,
4506 SourceRange());
4507}
4508
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004509/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4510/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4511/// they point to and return true. If T1 and T2 aren't pointer types
4512/// or pointer-to-member types, or if they are not similar at this
4513/// level, returns false and leaves T1 and T2 unchanged. Top-level
4514/// qualifiers on T1 and T2 are ignored. This function will typically
4515/// be called in a loop that successively "unwraps" pointer and
4516/// pointer-to-member types to compare them at each level.
4517bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4518 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4519 *T2PtrType = T2->getAs<PointerType>();
4520 if (T1PtrType && T2PtrType) {
4521 T1 = T1PtrType->getPointeeType();
4522 T2 = T2PtrType->getPointeeType();
4523 return true;
4524 }
4525
4526 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4527 *T2MPType = T2->getAs<MemberPointerType>();
4528 if (T1MPType && T2MPType &&
4529 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4530 QualType(T2MPType->getClass(), 0))) {
4531 T1 = T1MPType->getPointeeType();
4532 T2 = T2MPType->getPointeeType();
4533 return true;
4534 }
4535
David Blaikiebbafb8a2012-03-11 07:00:24 +00004536 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004537 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4538 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4539 if (T1OPType && T2OPType) {
4540 T1 = T1OPType->getPointeeType();
4541 T2 = T2OPType->getPointeeType();
4542 return true;
4543 }
4544 }
4545
4546 // FIXME: Block pointers, too?
4547
4548 return false;
4549}
4550
Jay Foad39c79802011-01-12 09:06:06 +00004551DeclarationNameInfo
4552ASTContext::getNameForTemplate(TemplateName Name,
4553 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004554 switch (Name.getKind()) {
4555 case TemplateName::QualifiedTemplate:
4556 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004557 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004558 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4559 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004560
John McCalld9dfe3a2011-06-30 08:33:18 +00004561 case TemplateName::OverloadedTemplate: {
4562 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4563 // DNInfo work in progress: CHECKME: what about DNLoc?
4564 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4565 }
4566
4567 case TemplateName::DependentTemplate: {
4568 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004569 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004570 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004571 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4572 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004573 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004574 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4575 // DNInfo work in progress: FIXME: source locations?
4576 DeclarationNameLoc DNLoc;
4577 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4578 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4579 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004580 }
4581 }
4582
John McCalld9dfe3a2011-06-30 08:33:18 +00004583 case TemplateName::SubstTemplateTemplateParm: {
4584 SubstTemplateTemplateParmStorage *subst
4585 = Name.getAsSubstTemplateTemplateParm();
4586 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4587 NameLoc);
4588 }
4589
4590 case TemplateName::SubstTemplateTemplateParmPack: {
4591 SubstTemplateTemplateParmPackStorage *subst
4592 = Name.getAsSubstTemplateTemplateParmPack();
4593 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4594 NameLoc);
4595 }
4596 }
4597
4598 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004599}
4600
Jay Foad39c79802011-01-12 09:06:06 +00004601TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004602 switch (Name.getKind()) {
4603 case TemplateName::QualifiedTemplate:
4604 case TemplateName::Template: {
4605 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004606 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004607 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004608 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4609
4610 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004611 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004612 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004613
John McCalld9dfe3a2011-06-30 08:33:18 +00004614 case TemplateName::OverloadedTemplate:
4615 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004616
John McCalld9dfe3a2011-06-30 08:33:18 +00004617 case TemplateName::DependentTemplate: {
4618 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4619 assert(DTN && "Non-dependent template names must refer to template decls.");
4620 return DTN->CanonicalTemplateName;
4621 }
4622
4623 case TemplateName::SubstTemplateTemplateParm: {
4624 SubstTemplateTemplateParmStorage *subst
4625 = Name.getAsSubstTemplateTemplateParm();
4626 return getCanonicalTemplateName(subst->getReplacement());
4627 }
4628
4629 case TemplateName::SubstTemplateTemplateParmPack: {
4630 SubstTemplateTemplateParmPackStorage *subst
4631 = Name.getAsSubstTemplateTemplateParmPack();
4632 TemplateTemplateParmDecl *canonParameter
4633 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4634 TemplateArgument canonArgPack
4635 = getCanonicalTemplateArgument(subst->getArgumentPack());
4636 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4637 }
4638 }
4639
4640 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004641}
4642
Douglas Gregoradee3e32009-11-11 23:06:43 +00004643bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4644 X = getCanonicalTemplateName(X);
4645 Y = getCanonicalTemplateName(Y);
4646 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4647}
4648
Mike Stump11289f42009-09-09 15:08:12 +00004649TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004650ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004651 switch (Arg.getKind()) {
4652 case TemplateArgument::Null:
4653 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004654
Douglas Gregora8e02e72009-07-28 23:00:59 +00004655 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004656 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004657
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004658 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004659 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004660 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004661 }
Mike Stump11289f42009-09-09 15:08:12 +00004662
Eli Friedmanb826a002012-09-26 02:36:12 +00004663 case TemplateArgument::NullPtr:
4664 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4665 /*isNullPtr*/true);
4666
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004667 case TemplateArgument::Template:
4668 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004669
4670 case TemplateArgument::TemplateExpansion:
4671 return TemplateArgument(getCanonicalTemplateName(
4672 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004673 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004674
Douglas Gregora8e02e72009-07-28 23:00:59 +00004675 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004676 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004677
Douglas Gregora8e02e72009-07-28 23:00:59 +00004678 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004679 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004680
Douglas Gregora8e02e72009-07-28 23:00:59 +00004681 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004682 if (Arg.pack_size() == 0)
4683 return Arg;
4684
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004685 TemplateArgument *CanonArgs
4686 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004687 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004688 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004689 AEnd = Arg.pack_end();
4690 A != AEnd; (void)++A, ++Idx)
4691 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004692
Benjamin Kramercce63472015-08-05 09:40:22 +00004693 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004694 }
4695 }
4696
4697 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004698 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004699}
4700
Douglas Gregor333489b2009-03-27 23:10:48 +00004701NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004702ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004703 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004704 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004705
4706 switch (NNS->getKind()) {
4707 case NestedNameSpecifier::Identifier:
4708 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004709 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004710 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4711 NNS->getAsIdentifier());
4712
4713 case NestedNameSpecifier::Namespace:
4714 // A namespace is canonical; build a nested-name-specifier with
4715 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004716 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004717 NNS->getAsNamespace()->getOriginalNamespace());
4718
4719 case NestedNameSpecifier::NamespaceAlias:
4720 // A namespace is canonical; build a nested-name-specifier with
4721 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004722 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004723 NNS->getAsNamespaceAlias()->getNamespace()
4724 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004725
4726 case NestedNameSpecifier::TypeSpec:
4727 case NestedNameSpecifier::TypeSpecWithTemplate: {
4728 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004729
4730 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4731 // break it apart into its prefix and identifier, then reconsititute those
4732 // as the canonical nested-name-specifier. This is required to canonicalize
4733 // a dependent nested-name-specifier involving typedefs of dependent-name
4734 // types, e.g.,
4735 // typedef typename T::type T1;
4736 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004737 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4738 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004739 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004740
Eli Friedman5358a0a2012-03-03 04:09:56 +00004741 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4742 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4743 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004744 return NestedNameSpecifier::Create(*this, nullptr, false,
4745 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004746 }
4747
4748 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004749 case NestedNameSpecifier::Super:
4750 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004751 return NNS;
4752 }
4753
David Blaikie8a40f702012-01-17 06:56:22 +00004754 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004755}
4756
Jay Foad39c79802011-01-12 09:06:06 +00004757const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004758 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004759 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004760 // Handle the common positive case fast.
4761 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4762 return AT;
4763 }
Mike Stump11289f42009-09-09 15:08:12 +00004764
John McCall8ccfcb52009-09-24 19:53:00 +00004765 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004766 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004767 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004768
John McCall8ccfcb52009-09-24 19:53:00 +00004769 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004770 // implements C99 6.7.3p8: "If the specification of an array type includes
4771 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004772
Chris Lattner7adf0762008-08-04 07:31:14 +00004773 // If we get here, we either have type qualifiers on the type, or we have
4774 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004775 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004776
John McCall33ddac02011-01-19 10:06:00 +00004777 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004778 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004779
Chris Lattner7adf0762008-08-04 07:31:14 +00004780 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004781 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004782 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004783 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004784
Chris Lattner7adf0762008-08-04 07:31:14 +00004785 // Otherwise, we have an array and we have qualifiers on it. Push the
4786 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004787 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004788
Chris Lattner7adf0762008-08-04 07:31:14 +00004789 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4790 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4791 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004792 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004793 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4794 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4795 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004796 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004797
Mike Stump11289f42009-09-09 15:08:12 +00004798 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004799 = dyn_cast<DependentSizedArrayType>(ATy))
4800 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004801 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004802 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004803 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004804 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004805 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chris Lattner7adf0762008-08-04 07:31:14 +00004807 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004808 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004809 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004810 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004811 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004812 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004813}
4814
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004815QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004816 if (T->isArrayType() || T->isFunctionType())
4817 return getDecayedType(T);
4818 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004819}
4820
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004821QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004822 T = getVariableArrayDecayedType(T);
4823 T = getAdjustedParameterType(T);
4824 return T.getUnqualifiedType();
4825}
4826
David Majnemerd09a51c2015-03-03 01:50:05 +00004827QualType ASTContext::getExceptionObjectType(QualType T) const {
4828 // C++ [except.throw]p3:
4829 // A throw-expression initializes a temporary object, called the exception
4830 // object, the type of which is determined by removing any top-level
4831 // cv-qualifiers from the static type of the operand of throw and adjusting
4832 // the type from "array of T" or "function returning T" to "pointer to T"
4833 // or "pointer to function returning T", [...]
4834 T = getVariableArrayDecayedType(T);
4835 if (T->isArrayType() || T->isFunctionType())
4836 T = getDecayedType(T);
4837 return T.getUnqualifiedType();
4838}
4839
Chris Lattnera21ad802008-04-02 05:18:44 +00004840/// getArrayDecayedType - Return the properly qualified result of decaying the
4841/// specified array type to a pointer. This operation is non-trivial when
4842/// handling typedefs etc. The canonical type of "T" must be an array type,
4843/// this returns a pointer to a properly qualified element of the array.
4844///
4845/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004846QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004847 // Get the element type with 'getAsArrayType' so that we don't lose any
4848 // typedefs in the element type of the array. This also handles propagation
4849 // of type qualifiers from the array type into the element type if present
4850 // (C99 6.7.3p8).
4851 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4852 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004853
Chris Lattner7adf0762008-08-04 07:31:14 +00004854 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004855
4856 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004857 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004858}
4859
John McCall33ddac02011-01-19 10:06:00 +00004860QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4861 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004862}
4863
John McCall33ddac02011-01-19 10:06:00 +00004864QualType ASTContext::getBaseElementType(QualType type) const {
4865 Qualifiers qs;
4866 while (true) {
4867 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004868 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004869 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004870
John McCall33ddac02011-01-19 10:06:00 +00004871 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004872 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004873 }
Mike Stump11289f42009-09-09 15:08:12 +00004874
John McCall33ddac02011-01-19 10:06:00 +00004875 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004876}
4877
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004878/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004879uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004880ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4881 uint64_t ElementCount = 1;
4882 do {
4883 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004884 CA = dyn_cast_or_null<ConstantArrayType>(
4885 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004886 } while (CA);
4887 return ElementCount;
4888}
4889
Steve Naroff0af91202007-04-27 21:51:21 +00004890/// getFloatingRank - Return a relative rank for floating point types.
4891/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004892static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004893 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004894 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004895
John McCall9dd450b2009-09-21 23:43:11 +00004896 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4897 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004898 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004899 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004900 case BuiltinType::Float: return FloatRank;
4901 case BuiltinType::Double: return DoubleRank;
4902 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004903 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00004904 }
4905}
4906
Mike Stump11289f42009-09-09 15:08:12 +00004907/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4908/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004909/// 'typeDomain' is a real floating point or complex type.
4910/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004911QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4912 QualType Domain) const {
4913 FloatingRank EltRank = getFloatingRank(Size);
4914 if (Domain->isComplexType()) {
4915 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004916 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004917 case FloatRank: return FloatComplexTy;
4918 case DoubleRank: return DoubleComplexTy;
4919 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004920 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004921 }
Steve Naroff0af91202007-04-27 21:51:21 +00004922 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004923
4924 assert(Domain->isRealFloatingType() && "Unknown domain!");
4925 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004926 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004927 case FloatRank: return FloatTy;
4928 case DoubleRank: return DoubleTy;
4929 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004930 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00004931 }
David Blaikief47fa302012-01-17 02:30:50 +00004932 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004933}
4934
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004935/// getFloatingTypeOrder - Compare the rank of the two specified floating
4936/// point types, ignoring the domain of the type (i.e. 'double' ==
4937/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004938/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004939int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004940 FloatingRank LHSR = getFloatingRank(LHS);
4941 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004942
Chris Lattnerb90739d2008-04-06 23:38:49 +00004943 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004944 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004945 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004946 return 1;
4947 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004948}
4949
Chris Lattner76a00cf2008-04-06 22:59:24 +00004950/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4951/// routine will assert if passed a built-in type that isn't an integer or enum,
4952/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004953unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004954 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004955
Chris Lattner76a00cf2008-04-06 22:59:24 +00004956 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004957 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004958 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004959 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004960 case BuiltinType::Char_S:
4961 case BuiltinType::Char_U:
4962 case BuiltinType::SChar:
4963 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004964 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004965 case BuiltinType::Short:
4966 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004967 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004968 case BuiltinType::Int:
4969 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004970 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004971 case BuiltinType::Long:
4972 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004973 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004974 case BuiltinType::LongLong:
4975 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004976 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004977 case BuiltinType::Int128:
4978 case BuiltinType::UInt128:
4979 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004980 }
4981}
4982
Eli Friedman629ffb92009-08-20 04:21:42 +00004983/// \brief Whether this is a promotable bitfield reference according
4984/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4985///
4986/// \returns the type this bit-field will promote to, or NULL if no
4987/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004988QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004989 if (E->isTypeDependent() || E->isValueDependent())
4990 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004991
4992 // FIXME: We should not do this unless E->refersToBitField() is true. This
4993 // matters in C where getSourceBitField() will find bit-fields for various
4994 // cases where the source expression is not a bit-field designator.
4995
John McCalld25db7e2013-05-06 21:39:12 +00004996 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004997 if (!Field)
4998 return QualType();
4999
5000 QualType FT = Field->getType();
5001
Richard Smithcaf33902011-10-10 18:28:20 +00005002 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005003 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005004 // C++ [conv.prom]p5:
5005 // A prvalue for an integral bit-field can be converted to a prvalue of type
5006 // int if int can represent all the values of the bit-field; otherwise, it
5007 // can be converted to unsigned int if unsigned int can represent all the
5008 // values of the bit-field. If the bit-field is larger yet, no integral
5009 // promotion applies to it.
5010 // C11 6.3.1.1/2:
5011 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5012 // If an int can represent all values of the original type (as restricted by
5013 // the width, for a bit-field), the value is converted to an int; otherwise,
5014 // it is converted to an unsigned int.
5015 //
5016 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5017 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005018 if (BitWidth < IntSize)
5019 return IntTy;
5020
5021 if (BitWidth == IntSize)
5022 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5023
5024 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005025 // like the base type. GCC has some weird bugs in this area that we
5026 // deliberately do not follow (GCC follows a pre-standard resolution to
5027 // C's DR315 which treats bit-width as being part of the type, and this leaks
5028 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005029 return QualType();
5030}
5031
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005032/// getPromotedIntegerType - Returns the type that Promotable will
5033/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5034/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005035QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005036 assert(!Promotable.isNull());
5037 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005038 if (const EnumType *ET = Promotable->getAs<EnumType>())
5039 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005040
5041 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5042 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5043 // (3.9.1) can be converted to a prvalue of the first of the following
5044 // types that can represent all the values of its underlying type:
5045 // int, unsigned int, long int, unsigned long int, long long int, or
5046 // unsigned long long int [...]
5047 // FIXME: Is there some better way to compute this?
5048 if (BT->getKind() == BuiltinType::WChar_S ||
5049 BT->getKind() == BuiltinType::WChar_U ||
5050 BT->getKind() == BuiltinType::Char16 ||
5051 BT->getKind() == BuiltinType::Char32) {
5052 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5053 uint64_t FromSize = getTypeSize(BT);
5054 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5055 LongLongTy, UnsignedLongLongTy };
5056 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5057 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5058 if (FromSize < ToSize ||
5059 (FromSize == ToSize &&
5060 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5061 return PromoteTypes[Idx];
5062 }
5063 llvm_unreachable("char type should fit into long long");
5064 }
5065 }
5066
5067 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005068 if (Promotable->isSignedIntegerType())
5069 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005070 uint64_t PromotableSize = getIntWidth(Promotable);
5071 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005072 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5073 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5074}
5075
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005076/// \brief Recurses in pointer/array types until it finds an objc retainable
5077/// type and returns its ownership.
5078Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5079 while (!T.isNull()) {
5080 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5081 return T.getObjCLifetime();
5082 if (T->isArrayType())
5083 T = getBaseElementType(T);
5084 else if (const PointerType *PT = T->getAs<PointerType>())
5085 T = PT->getPointeeType();
5086 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005087 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005088 else
5089 break;
5090 }
5091
5092 return Qualifiers::OCL_None;
5093}
5094
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005095static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5096 // Incomplete enum types are not treated as integer types.
5097 // FIXME: In C++, enum types are never integer types.
5098 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5099 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005100 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005101}
5102
Mike Stump11289f42009-09-09 15:08:12 +00005103/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005104/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005105/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005106int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005107 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5108 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005109
5110 // Unwrap enums to their underlying type.
5111 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5112 LHSC = getIntegerTypeForEnum(ET);
5113 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5114 RHSC = getIntegerTypeForEnum(ET);
5115
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005116 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005117
Chris Lattner76a00cf2008-04-06 22:59:24 +00005118 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5119 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005120
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005121 unsigned LHSRank = getIntegerRank(LHSC);
5122 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005123
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005124 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5125 if (LHSRank == RHSRank) return 0;
5126 return LHSRank > RHSRank ? 1 : -1;
5127 }
Mike Stump11289f42009-09-09 15:08:12 +00005128
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005129 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5130 if (LHSUnsigned) {
5131 // If the unsigned [LHS] type is larger, return it.
5132 if (LHSRank >= RHSRank)
5133 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005134
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005135 // If the signed type can represent all values of the unsigned type, it
5136 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005137 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005138 return -1;
5139 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005140
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005141 // If the unsigned [RHS] type is larger, return it.
5142 if (RHSRank >= LHSRank)
5143 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005144
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005145 // If the signed type can represent all values of the unsigned type, it
5146 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005147 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005148 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005149}
Anders Carlsson98f07902007-08-17 05:31:46 +00005150
Ben Langmuirf5416742016-02-04 00:55:24 +00005151TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005152 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005153 assert(!CFConstantStringTagDecl &&
5154 "tag and typedef should be initialized together");
5155 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5156 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005157
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005158 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005159 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005160
Anders Carlsson98f07902007-08-17 05:31:46 +00005161 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005162 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005163 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005164 // int flags;
5165 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005166 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005167 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005168 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005169 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005170 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005171 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005172 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005173
Anders Carlsson98f07902007-08-17 05:31:46 +00005174 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005175 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005176 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005177 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005178 SourceLocation(),
5179 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005180 FieldTypes[i], /*TInfo=*/nullptr,
5181 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005182 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005183 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005184 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005185 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005186 }
5187
Ben Langmuirf5416742016-02-04 00:55:24 +00005188 CFConstantStringTagDecl->completeDefinition();
5189 // This type is designed to be compatible with NSConstantString, but cannot
5190 // use the same name, since NSConstantString is an interface.
5191 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5192 CFConstantStringTypeDecl =
5193 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005194 }
Mike Stump11289f42009-09-09 15:08:12 +00005195
Quentin Colombet043406b2016-02-03 22:41:00 +00005196 return CFConstantStringTypeDecl;
5197}
5198
Ben Langmuirf5416742016-02-04 00:55:24 +00005199RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5200 if (!CFConstantStringTagDecl)
5201 getCFConstantStringDecl(); // Build the tag and the typedef.
5202 return CFConstantStringTagDecl;
5203}
5204
Quentin Colombet043406b2016-02-03 22:41:00 +00005205// getCFConstantStringType - Return the type used for constant CFStrings.
5206QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005207 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005208}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005209
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005210QualType ASTContext::getObjCSuperType() const {
5211 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005212 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005213 TUDecl->addDecl(ObjCSuperTypeDecl);
5214 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5215 }
5216 return ObjCSuperType;
5217}
5218
Douglas Gregor512b0772009-04-23 22:29:11 +00005219void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005220 const TypedefType *TD = T->getAs<TypedefType>();
5221 assert(TD && "Invalid CFConstantStringType");
5222 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5223 auto TagType =
5224 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5225 assert(TagType && "Invalid CFConstantStringType");
5226 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005227}
5228
Jay Foad39c79802011-01-12 09:06:06 +00005229QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005230 if (BlockDescriptorType)
5231 return getTagDeclType(BlockDescriptorType);
5232
Alp Toker2dea15b2013-12-17 01:22:38 +00005233 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005234 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005235 RD = buildImplicitRecord("__block_descriptor");
5236 RD->startDefinition();
5237
Mike Stumpd0153282009-10-20 02:12:22 +00005238 QualType FieldTypes[] = {
5239 UnsignedLongTy,
5240 UnsignedLongTy,
5241 };
5242
Craig Topperd6d31ac2013-07-15 08:24:27 +00005243 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005244 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005245 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005246 };
5247
5248 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005249 FieldDecl *Field = FieldDecl::Create(
5250 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005251 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5252 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005253 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005254 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005255 }
5256
Alp Toker2dea15b2013-12-17 01:22:38 +00005257 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005258
Alp Toker2dea15b2013-12-17 01:22:38 +00005259 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005260
5261 return getTagDeclType(BlockDescriptorType);
5262}
5263
Jay Foad39c79802011-01-12 09:06:06 +00005264QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005265 if (BlockDescriptorExtendedType)
5266 return getTagDeclType(BlockDescriptorExtendedType);
5267
Alp Toker2dea15b2013-12-17 01:22:38 +00005268 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005269 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005270 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5271 RD->startDefinition();
5272
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005273 QualType FieldTypes[] = {
5274 UnsignedLongTy,
5275 UnsignedLongTy,
5276 getPointerType(VoidPtrTy),
5277 getPointerType(VoidPtrTy)
5278 };
5279
Craig Topperd6d31ac2013-07-15 08:24:27 +00005280 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005281 "reserved",
5282 "Size",
5283 "CopyFuncPtr",
5284 "DestroyFuncPtr"
5285 };
5286
5287 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005288 FieldDecl *Field = FieldDecl::Create(
5289 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005290 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5291 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005292 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005293 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005294 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005295 }
5296
Alp Toker2dea15b2013-12-17 01:22:38 +00005297 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005298
Alp Toker2dea15b2013-12-17 01:22:38 +00005299 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005300 return getTagDeclType(BlockDescriptorExtendedType);
5301}
5302
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005303/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5304/// requires copy/dispose. Note that this must match the logic
5305/// in buildByrefHelpers.
5306bool ASTContext::BlockRequiresCopying(QualType Ty,
5307 const VarDecl *D) {
5308 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5309 const Expr *copyExpr = getBlockVarCopyInits(D);
5310 if (!copyExpr && record->hasTrivialDestructor()) return false;
5311
Mike Stump94967902009-10-21 18:16:27 +00005312 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005313 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005314
5315 if (!Ty->isObjCRetainableType()) return false;
5316
5317 Qualifiers qs = Ty.getQualifiers();
5318
5319 // If we have lifetime, that dominates.
5320 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005321 switch (lifetime) {
5322 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5323
5324 // These are just bits as far as the runtime is concerned.
5325 case Qualifiers::OCL_ExplicitNone:
5326 case Qualifiers::OCL_Autoreleasing:
5327 return false;
5328
5329 // Tell the runtime that this is ARC __weak, called by the
5330 // byref routines.
5331 case Qualifiers::OCL_Weak:
5332 // ARC __strong __block variables need to be retained.
5333 case Qualifiers::OCL_Strong:
5334 return true;
5335 }
5336 llvm_unreachable("fell out of lifetime switch!");
5337 }
5338 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5339 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005340}
5341
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005342bool ASTContext::getByrefLifetime(QualType Ty,
5343 Qualifiers::ObjCLifetime &LifeTime,
5344 bool &HasByrefExtendedLayout) const {
5345
5346 if (!getLangOpts().ObjC1 ||
5347 getLangOpts().getGC() != LangOptions::NonGC)
5348 return false;
5349
5350 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005351 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005352 HasByrefExtendedLayout = true;
5353 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005354 } else if ((LifeTime = Ty.getObjCLifetime())) {
5355 // Honor the ARC qualifiers.
5356 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5357 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005358 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005359 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005360 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005361 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005362 return true;
5363}
5364
Douglas Gregorbab8a962011-09-08 01:46:34 +00005365TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5366 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005367 ObjCInstanceTypeDecl =
5368 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005369 return ObjCInstanceTypeDecl;
5370}
5371
Anders Carlsson18acd442007-10-29 06:33:42 +00005372// This returns true if a type has been typedefed to BOOL:
5373// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005374static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005375 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005376 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5377 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005378
Anders Carlssond8499822007-10-29 05:01:08 +00005379 return false;
5380}
5381
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005382/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005383/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005384CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005385 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5386 return CharUnits::Zero();
5387
Ken Dyck40775002010-01-11 17:06:35 +00005388 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005389
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005390 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005391 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005392 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005393 // Treat arrays as pointers, since that's how they're passed in.
5394 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005395 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005396 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005397}
5398
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005399bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005400 return getTargetInfo().getCXXABI().isMicrosoft() &&
5401 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005402 VD->getType()->isIntegralOrEnumerationType() &&
5403 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005404}
5405
Richard Smithd9b90092016-07-02 01:32:16 +00005406ASTContext::InlineVariableDefinitionKind
5407ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5408 if (!VD->isInline())
5409 return InlineVariableDefinitionKind::None;
5410
5411 // In almost all cases, it's a weak definition.
5412 auto *First = VD->getFirstDecl();
5413 if (!First->isConstexpr() || First->isInlineSpecified() ||
5414 !VD->isStaticDataMember())
5415 return InlineVariableDefinitionKind::Weak;
5416
5417 // If there's a file-context declaration in this translation unit, it's a
5418 // non-discardable definition.
5419 for (auto *D : VD->redecls())
5420 if (D->getLexicalDeclContext()->isFileContext())
5421 return InlineVariableDefinitionKind::Strong;
5422
5423 // If we've not seen one yet, we don't know.
5424 return InlineVariableDefinitionKind::WeakUnknown;
5425}
5426
Ken Dyck40775002010-01-11 17:06:35 +00005427static inline
5428std::string charUnitsToString(const CharUnits &CU) {
5429 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005430}
5431
John McCall351762c2011-02-07 10:33:21 +00005432/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005433/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005434std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5435 std::string S;
5436
David Chisnall950a9512009-11-17 19:33:30 +00005437 const BlockDecl *Decl = Expr->getBlockDecl();
5438 QualType BlockTy =
5439 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5440 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005441 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005442 getObjCEncodingForMethodParameter(
5443 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5444 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005445 else
Alp Toker314cc812014-01-25 16:55:45 +00005446 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005447 // Compute size of all parameters.
5448 // Start with computing size of a pointer in number of bytes.
5449 // FIXME: There might(should) be a better way of doing this computation!
5450 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005451 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5452 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005453 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005454 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005455 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005456 if (sz.isZero())
5457 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005458 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005459 ParmOffset += sz;
5460 }
5461 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005462 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005463 // Block pointer and offset.
5464 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005465
5466 // Argument types.
5467 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005468 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005469 QualType PType = PVDecl->getOriginalType();
5470 if (const ArrayType *AT =
5471 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5472 // Use array's original type only if it has known number of
5473 // elements.
5474 if (!isa<ConstantArrayType>(AT))
5475 PType = PVDecl->getType();
5476 } else if (PType->isFunctionType())
5477 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005478 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005479 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5480 S, true /*Extended*/);
5481 else
5482 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005483 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005484 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005485 }
John McCall351762c2011-02-07 10:33:21 +00005486
5487 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005488}
5489
Douglas Gregora9d84932011-05-27 01:19:52 +00005490bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005491 std::string& S) {
5492 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005493 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005494 CharUnits ParmOffset;
5495 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005496 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005497 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005498 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005499 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005500 continue;
5501
David Chisnall50e4eba2010-12-30 14:05:53 +00005502 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005503 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005504 ParmOffset += sz;
5505 }
5506 S += charUnitsToString(ParmOffset);
5507 ParmOffset = CharUnits::Zero();
5508
5509 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005510 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005511 QualType PType = PVDecl->getOriginalType();
5512 if (const ArrayType *AT =
5513 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5514 // Use array's original type only if it has known number of
5515 // elements.
5516 if (!isa<ConstantArrayType>(AT))
5517 PType = PVDecl->getType();
5518 } else if (PType->isFunctionType())
5519 PType = PVDecl->getType();
5520 getObjCEncodingForType(PType, S);
5521 S += charUnitsToString(ParmOffset);
5522 ParmOffset += getObjCEncodingTypeSize(PType);
5523 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005524
5525 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005526}
5527
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005528/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5529/// method parameter or return type. If Extended, include class names and
5530/// block object types.
5531void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5532 QualType T, std::string& S,
5533 bool Extended) const {
5534 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5535 getObjCEncodingForTypeQualifier(QT, S);
5536 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005537 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005538 true /*OutermostType*/,
5539 false /*EncodingProperty*/,
5540 false /*StructField*/,
5541 Extended /*EncodeBlockParameters*/,
5542 Extended /*EncodeClassNames*/);
5543}
5544
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005545/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005546/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005547bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005548 std::string& S,
5549 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005550 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005551 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005552 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5553 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005554 // Compute size of all parameters.
5555 // Start with computing size of a pointer in number of bytes.
5556 // FIXME: There might(should) be a better way of doing this computation!
5557 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005558 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005559 // The first two arguments (self and _cmd) are pointers; account for
5560 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005561 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005562 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005563 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005564 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005565 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005566 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005567 continue;
5568
Ken Dyck40775002010-01-11 17:06:35 +00005569 assert (sz.isPositive() &&
5570 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005571 ParmOffset += sz;
5572 }
Ken Dyck40775002010-01-11 17:06:35 +00005573 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005574 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005575 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005576
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005577 // Argument types.
5578 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005579 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005580 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005581 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005582 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005583 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005584 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5585 // Use array's original type only if it has known number of
5586 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005587 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005588 PType = PVDecl->getType();
5589 } else if (PType->isFunctionType())
5590 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005591 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5592 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005593 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005594 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005595 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005596
5597 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005598}
5599
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005600ObjCPropertyImplDecl *
5601ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5602 const ObjCPropertyDecl *PD,
5603 const Decl *Container) const {
5604 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005605 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005606 if (const ObjCCategoryImplDecl *CID =
5607 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005608 for (auto *PID : CID->property_impls())
5609 if (PID->getPropertyDecl() == PD)
5610 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005611 } else {
5612 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5613 for (auto *PID : OID->property_impls())
5614 if (PID->getPropertyDecl() == PD)
5615 return PID;
5616 }
5617 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005618}
5619
Daniel Dunbar4932b362008-08-28 04:38:10 +00005620/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005621/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005622/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5623/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005624/// Property attributes are stored as a comma-delimited C string. The simple
5625/// attributes readonly and bycopy are encoded as single characters. The
5626/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5627/// encoded as single characters, followed by an identifier. Property types
5628/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005629/// these attributes are defined by the following enumeration:
5630/// @code
5631/// enum PropertyAttributes {
5632/// kPropertyReadOnly = 'R', // property is read-only.
5633/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5634/// kPropertyByref = '&', // property is a reference to the value last assigned
5635/// kPropertyDynamic = 'D', // property is dynamic
5636/// kPropertyGetter = 'G', // followed by getter selector name
5637/// kPropertySetter = 'S', // followed by setter selector name
5638/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005639/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005640/// kPropertyWeak = 'W' // 'weak' property
5641/// kPropertyStrong = 'P' // property GC'able
5642/// kPropertyNonAtomic = 'N' // property non-atomic
5643/// };
5644/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005645void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005646 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005647 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005648 // Collect information from the property implementation decl(s).
5649 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005650 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005651
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005652 if (ObjCPropertyImplDecl *PropertyImpDecl =
5653 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5654 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5655 Dynamic = true;
5656 else
5657 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005658 }
5659
5660 // FIXME: This is not very efficient.
5661 S = "T";
5662
5663 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005664 // GCC has some special rules regarding encoding of properties which
5665 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005666 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005667
5668 if (PD->isReadOnly()) {
5669 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005670 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5671 S += ",C";
5672 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5673 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005674 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5675 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005676 } else {
5677 switch (PD->getSetterKind()) {
5678 case ObjCPropertyDecl::Assign: break;
5679 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005680 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005681 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005682 }
5683 }
5684
5685 // It really isn't clear at all what this means, since properties
5686 // are "dynamic by default".
5687 if (Dynamic)
5688 S += ",D";
5689
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005690 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5691 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005692
Daniel Dunbar4932b362008-08-28 04:38:10 +00005693 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5694 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005695 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005696 }
5697
5698 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5699 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005700 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005701 }
5702
5703 if (SynthesizePID) {
5704 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5705 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005706 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005707 }
5708
5709 // FIXME: OBJCGC: weak & strong
5710}
5711
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005712/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005713/// Another legacy compatibility encoding: 32-bit longs are encoded as
5714/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005715/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5716///
5717void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005718 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005719 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005720 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005721 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005722 else
Jay Foad39c79802011-01-12 09:06:06 +00005723 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005724 PointeeTy = IntTy;
5725 }
5726 }
5727}
5728
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005729void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005730 const FieldDecl *Field,
5731 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005732 // We follow the behavior of gcc, expanding structures which are
5733 // directly pointed to, and expanding embedded structures. Note that
5734 // these rules are sufficient to prevent recursive encoding of the
5735 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005736 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005737 true /* outermost type */, false, false,
5738 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005739}
5740
Joe Groff98ac7d22014-07-07 22:25:15 +00005741void ASTContext::getObjCEncodingForPropertyType(QualType T,
5742 std::string& S) const {
5743 // Encode result type.
5744 // GCC has some special rules regarding encoding of properties which
5745 // closely resembles encoding of ivars.
5746 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5747 true /* outermost type */,
5748 true /* encoding property */);
5749}
5750
John McCall393a78d2012-12-20 02:45:14 +00005751static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5752 BuiltinType::Kind kind) {
5753 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005754 case BuiltinType::Void: return 'v';
5755 case BuiltinType::Bool: return 'B';
5756 case BuiltinType::Char_U:
5757 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005758 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005759 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005760 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005761 case BuiltinType::UInt: return 'I';
5762 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005763 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005764 case BuiltinType::UInt128: return 'T';
5765 case BuiltinType::ULongLong: return 'Q';
5766 case BuiltinType::Char_S:
5767 case BuiltinType::SChar: return 'c';
5768 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005769 case BuiltinType::WChar_S:
5770 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005771 case BuiltinType::Int: return 'i';
5772 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005773 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005774 case BuiltinType::LongLong: return 'q';
5775 case BuiltinType::Int128: return 't';
5776 case BuiltinType::Float: return 'f';
5777 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005778 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005779 case BuiltinType::NullPtr: return '*'; // like char*
5780
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005781 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005782 case BuiltinType::Half:
5783 // FIXME: potentially need @encodes for these!
5784 return ' ';
5785
5786 case BuiltinType::ObjCId:
5787 case BuiltinType::ObjCClass:
5788 case BuiltinType::ObjCSel:
5789 llvm_unreachable("@encoding ObjC primitive type");
5790
5791 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005792#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5793 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005794#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005795 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005796 case BuiltinType::OCLClkEvent:
5797 case BuiltinType::OCLQueue:
5798 case BuiltinType::OCLNDRange:
5799 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005800 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005801 case BuiltinType::Dependent:
5802#define BUILTIN_TYPE(KIND, ID)
5803#define PLACEHOLDER_TYPE(KIND, ID) \
5804 case BuiltinType::KIND:
5805#include "clang/AST/BuiltinTypes.def"
5806 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005807 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005808 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005809}
5810
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005811static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5812 EnumDecl *Enum = ET->getDecl();
5813
5814 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5815 if (!Enum->isFixed())
5816 return 'i';
5817
5818 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005819 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5820 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005821}
5822
Jay Foad39c79802011-01-12 09:06:06 +00005823static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005824 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005825 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005826 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005827 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5828 // The GNU runtime requires more information; bitfields are encoded as b,
5829 // then the offset (in bits) of the first element, then the type of the
5830 // bitfield, then the size in bits. For example, in this structure:
5831 //
5832 // struct
5833 // {
5834 // int integer;
5835 // int flags:2;
5836 // };
5837 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5838 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5839 // information is not especially sensible, but we're stuck with it for
5840 // compatibility with GCC, although providing it breaks anything that
5841 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005842 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005843 const RecordDecl *RD = FD->getParent();
5844 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005845 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005846 if (const EnumType *ET = T->getAs<EnumType>())
5847 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005848 else {
5849 const BuiltinType *BT = T->castAs<BuiltinType>();
5850 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5851 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005852 }
Richard Smithcaf33902011-10-10 18:28:20 +00005853 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005854}
5855
Daniel Dunbar07d07852009-10-18 21:17:35 +00005856// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005857void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5858 bool ExpandPointedToStructures,
5859 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005860 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005861 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005862 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005863 bool StructField,
5864 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005865 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005866 bool EncodePointerToObjCTypedef,
5867 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005868 CanQualType CT = getCanonicalType(T);
5869 switch (CT->getTypeClass()) {
5870 case Type::Builtin:
5871 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005872 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005873 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005874 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5875 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5876 else
5877 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005878 return;
Mike Stump11289f42009-09-09 15:08:12 +00005879
John McCall393a78d2012-12-20 02:45:14 +00005880 case Type::Complex: {
5881 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005882 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005883 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005884 return;
5885 }
John McCall393a78d2012-12-20 02:45:14 +00005886
5887 case Type::Atomic: {
5888 const AtomicType *AT = T->castAs<AtomicType>();
5889 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005890 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005891 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005892 }
John McCall393a78d2012-12-20 02:45:14 +00005893
5894 // encoding for pointer or reference types.
5895 case Type::Pointer:
5896 case Type::LValueReference:
5897 case Type::RValueReference: {
5898 QualType PointeeTy;
5899 if (isa<PointerType>(CT)) {
5900 const PointerType *PT = T->castAs<PointerType>();
5901 if (PT->isObjCSelType()) {
5902 S += ':';
5903 return;
5904 }
5905 PointeeTy = PT->getPointeeType();
5906 } else {
5907 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5908 }
5909
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005910 bool isReadOnly = false;
5911 // For historical/compatibility reasons, the read-only qualifier of the
5912 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5913 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005914 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005915 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005916 if (OutermostType && T.isConstQualified()) {
5917 isReadOnly = true;
5918 S += 'r';
5919 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005920 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005921 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005922 while (P->getAs<PointerType>())
5923 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005924 if (P.isConstQualified()) {
5925 isReadOnly = true;
5926 S += 'r';
5927 }
5928 }
5929 if (isReadOnly) {
5930 // Another legacy compatibility encoding. Some ObjC qualifier and type
5931 // combinations need to be rearranged.
5932 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005933 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005934 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005935 }
Mike Stump11289f42009-09-09 15:08:12 +00005936
Anders Carlssond8499822007-10-29 05:01:08 +00005937 if (PointeeTy->isCharType()) {
5938 // char pointer types should be encoded as '*' unless it is a
5939 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005940 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005941 S += '*';
5942 return;
5943 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005944 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005945 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5946 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5947 S += '#';
5948 return;
5949 }
5950 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5951 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5952 S += '@';
5953 return;
5954 }
5955 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005956 }
Anders Carlssond8499822007-10-29 05:01:08 +00005957 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005958 getLegacyIntegralTypeEncoding(PointeeTy);
5959
Mike Stump11289f42009-09-09 15:08:12 +00005960 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005961 nullptr, false, false, false, false, false, false,
5962 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005963 return;
5964 }
John McCall393a78d2012-12-20 02:45:14 +00005965
5966 case Type::ConstantArray:
5967 case Type::IncompleteArray:
5968 case Type::VariableArray: {
5969 const ArrayType *AT = cast<ArrayType>(CT);
5970
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005971 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005972 // Incomplete arrays are encoded as a pointer to the array element.
5973 S += '^';
5974
Mike Stump11289f42009-09-09 15:08:12 +00005975 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005976 false, ExpandStructures, FD);
5977 } else {
5978 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005979
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005980 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5981 S += llvm::utostr(CAT->getSize().getZExtValue());
5982 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005983 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005984 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5985 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005986 S += '0';
5987 }
Mike Stump11289f42009-09-09 15:08:12 +00005988
5989 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005990 false, ExpandStructures, FD,
5991 false, false, false, false, false, false,
5992 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005993 S += ']';
5994 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005995 return;
5996 }
Mike Stump11289f42009-09-09 15:08:12 +00005997
John McCall393a78d2012-12-20 02:45:14 +00005998 case Type::FunctionNoProto:
5999 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006000 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006001 return;
Mike Stump11289f42009-09-09 15:08:12 +00006002
John McCall393a78d2012-12-20 02:45:14 +00006003 case Type::Record: {
6004 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006005 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006006 // Anonymous structures print as '?'
6007 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6008 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006009 if (ClassTemplateSpecializationDecl *Spec
6010 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6011 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006012 llvm::raw_string_ostream OS(S);
6013 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006014 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006015 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006016 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006017 } else {
6018 S += '?';
6019 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006020 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006021 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006022 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006023 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006024 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006025 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006026 if (FD) {
6027 S += '"';
6028 S += Field->getNameAsString();
6029 S += '"';
6030 }
Mike Stump11289f42009-09-09 15:08:12 +00006031
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006032 // Special case bit-fields.
6033 if (Field->isBitField()) {
6034 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006035 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006036 } else {
6037 QualType qt = Field->getType();
6038 getLegacyIntegralTypeEncoding(qt);
6039 getObjCEncodingForTypeImpl(qt, S, false, true,
6040 FD, /*OutermostType*/false,
6041 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006042 /*StructField*/true,
6043 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006044 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006045 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006046 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006047 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006048 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006049 return;
6050 }
Mike Stump11289f42009-09-09 15:08:12 +00006051
John McCall393a78d2012-12-20 02:45:14 +00006052 case Type::BlockPointer: {
6053 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006054 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006055 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006056 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006057
6058 S += '<';
6059 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006060 getObjCEncodingForTypeImpl(
6061 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6062 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006063 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6064 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006065 // Block self
6066 S += "@?";
6067 // Block parameters
6068 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006069 for (const auto &I : FPT->param_types())
6070 getObjCEncodingForTypeImpl(
6071 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6072 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006073 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6074 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006075 }
6076 S += '>';
6077 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006078 return;
6079 }
Mike Stump11289f42009-09-09 15:08:12 +00006080
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006081 case Type::ObjCObject: {
6082 // hack to match legacy encoding of *id and *Class
6083 QualType Ty = getObjCObjectPointerType(CT);
6084 if (Ty->isObjCIdType()) {
6085 S += "{objc_object=}";
6086 return;
6087 }
6088 else if (Ty->isObjCClassType()) {
6089 S += "{objc_class=}";
6090 return;
6091 }
6092 }
6093
John McCall393a78d2012-12-20 02:45:14 +00006094 case Type::ObjCInterface: {
6095 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006096 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006097 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006098 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006099 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006100 if (ExpandStructures) {
6101 S += '=';
6102 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6103 DeepCollectObjCIvars(OI, true, Ivars);
6104 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6105 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6106 if (Field->isBitField())
6107 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6108 else
6109 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6110 false, false, false, false, false,
6111 EncodePointerToObjCTypedef,
6112 NotEncodedT);
6113 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006114 }
6115 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006116 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006117 }
Mike Stump11289f42009-09-09 15:08:12 +00006118
John McCall393a78d2012-12-20 02:45:14 +00006119 case Type::ObjCObjectPointer: {
6120 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006121 if (OPT->isObjCIdType()) {
6122 S += '@';
6123 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006124 }
Mike Stump11289f42009-09-09 15:08:12 +00006125
Steve Narofff0c86112009-10-28 22:03:49 +00006126 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6127 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6128 // Since this is a binary compatibility issue, need to consult with runtime
6129 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006130 S += '#';
6131 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006132 }
Mike Stump11289f42009-09-09 15:08:12 +00006133
Chris Lattnere7cabb92009-07-13 00:10:46 +00006134 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006135 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006136 ExpandPointedToStructures,
6137 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006138 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006139 // Note that we do extended encoding of protocol qualifer list
6140 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006141 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006142 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006143 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006144 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006145 S += '>';
6146 }
6147 S += '"';
6148 }
6149 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006150 }
Mike Stump11289f42009-09-09 15:08:12 +00006151
Chris Lattnere7cabb92009-07-13 00:10:46 +00006152 QualType PointeeTy = OPT->getPointeeType();
6153 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006154 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6155 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006156 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006157 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006158 // {...};
6159 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006160 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006161 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006162 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6163 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6164 DeepCollectObjCIvars(OI, true, Ivars);
6165 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6166 if (cast<FieldDecl>(Ivars[i]) == FD) {
6167 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006168 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006169 S += '}';
6170 return;
6171 }
6172 }
6173 }
Mike Stump11289f42009-09-09 15:08:12 +00006174 getObjCEncodingForTypeImpl(PointeeTy, S,
6175 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006176 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006177 false, false, false, false, false,
6178 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006179 return;
6180 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006181
6182 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006183 if (OPT->getInterfaceDecl() &&
6184 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006185 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006186 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006187 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006188 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006189 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006190 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006191 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006192 S += '"';
6193 }
6194 return;
6195 }
Mike Stump11289f42009-09-09 15:08:12 +00006196
John McCalla9e6e8d2010-05-17 23:56:34 +00006197 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006198 // FIXME: we shoul do better than that. 'M' is available.
6199 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006200 // This matches gcc's encoding, even though technically it is insufficient.
6201 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006202 case Type::Vector:
6203 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006204 // Until we have a coherent encoding of these three types, issue warning.
6205 { if (NotEncodedT)
6206 *NotEncodedT = T;
6207 return;
6208 }
6209
6210 // We could see an undeduced auto type here during error recovery.
6211 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006212 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00006213 return;
6214
Xiuli Pan9c14e282016-01-09 12:53:17 +00006215 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006216#define ABSTRACT_TYPE(KIND, BASE)
6217#define TYPE(KIND, BASE)
6218#define DEPENDENT_TYPE(KIND, BASE) \
6219 case Type::KIND:
6220#define NON_CANONICAL_TYPE(KIND, BASE) \
6221 case Type::KIND:
6222#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6223 case Type::KIND:
6224#include "clang/AST/TypeNodes.def"
6225 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006226 }
John McCall393a78d2012-12-20 02:45:14 +00006227 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006228}
6229
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006230void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6231 std::string &S,
6232 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006233 bool includeVBases,
6234 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006235 assert(RDecl && "Expected non-null RecordDecl");
6236 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006237 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006238 return;
6239
6240 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6241 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6242 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6243
6244 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006245 for (const auto &BI : CXXRec->bases()) {
6246 if (!BI.isVirtual()) {
6247 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006248 if (base->isEmpty())
6249 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006250 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006251 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6252 std::make_pair(offs, base));
6253 }
6254 }
6255 }
6256
6257 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006258 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006259 uint64_t offs = layout.getFieldOffset(i);
6260 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006261 std::make_pair(offs, Field));
6262 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006263 }
6264
6265 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006266 for (const auto &BI : CXXRec->vbases()) {
6267 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006268 if (base->isEmpty())
6269 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006270 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006271 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6272 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006273 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6274 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006275 }
6276 }
6277
6278 CharUnits size;
6279 if (CXXRec) {
6280 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6281 } else {
6282 size = layout.getSize();
6283 }
6284
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006285#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006286 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006287#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006288 std::multimap<uint64_t, NamedDecl *>::iterator
6289 CurLayObj = FieldOrBaseOffsets.begin();
6290
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006291 if (CXXRec && CXXRec->isDynamicClass() &&
6292 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006293 if (FD) {
6294 S += "\"_vptr$";
6295 std::string recname = CXXRec->getNameAsString();
6296 if (recname.empty()) recname = "?";
6297 S += recname;
6298 S += '"';
6299 }
6300 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006301#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006302 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006303#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006304 }
6305
6306 if (!RDecl->hasFlexibleArrayMember()) {
6307 // Mark the end of the structure.
6308 uint64_t offs = toBits(size);
6309 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006310 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006311 }
6312
6313 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006314#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006315 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006316 if (CurOffs < CurLayObj->first) {
6317 uint64_t padding = CurLayObj->first - CurOffs;
6318 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6319 // packing/alignment of members is different that normal, in which case
6320 // the encoding will be out-of-sync with the real layout.
6321 // If the runtime switches to just consider the size of types without
6322 // taking into account alignment, we could make padding explicit in the
6323 // encoding (e.g. using arrays of chars). The encoding strings would be
6324 // longer then though.
6325 CurOffs += padding;
6326 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006327#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006328
6329 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006330 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006331 break; // reached end of structure.
6332
6333 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6334 // We expand the bases without their virtual bases since those are going
6335 // in the initial structure. Note that this differs from gcc which
6336 // expands virtual bases each time one is encountered in the hierarchy,
6337 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006338 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6339 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006340 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006341#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006342 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006343#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006344 } else {
6345 FieldDecl *field = cast<FieldDecl>(dcl);
6346 if (FD) {
6347 S += '"';
6348 S += field->getNameAsString();
6349 S += '"';
6350 }
6351
6352 if (field->isBitField()) {
6353 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006354#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006355 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006356#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006357 } else {
6358 QualType qt = field->getType();
6359 getLegacyIntegralTypeEncoding(qt);
6360 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6361 /*OutermostType*/false,
6362 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006363 /*StructField*/true,
6364 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006365#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006366 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006367#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006368 }
6369 }
6370 }
6371}
6372
Mike Stump11289f42009-09-09 15:08:12 +00006373void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006374 std::string& S) const {
6375 if (QT & Decl::OBJC_TQ_In)
6376 S += 'n';
6377 if (QT & Decl::OBJC_TQ_Inout)
6378 S += 'N';
6379 if (QT & Decl::OBJC_TQ_Out)
6380 S += 'o';
6381 if (QT & Decl::OBJC_TQ_Bycopy)
6382 S += 'O';
6383 if (QT & Decl::OBJC_TQ_Byref)
6384 S += 'R';
6385 if (QT & Decl::OBJC_TQ_Oneway)
6386 S += 'V';
6387}
6388
Douglas Gregor3ea72692011-08-12 05:46:01 +00006389TypedefDecl *ASTContext::getObjCIdDecl() const {
6390 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006391 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006392 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006393 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006394 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006395 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006396}
6397
Douglas Gregor52e02802011-08-12 06:17:30 +00006398TypedefDecl *ASTContext::getObjCSelDecl() const {
6399 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006400 QualType T = getPointerType(ObjCBuiltinSelTy);
6401 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006402 }
6403 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006404}
6405
Douglas Gregor0a586182011-08-12 05:59:41 +00006406TypedefDecl *ASTContext::getObjCClassDecl() const {
6407 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006408 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006409 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006410 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006411 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006412 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006413}
6414
Douglas Gregord53ae832012-01-17 18:09:05 +00006415ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6416 if (!ObjCProtocolClassDecl) {
6417 ObjCProtocolClassDecl
6418 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6419 SourceLocation(),
6420 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006421 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006422 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006423 SourceLocation(), true);
6424 }
6425
6426 return ObjCProtocolClassDecl;
6427}
6428
Meador Inge5d3fb222012-06-16 03:34:49 +00006429//===----------------------------------------------------------------------===//
6430// __builtin_va_list Construction Functions
6431//===----------------------------------------------------------------------===//
6432
Charles Davisc7d5c942015-09-17 20:55:33 +00006433static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6434 StringRef Name) {
6435 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006436 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006437 return Context->buildImplicitTypedef(T, Name);
6438}
6439
6440static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6441 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6442}
6443
6444static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6445 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006446}
6447
6448static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6449 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006450 QualType T = Context->getPointerType(Context->VoidTy);
6451 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006452}
6453
Tim Northover9bb857a2013-01-31 12:13:10 +00006454static TypedefDecl *
6455CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006456 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006457 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006458 if (Context->getLangOpts().CPlusPlus) {
6459 // namespace std { struct __va_list {
6460 NamespaceDecl *NS;
6461 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6462 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006463 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006464 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006465 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006466 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006467 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006468 }
6469
6470 VaListTagDecl->startDefinition();
6471
6472 const size_t NumFields = 5;
6473 QualType FieldTypes[NumFields];
6474 const char *FieldNames[NumFields];
6475
6476 // void *__stack;
6477 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6478 FieldNames[0] = "__stack";
6479
6480 // void *__gr_top;
6481 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6482 FieldNames[1] = "__gr_top";
6483
6484 // void *__vr_top;
6485 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6486 FieldNames[2] = "__vr_top";
6487
6488 // int __gr_offs;
6489 FieldTypes[3] = Context->IntTy;
6490 FieldNames[3] = "__gr_offs";
6491
6492 // int __vr_offs;
6493 FieldTypes[4] = Context->IntTy;
6494 FieldNames[4] = "__vr_offs";
6495
6496 // Create fields
6497 for (unsigned i = 0; i < NumFields; ++i) {
6498 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6499 VaListTagDecl,
6500 SourceLocation(),
6501 SourceLocation(),
6502 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006503 FieldTypes[i], /*TInfo=*/nullptr,
6504 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006505 /*Mutable=*/false,
6506 ICIS_NoInit);
6507 Field->setAccess(AS_public);
6508 VaListTagDecl->addDecl(Field);
6509 }
6510 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006511 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006512 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006513
6514 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006515 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006516}
6517
Meador Inge5d3fb222012-06-16 03:34:49 +00006518static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6519 // typedef struct __va_list_tag {
6520 RecordDecl *VaListTagDecl;
6521
Alp Toker2dea15b2013-12-17 01:22:38 +00006522 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006523 VaListTagDecl->startDefinition();
6524
6525 const size_t NumFields = 5;
6526 QualType FieldTypes[NumFields];
6527 const char *FieldNames[NumFields];
6528
6529 // unsigned char gpr;
6530 FieldTypes[0] = Context->UnsignedCharTy;
6531 FieldNames[0] = "gpr";
6532
6533 // unsigned char fpr;
6534 FieldTypes[1] = Context->UnsignedCharTy;
6535 FieldNames[1] = "fpr";
6536
6537 // unsigned short reserved;
6538 FieldTypes[2] = Context->UnsignedShortTy;
6539 FieldNames[2] = "reserved";
6540
6541 // void* overflow_arg_area;
6542 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6543 FieldNames[3] = "overflow_arg_area";
6544
6545 // void* reg_save_area;
6546 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6547 FieldNames[4] = "reg_save_area";
6548
6549 // Create fields
6550 for (unsigned i = 0; i < NumFields; ++i) {
6551 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6552 SourceLocation(),
6553 SourceLocation(),
6554 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006555 FieldTypes[i], /*TInfo=*/nullptr,
6556 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006557 /*Mutable=*/false,
6558 ICIS_NoInit);
6559 Field->setAccess(AS_public);
6560 VaListTagDecl->addDecl(Field);
6561 }
6562 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006563 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006564 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6565
6566 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006567 TypedefDecl *VaListTagTypedefDecl =
6568 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6569
Meador Inge5d3fb222012-06-16 03:34:49 +00006570 QualType VaListTagTypedefType =
6571 Context->getTypedefType(VaListTagTypedefDecl);
6572
6573 // typedef __va_list_tag __builtin_va_list[1];
6574 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6575 QualType VaListTagArrayType
6576 = Context->getConstantArrayType(VaListTagTypedefType,
6577 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006578 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006579}
6580
6581static TypedefDecl *
6582CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006583 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006584 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006585 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006586 VaListTagDecl->startDefinition();
6587
6588 const size_t NumFields = 4;
6589 QualType FieldTypes[NumFields];
6590 const char *FieldNames[NumFields];
6591
6592 // unsigned gp_offset;
6593 FieldTypes[0] = Context->UnsignedIntTy;
6594 FieldNames[0] = "gp_offset";
6595
6596 // unsigned fp_offset;
6597 FieldTypes[1] = Context->UnsignedIntTy;
6598 FieldNames[1] = "fp_offset";
6599
6600 // void* overflow_arg_area;
6601 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6602 FieldNames[2] = "overflow_arg_area";
6603
6604 // void* reg_save_area;
6605 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6606 FieldNames[3] = "reg_save_area";
6607
6608 // Create fields
6609 for (unsigned i = 0; i < NumFields; ++i) {
6610 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6611 VaListTagDecl,
6612 SourceLocation(),
6613 SourceLocation(),
6614 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006615 FieldTypes[i], /*TInfo=*/nullptr,
6616 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006617 /*Mutable=*/false,
6618 ICIS_NoInit);
6619 Field->setAccess(AS_public);
6620 VaListTagDecl->addDecl(Field);
6621 }
6622 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006623 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006624 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6625
Richard Smith9b88a4c2015-07-27 05:40:23 +00006626 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006627
Richard Smith9b88a4c2015-07-27 05:40:23 +00006628 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006629 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006630 QualType VaListTagArrayType =
6631 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006632 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006633}
6634
6635static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6636 // typedef int __builtin_va_list[4];
6637 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006638 QualType IntArrayType =
6639 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006640 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006641}
6642
Logan Chien57086ce2012-10-10 06:56:20 +00006643static TypedefDecl *
6644CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006645 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006646 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006647 if (Context->getLangOpts().CPlusPlus) {
6648 // namespace std { struct __va_list {
6649 NamespaceDecl *NS;
6650 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6651 Context->getTranslationUnitDecl(),
6652 /*Inline*/false, SourceLocation(),
6653 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006654 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006655 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006656 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006657 }
6658
6659 VaListDecl->startDefinition();
6660
6661 // void * __ap;
6662 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6663 VaListDecl,
6664 SourceLocation(),
6665 SourceLocation(),
6666 &Context->Idents.get("__ap"),
6667 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006668 /*TInfo=*/nullptr,
6669 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006670 /*Mutable=*/false,
6671 ICIS_NoInit);
6672 Field->setAccess(AS_public);
6673 VaListDecl->addDecl(Field);
6674
6675 // };
6676 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006677 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006678
6679 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006680 QualType T = Context->getRecordType(VaListDecl);
6681 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006682}
6683
Ulrich Weigand47445072013-05-06 16:26:41 +00006684static TypedefDecl *
6685CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006686 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006687 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006688 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006689 VaListTagDecl->startDefinition();
6690
6691 const size_t NumFields = 4;
6692 QualType FieldTypes[NumFields];
6693 const char *FieldNames[NumFields];
6694
6695 // long __gpr;
6696 FieldTypes[0] = Context->LongTy;
6697 FieldNames[0] = "__gpr";
6698
6699 // long __fpr;
6700 FieldTypes[1] = Context->LongTy;
6701 FieldNames[1] = "__fpr";
6702
6703 // void *__overflow_arg_area;
6704 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6705 FieldNames[2] = "__overflow_arg_area";
6706
6707 // void *__reg_save_area;
6708 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6709 FieldNames[3] = "__reg_save_area";
6710
6711 // Create fields
6712 for (unsigned i = 0; i < NumFields; ++i) {
6713 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6714 VaListTagDecl,
6715 SourceLocation(),
6716 SourceLocation(),
6717 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006718 FieldTypes[i], /*TInfo=*/nullptr,
6719 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006720 /*Mutable=*/false,
6721 ICIS_NoInit);
6722 Field->setAccess(AS_public);
6723 VaListTagDecl->addDecl(Field);
6724 }
6725 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006726 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006727 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006728
Richard Smith9b88a4c2015-07-27 05:40:23 +00006729 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006730
6731 // typedef __va_list_tag __builtin_va_list[1];
6732 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006733 QualType VaListTagArrayType =
6734 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006735
Alp Toker56b5cc92013-12-15 10:36:26 +00006736 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006737}
6738
Meador Inge5d3fb222012-06-16 03:34:49 +00006739static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6740 TargetInfo::BuiltinVaListKind Kind) {
6741 switch (Kind) {
6742 case TargetInfo::CharPtrBuiltinVaList:
6743 return CreateCharPtrBuiltinVaListDecl(Context);
6744 case TargetInfo::VoidPtrBuiltinVaList:
6745 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006746 case TargetInfo::AArch64ABIBuiltinVaList:
6747 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006748 case TargetInfo::PowerABIBuiltinVaList:
6749 return CreatePowerABIBuiltinVaListDecl(Context);
6750 case TargetInfo::X86_64ABIBuiltinVaList:
6751 return CreateX86_64ABIBuiltinVaListDecl(Context);
6752 case TargetInfo::PNaClABIBuiltinVaList:
6753 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006754 case TargetInfo::AAPCSABIBuiltinVaList:
6755 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006756 case TargetInfo::SystemZBuiltinVaList:
6757 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006758 }
6759
6760 llvm_unreachable("Unhandled __builtin_va_list type kind");
6761}
6762
6763TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006764 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006765 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006766 assert(BuiltinVaListDecl->isImplicit());
6767 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006768
6769 return BuiltinVaListDecl;
6770}
6771
Richard Smith9b88a4c2015-07-27 05:40:23 +00006772Decl *ASTContext::getVaListTagDecl() const {
6773 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006774 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006775 if (!VaListTagDecl)
6776 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006777
Richard Smith9b88a4c2015-07-27 05:40:23 +00006778 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006779}
6780
Charles Davisc7d5c942015-09-17 20:55:33 +00006781TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6782 if (!BuiltinMSVaListDecl)
6783 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6784
6785 return BuiltinMSVaListDecl;
6786}
6787
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006788void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006789 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006790 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006791
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006792 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006793}
6794
John McCalld28ae272009-12-02 08:04:21 +00006795/// \brief Retrieve the template name that corresponds to a non-empty
6796/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006797TemplateName
6798ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6799 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006800 unsigned size = End - Begin;
6801 assert(size > 1 && "set is not overloaded!");
6802
6803 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6804 size * sizeof(FunctionTemplateDecl*));
6805 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6806
6807 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006808 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006809 NamedDecl *D = *I;
6810 assert(isa<FunctionTemplateDecl>(D) ||
6811 (isa<UsingShadowDecl>(D) &&
6812 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6813 *Storage++ = D;
6814 }
6815
6816 return TemplateName(OT);
6817}
6818
Douglas Gregordc572a32009-03-30 22:58:21 +00006819/// \brief Retrieve the template name that represents a qualified
6820/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006821TemplateName
6822ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6823 bool TemplateKeyword,
6824 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006825 assert(NNS && "Missing nested-name-specifier in qualified template name");
6826
Douglas Gregorc42075a2010-02-04 18:10:26 +00006827 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006828 llvm::FoldingSetNodeID ID;
6829 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6830
Craig Topper36250ad2014-05-12 05:36:57 +00006831 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006832 QualifiedTemplateName *QTN =
6833 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6834 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006835 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6836 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006837 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6838 }
6839
6840 return TemplateName(QTN);
6841}
6842
6843/// \brief Retrieve the template name that represents a dependent
6844/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006845TemplateName
6846ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6847 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006848 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006849 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006850
6851 llvm::FoldingSetNodeID ID;
6852 DependentTemplateName::Profile(ID, NNS, Name);
6853
Craig Topper36250ad2014-05-12 05:36:57 +00006854 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006855 DependentTemplateName *QTN =
6856 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6857
6858 if (QTN)
6859 return TemplateName(QTN);
6860
6861 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6862 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006863 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6864 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006865 } else {
6866 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006867 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6868 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006869 DependentTemplateName *CheckQTN =
6870 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6871 assert(!CheckQTN && "Dependent type name canonicalization broken");
6872 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006873 }
6874
6875 DependentTemplateNames.InsertNode(QTN, InsertPos);
6876 return TemplateName(QTN);
6877}
6878
Douglas Gregor71395fa2009-11-04 00:56:37 +00006879/// \brief Retrieve the template name that represents a dependent
6880/// template name such as \c MetaFun::template operator+.
6881TemplateName
6882ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006883 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006884 assert((!NNS || NNS->isDependent()) &&
6885 "Nested name specifier must be dependent");
6886
6887 llvm::FoldingSetNodeID ID;
6888 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006889
6890 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006891 DependentTemplateName *QTN
6892 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006893
6894 if (QTN)
6895 return TemplateName(QTN);
6896
6897 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6898 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006899 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6900 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006901 } else {
6902 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006903 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6904 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006905
6906 DependentTemplateName *CheckQTN
6907 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6908 assert(!CheckQTN && "Dependent template name canonicalization broken");
6909 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006910 }
6911
6912 DependentTemplateNames.InsertNode(QTN, InsertPos);
6913 return TemplateName(QTN);
6914}
6915
Douglas Gregor5590be02011-01-15 06:45:20 +00006916TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006917ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6918 TemplateName replacement) const {
6919 llvm::FoldingSetNodeID ID;
6920 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006921
6922 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006923 SubstTemplateTemplateParmStorage *subst
6924 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6925
6926 if (!subst) {
6927 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6928 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6929 }
6930
6931 return TemplateName(subst);
6932}
6933
6934TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006935ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6936 const TemplateArgument &ArgPack) const {
6937 ASTContext &Self = const_cast<ASTContext &>(*this);
6938 llvm::FoldingSetNodeID ID;
6939 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006940
6941 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006942 SubstTemplateTemplateParmPackStorage *Subst
6943 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6944
6945 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006946 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006947 ArgPack.pack_size(),
6948 ArgPack.pack_begin());
6949 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6950 }
6951
6952 return TemplateName(Subst);
6953}
6954
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006955/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006956/// TargetInfo, produce the corresponding type. The unsigned @p Type
6957/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006958CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006959 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006960 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006961 case TargetInfo::SignedChar: return SignedCharTy;
6962 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006963 case TargetInfo::SignedShort: return ShortTy;
6964 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6965 case TargetInfo::SignedInt: return IntTy;
6966 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6967 case TargetInfo::SignedLong: return LongTy;
6968 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6969 case TargetInfo::SignedLongLong: return LongLongTy;
6970 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6971 }
6972
David Blaikie83d382b2011-09-23 05:06:16 +00006973 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006974}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006975
6976//===----------------------------------------------------------------------===//
6977// Type Predicates.
6978//===----------------------------------------------------------------------===//
6979
Fariborz Jahanian96207692009-02-18 21:49:28 +00006980/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6981/// garbage collection attribute.
6982///
John McCall553d45a2011-01-12 00:34:59 +00006983Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006984 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006985 return Qualifiers::GCNone;
6986
David Blaikiebbafb8a2012-03-11 07:00:24 +00006987 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006988 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6989
6990 // Default behaviour under objective-C's gc is for ObjC pointers
6991 // (or pointers to them) be treated as though they were declared
6992 // as __strong.
6993 if (GCAttrs == Qualifiers::GCNone) {
6994 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6995 return Qualifiers::Strong;
6996 else if (Ty->isPointerType())
6997 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6998 } else {
6999 // It's not valid to set GC attributes on anything that isn't a
7000 // pointer.
7001#ifndef NDEBUG
7002 QualType CT = Ty->getCanonicalTypeInternal();
7003 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7004 CT = AT->getElementType();
7005 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7006#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007007 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007008 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007009}
7010
Chris Lattner49af6a42008-04-07 06:51:04 +00007011//===----------------------------------------------------------------------===//
7012// Type Compatibility Testing
7013//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007014
Mike Stump11289f42009-09-09 15:08:12 +00007015/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007016/// compatible.
7017static bool areCompatVectorTypes(const VectorType *LHS,
7018 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007019 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007020 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007021 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007022}
7023
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007024bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7025 QualType SecondVec) {
7026 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7027 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7028
7029 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7030 return true;
7031
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007032 // Treat Neon vector types and most AltiVec vector types as if they are the
7033 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007034 const VectorType *First = FirstVec->getAs<VectorType>();
7035 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007036 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007037 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007038 First->getVectorKind() != VectorType::AltiVecPixel &&
7039 First->getVectorKind() != VectorType::AltiVecBool &&
7040 Second->getVectorKind() != VectorType::AltiVecPixel &&
7041 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007042 return true;
7043
7044 return false;
7045}
7046
Steve Naroff8e6aee52009-07-23 01:01:38 +00007047//===----------------------------------------------------------------------===//
7048// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7049//===----------------------------------------------------------------------===//
7050
7051/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7052/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007053bool
7054ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7055 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007056 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007057 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007058 for (auto *PI : rProto->protocols())
7059 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007060 return true;
7061 return false;
7062}
7063
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007064/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7065/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007066bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7067 QualType rhs) {
7068 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7069 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7070 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7071
Aaron Ballman83731462014-03-17 16:14:00 +00007072 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007073 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007074 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007075 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7076 match = true;
7077 break;
7078 }
7079 }
7080 if (!match)
7081 return false;
7082 }
7083 return true;
7084}
7085
Steve Naroff8e6aee52009-07-23 01:01:38 +00007086/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7087/// ObjCQualifiedIDType.
7088bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7089 bool compare) {
7090 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007091 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007092 lhs->isObjCIdType() || lhs->isObjCClassType())
7093 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007094 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007095 rhs->isObjCIdType() || rhs->isObjCClassType())
7096 return true;
7097
7098 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007099 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007100
Steve Naroff8e6aee52009-07-23 01:01:38 +00007101 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007102
Steve Naroff8e6aee52009-07-23 01:01:38 +00007103 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007104 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007105 // make sure we check the class hierarchy.
7106 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007107 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007108 // when comparing an id<P> on lhs with a static type on rhs,
7109 // see if static class implements all of id's protocols, directly or
7110 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007111 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007112 return false;
7113 }
7114 }
7115 // If there are no qualifiers and no interface, we have an 'id'.
7116 return true;
7117 }
Mike Stump11289f42009-09-09 15:08:12 +00007118 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007119 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007120 bool match = false;
7121
7122 // when comparing an id<P> on lhs with a static type on rhs,
7123 // see if static class implements all of id's protocols, directly or
7124 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007125 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007126 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7127 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7128 match = true;
7129 break;
7130 }
7131 }
Mike Stump11289f42009-09-09 15:08:12 +00007132 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007133 // make sure we check the class hierarchy.
7134 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007135 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007136 // when comparing an id<P> on lhs with a static type on rhs,
7137 // see if static class implements all of id's protocols, directly or
7138 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007139 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007140 match = true;
7141 break;
7142 }
7143 }
7144 }
7145 if (!match)
7146 return false;
7147 }
Mike Stump11289f42009-09-09 15:08:12 +00007148
Steve Naroff8e6aee52009-07-23 01:01:38 +00007149 return true;
7150 }
Mike Stump11289f42009-09-09 15:08:12 +00007151
Steve Naroff8e6aee52009-07-23 01:01:38 +00007152 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7153 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7154
Mike Stump11289f42009-09-09 15:08:12 +00007155 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007156 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007157 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007158 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007159 bool match = false;
7160
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007161 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007162 // see if static class implements all of id's protocols, directly or
7163 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007164 // First, lhs protocols in the qualifier list must be found, direct
7165 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007166 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007167 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7168 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7169 match = true;
7170 break;
7171 }
7172 }
7173 if (!match)
7174 return false;
7175 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007176
7177 // Static class's protocols, or its super class or category protocols
7178 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7179 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7180 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7181 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7182 // This is rather dubious but matches gcc's behavior. If lhs has
7183 // no type qualifier and its class has no static protocol(s)
7184 // assume that it is mismatch.
7185 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7186 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007187 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007188 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007189 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007190 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7191 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7192 match = true;
7193 break;
7194 }
7195 }
7196 if (!match)
7197 return false;
7198 }
7199 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007200 return true;
7201 }
7202 return false;
7203}
7204
Eli Friedman47f77112008-08-22 00:56:42 +00007205/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007206/// compatible for assignment from RHS to LHS. This handles validation of any
7207/// protocol qualifiers on the LHS or RHS.
7208///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007209bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7210 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007211 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7212 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7213
Steve Naroff1329fa02009-07-15 18:40:39 +00007214 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007215 if (LHS->isObjCUnqualifiedIdOrClass() ||
7216 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007217 return true;
7218
Douglas Gregorab209d82015-07-07 03:58:42 +00007219 // Function object that propagates a successful result or handles
7220 // __kindof types.
7221 auto finish = [&](bool succeeded) -> bool {
7222 if (succeeded)
7223 return true;
7224
7225 if (!RHS->isKindOfType())
7226 return false;
7227
7228 // Strip off __kindof and protocol qualifiers, then check whether
7229 // we can assign the other way.
7230 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7231 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7232 };
7233
7234 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7235 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7236 QualType(RHSOPT,0),
7237 false));
7238 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007239
Douglas Gregorab209d82015-07-07 03:58:42 +00007240 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7241 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7242 QualType(RHSOPT,0)));
7243 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007244
John McCall8b07ec22010-05-15 11:32:37 +00007245 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007246 if (LHS->getInterface() && RHS->getInterface()) {
7247 return finish(canAssignObjCInterfaces(LHS, RHS));
7248 }
Mike Stump11289f42009-09-09 15:08:12 +00007249
Steve Naroff8e6aee52009-07-23 01:01:38 +00007250 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007251}
7252
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007253/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007254/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007255/// arguments in block literals. When passed as arguments, passing 'A*' where
7256/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7257/// not OK. For the return type, the opposite is not OK.
7258bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7259 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007260 const ObjCObjectPointerType *RHSOPT,
7261 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007262
7263 // Function object that propagates a successful result or handles
7264 // __kindof types.
7265 auto finish = [&](bool succeeded) -> bool {
7266 if (succeeded)
7267 return true;
7268
7269 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7270 if (!Expected->isKindOfType())
7271 return false;
7272
7273 // Strip off __kindof and protocol qualifiers, then check whether
7274 // we can assign the other way.
7275 return canAssignObjCInterfacesInBlockPointer(
7276 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7277 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7278 BlockReturnType);
7279 };
7280
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007281 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007282 return true;
7283
7284 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007285 return finish(RHSOPT->isObjCBuiltinType() ||
7286 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007287 }
7288
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007289 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007290 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7291 QualType(RHSOPT,0),
7292 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007293
7294 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7295 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7296 if (LHS && RHS) { // We have 2 user-defined types.
7297 if (LHS != RHS) {
7298 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007299 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007300 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007301 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007302 }
7303 else
7304 return true;
7305 }
7306 return false;
7307}
7308
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007309/// Comparison routine for Objective-C protocols to be used with
7310/// llvm::array_pod_sort.
7311static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7312 ObjCProtocolDecl * const *rhs) {
7313 return (*lhs)->getName().compare((*rhs)->getName());
7314
7315}
7316
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007317/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007318/// of protocols inherited from two distinct objective-c pointer objects with
7319/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007320/// It is used to build composite qualifier list of the composite type of
7321/// the conditional expression involving two objective-c pointer objects.
7322static
7323void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007324 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007325 const ObjCObjectPointerType *LHSOPT,
7326 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007327 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007328
John McCall8b07ec22010-05-15 11:32:37 +00007329 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7330 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7331 assert(LHS->getInterface() && "LHS must have an interface base");
7332 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007333
7334 // Add all of the protocols for the LHS.
7335 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7336
7337 // Start with the protocol qualifiers.
7338 for (auto proto : LHS->quals()) {
7339 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007340 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007341
7342 // Also add the protocols associated with the LHS interface.
7343 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7344
7345 // Add all of the protocls for the RHS.
7346 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7347
7348 // Start with the protocol qualifiers.
7349 for (auto proto : RHS->quals()) {
7350 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007351 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007352
7353 // Also add the protocols associated with the RHS interface.
7354 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7355
7356 // Compute the intersection of the collected protocol sets.
7357 for (auto proto : LHSProtocolSet) {
7358 if (RHSProtocolSet.count(proto))
7359 IntersectionSet.push_back(proto);
7360 }
7361
7362 // Compute the set of protocols that is implied by either the common type or
7363 // the protocols within the intersection.
7364 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7365 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7366
7367 // Remove any implied protocols from the list of inherited protocols.
7368 if (!ImpliedProtocols.empty()) {
7369 IntersectionSet.erase(
7370 std::remove_if(IntersectionSet.begin(),
7371 IntersectionSet.end(),
7372 [&](ObjCProtocolDecl *proto) -> bool {
7373 return ImpliedProtocols.count(proto) > 0;
7374 }),
7375 IntersectionSet.end());
7376 }
7377
7378 // Sort the remaining protocols by name.
7379 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7380 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007381}
7382
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007383/// Determine whether the first type is a subtype of the second.
7384static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7385 QualType rhs) {
7386 // Common case: two object pointers.
7387 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7388 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7389 if (lhsOPT && rhsOPT)
7390 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7391
7392 // Two block pointers.
7393 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7394 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7395 if (lhsBlock && rhsBlock)
7396 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7397
7398 // If either is an unqualified 'id' and the other is a block, it's
7399 // acceptable.
7400 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7401 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7402 return true;
7403
7404 return false;
7405}
7406
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007407// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007408static bool sameObjCTypeArgs(ASTContext &ctx,
7409 const ObjCInterfaceDecl *iface,
7410 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007411 ArrayRef<QualType> rhsArgs,
7412 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007413 if (lhsArgs.size() != rhsArgs.size())
7414 return false;
7415
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007416 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007417 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007418 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7419 continue;
7420
7421 switch (typeParams->begin()[i]->getVariance()) {
7422 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007423 if (!stripKindOf ||
7424 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7425 rhsArgs[i].stripObjCKindOfType(ctx))) {
7426 return false;
7427 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007428 break;
7429
7430 case ObjCTypeParamVariance::Covariant:
7431 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7432 return false;
7433 break;
7434
7435 case ObjCTypeParamVariance::Contravariant:
7436 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7437 return false;
7438 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007439 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007440 }
7441
7442 return true;
7443}
7444
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007445QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007446 const ObjCObjectPointerType *Lptr,
7447 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007448 const ObjCObjectType *LHS = Lptr->getObjectType();
7449 const ObjCObjectType *RHS = Rptr->getObjectType();
7450 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7451 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007452
7453 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007454 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007455
Manman Renc46f7d12016-05-06 19:35:02 +00007456 // When either LHS or RHS is a kindof type, we should return a kindof type.
7457 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7458 // kindof(A).
7459 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7460
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007461 // Follow the left-hand side up the class hierarchy until we either hit a
7462 // root or find the RHS. Record the ancestors in case we don't find it.
7463 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7464 LHSAncestors;
7465 while (true) {
7466 // Record this ancestor. We'll need this if the common type isn't in the
7467 // path from the LHS to the root.
7468 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007469
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007470 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7471 // Get the type arguments.
7472 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7473 bool anyChanges = false;
7474 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7475 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007476 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7477 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007478 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007479 return QualType();
7480 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7481 // If only one has type arguments, the result will not have type
7482 // arguments.
7483 LHSTypeArgs = { };
7484 anyChanges = true;
7485 }
7486
7487 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007488 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007489 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7490 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007491 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007492 anyChanges = true;
7493
7494 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007495 // If we need to return a kindof type but LHS is not a kindof type, we
7496 // build a new result type.
7497 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007498 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007499 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007500 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007501 return getObjCObjectPointerType(Result);
7502 }
7503
7504 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007505 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007506
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007507 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007508 QualType LHSSuperType = LHS->getSuperClassType();
7509 if (LHSSuperType.isNull())
7510 break;
7511
7512 LHS = LHSSuperType->castAs<ObjCObjectType>();
7513 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007514
7515 // We didn't find anything by following the LHS to its root; now check
7516 // the RHS against the cached set of ancestors.
7517 while (true) {
7518 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7519 if (KnownLHS != LHSAncestors.end()) {
7520 LHS = KnownLHS->second;
7521
7522 // Get the type arguments.
7523 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7524 bool anyChanges = false;
7525 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7526 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007527 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7528 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007529 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007530 return QualType();
7531 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7532 // If only one has type arguments, the result will not have type
7533 // arguments.
7534 RHSTypeArgs = { };
7535 anyChanges = true;
7536 }
7537
7538 // Compute the intersection of protocols.
7539 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7540 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7541 Protocols);
7542 if (!Protocols.empty())
7543 anyChanges = true;
7544
Manman Renc46f7d12016-05-06 19:35:02 +00007545 // If we need to return a kindof type but RHS is not a kindof type, we
7546 // build a new result type.
7547 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007548 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007549 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007550 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007551 return getObjCObjectPointerType(Result);
7552 }
7553
7554 return getObjCObjectPointerType(QualType(RHS, 0));
7555 }
7556
7557 // Find the superclass of the RHS.
7558 QualType RHSSuperType = RHS->getSuperClassType();
7559 if (RHSSuperType.isNull())
7560 break;
7561
7562 RHS = RHSSuperType->castAs<ObjCObjectType>();
7563 }
7564
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007565 return QualType();
7566}
7567
John McCall8b07ec22010-05-15 11:32:37 +00007568bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7569 const ObjCObjectType *RHS) {
7570 assert(LHS->getInterface() && "LHS is not an interface type");
7571 assert(RHS->getInterface() && "RHS is not an interface type");
7572
Chris Lattner49af6a42008-04-07 06:51:04 +00007573 // Verify that the base decls are compatible: the RHS must be a subclass of
7574 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007575 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7576 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7577 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007578 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007579
Douglas Gregore83b9562015-07-07 03:57:53 +00007580 // If the LHS has protocol qualifiers, determine whether all of them are
7581 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7582 // LHS).
7583 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007584 // OK if conversion of LHS to SuperClass results in narrowing of types
7585 // ; i.e., SuperClass may implement at least one of the protocols
7586 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7587 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7588 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7589 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7590 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7591 // qualifiers.
7592 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007593 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007594 // If there is no protocols associated with RHS, it is not a match.
7595 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007596 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007597
7598 for (const auto *LHSProto : LHS->quals()) {
7599 bool SuperImplementsProtocol = false;
7600 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7601 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7602 SuperImplementsProtocol = true;
7603 break;
7604 }
7605 if (!SuperImplementsProtocol)
7606 return false;
7607 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007608 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007609
7610 // If the LHS is specialized, we may need to check type arguments.
7611 if (LHS->isSpecialized()) {
7612 // Follow the superclass chain until we've matched the LHS class in the
7613 // hierarchy. This substitutes type arguments through.
7614 const ObjCObjectType *RHSSuper = RHS;
7615 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7616 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7617
7618 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007619 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007620 !sameObjCTypeArgs(*this, LHS->getInterface(),
7621 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007622 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007623 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007624 }
7625 }
7626
7627 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007628}
7629
Steve Naroffb7605152009-02-12 17:52:19 +00007630bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7631 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007632 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7633 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007634
Steve Naroff7cae42b2009-07-10 23:34:53 +00007635 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007636 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007637
7638 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7639 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007640}
7641
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007642bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7643 return canAssignObjCInterfaces(
7644 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7645 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7646}
7647
Mike Stump11289f42009-09-09 15:08:12 +00007648/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007649/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007650/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007651/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007652bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7653 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007654 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007655 return hasSameType(LHS, RHS);
7656
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007657 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007658}
7659
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007660bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007661 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007662}
7663
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007664bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7665 return !mergeTypes(LHS, RHS, true).isNull();
7666}
7667
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007668/// mergeTransparentUnionType - if T is a transparent union type and a member
7669/// of T is compatible with SubType, return the merged type, else return
7670/// QualType()
7671QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7672 bool OfBlockPointer,
7673 bool Unqualified) {
7674 if (const RecordType *UT = T->getAsUnionType()) {
7675 RecordDecl *UD = UT->getDecl();
7676 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007677 for (const auto *I : UD->fields()) {
7678 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007679 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7680 if (!MT.isNull())
7681 return MT;
7682 }
7683 }
7684 }
7685
7686 return QualType();
7687}
7688
Alp Toker9cacbab2014-01-20 20:26:09 +00007689/// mergeFunctionParameterTypes - merge two types which appear as function
7690/// parameter types
7691QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7692 bool OfBlockPointer,
7693 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007694 // GNU extension: two types are compatible if they appear as a function
7695 // argument, one of the types is a transparent union type and the other
7696 // type is compatible with a union member
7697 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7698 Unqualified);
7699 if (!lmerge.isNull())
7700 return lmerge;
7701
7702 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7703 Unqualified);
7704 if (!rmerge.isNull())
7705 return rmerge;
7706
7707 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7708}
7709
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007710QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007711 bool OfBlockPointer,
7712 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007713 const FunctionType *lbase = lhs->getAs<FunctionType>();
7714 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007715 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7716 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007717 bool allLTypes = true;
7718 bool allRTypes = true;
7719
7720 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007721 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007722 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007723 QualType RHS = rbase->getReturnType();
7724 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007725 bool UnqualifiedResult = Unqualified;
7726 if (!UnqualifiedResult)
7727 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007728 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007729 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007730 else
Alp Toker314cc812014-01-25 16:55:45 +00007731 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007732 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007733 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007734
7735 if (Unqualified)
7736 retType = retType.getUnqualifiedType();
7737
Alp Toker314cc812014-01-25 16:55:45 +00007738 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7739 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007740 if (Unqualified) {
7741 LRetType = LRetType.getUnqualifiedType();
7742 RRetType = RRetType.getUnqualifiedType();
7743 }
7744
7745 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007746 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007747 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007748 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007749
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007750 // FIXME: double check this
7751 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7752 // rbase->getRegParmAttr() != 0 &&
7753 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007754 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7755 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007756
Douglas Gregor8c940862010-01-18 17:14:39 +00007757 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007758 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007759 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007760
John McCall8c6b56f2010-12-15 01:06:38 +00007761 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007762 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7763 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007764 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7765 return QualType();
7766
John McCall31168b02011-06-15 23:02:42 +00007767 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7768 return QualType();
7769
John McCall8c6b56f2010-12-15 01:06:38 +00007770 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7771 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007772
Rafael Espindola8778c282012-11-29 16:09:03 +00007773 if (lbaseInfo.getNoReturn() != NoReturn)
7774 allLTypes = false;
7775 if (rbaseInfo.getNoReturn() != NoReturn)
7776 allRTypes = false;
7777
John McCall31168b02011-06-15 23:02:42 +00007778 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007779
Eli Friedman47f77112008-08-22 00:56:42 +00007780 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007781 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7782 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007783 // Compatible functions must have the same number of parameters
7784 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007785 return QualType();
7786
7787 // Variadic and non-variadic functions aren't compatible
7788 if (lproto->isVariadic() != rproto->isVariadic())
7789 return QualType();
7790
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007791 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7792 return QualType();
7793
John McCall18afab72016-03-01 00:49:02 +00007794 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007795 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007796
7797 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007798 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007799 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7800 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7801 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7802 QualType paramType = mergeFunctionParameterTypes(
7803 lParamType, rParamType, OfBlockPointer, Unqualified);
7804 if (paramType.isNull())
7805 return QualType();
7806
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007807 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007808 paramType = paramType.getUnqualifiedType();
7809
7810 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007811 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007812 lParamType = lParamType.getUnqualifiedType();
7813 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007814 }
Alp Toker601b22c2014-01-21 23:35:24 +00007815
7816 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007817 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007818 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007819 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007820 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007821
Eli Friedman47f77112008-08-22 00:56:42 +00007822 if (allLTypes) return lhs;
7823 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007824
7825 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7826 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007827 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007828 }
7829
7830 if (lproto) allRTypes = false;
7831 if (rproto) allLTypes = false;
7832
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007833 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007834 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007835 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007836 if (proto->isVariadic()) return QualType();
7837 // Check that the types are compatible with the types that
7838 // would result from default argument promotions (C99 6.7.5.3p15).
7839 // The only types actually affected are promotable integer
7840 // types and floats, which would be passed as a different
7841 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007842 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7843 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007844
Eli Friedman448ce402012-08-30 00:44:15 +00007845 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007846 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007847 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7848 paramTy = Enum->getDecl()->getIntegerType();
7849 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007850 return QualType();
7851 }
Alp Toker601b22c2014-01-21 23:35:24 +00007852
7853 if (paramTy->isPromotableIntegerType() ||
7854 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007855 return QualType();
7856 }
7857
7858 if (allLTypes) return lhs;
7859 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007860
7861 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7862 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007863 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007864 }
7865
7866 if (allLTypes) return lhs;
7867 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007868 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007869}
7870
John McCall433c2e62013-03-21 00:10:07 +00007871/// Given that we have an enum type and a non-enum type, try to merge them.
7872static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7873 QualType other, bool isBlockReturnType) {
7874 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7875 // a signed integer type, or an unsigned integer type.
7876 // Compatibility is based on the underlying type, not the promotion
7877 // type.
7878 QualType underlyingType = ET->getDecl()->getIntegerType();
7879 if (underlyingType.isNull()) return QualType();
7880 if (Context.hasSameType(underlyingType, other))
7881 return other;
7882
7883 // In block return types, we're more permissive and accept any
7884 // integral type of the same size.
7885 if (isBlockReturnType && other->isIntegerType() &&
7886 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7887 return other;
7888
7889 return QualType();
7890}
7891
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007892QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007893 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007894 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007895 // C++ [expr]: If an expression initially has the type "reference to T", the
7896 // type is adjusted to "T" prior to any further analysis, the expression
7897 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007898 // expression is an lvalue unless the reference is an rvalue reference and
7899 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007900 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7901 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007902
7903 if (Unqualified) {
7904 LHS = LHS.getUnqualifiedType();
7905 RHS = RHS.getUnqualifiedType();
7906 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007907
Eli Friedman47f77112008-08-22 00:56:42 +00007908 QualType LHSCan = getCanonicalType(LHS),
7909 RHSCan = getCanonicalType(RHS);
7910
7911 // If two types are identical, they are compatible.
7912 if (LHSCan == RHSCan)
7913 return LHS;
7914
John McCall8ccfcb52009-09-24 19:53:00 +00007915 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007916 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7917 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007918 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007919 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00007920 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007921 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7922 return QualType();
7923 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7924 return LHS;
7925 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7926 return RHS;
7927 }
John McCall8ccfcb52009-09-24 19:53:00 +00007928 // If any of these qualifiers are different, we have a type
7929 // mismatch.
7930 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007931 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7932 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007933 return QualType();
7934
7935 // Exactly one GC qualifier difference is allowed: __strong is
7936 // okay if the other type has no GC qualifier but is an Objective
7937 // C object pointer (i.e. implicitly strong by default). We fix
7938 // this by pretending that the unqualified type was actually
7939 // qualified __strong.
7940 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7941 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7942 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7943
7944 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7945 return QualType();
7946
7947 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7948 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7949 }
7950 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7951 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7952 }
Eli Friedman47f77112008-08-22 00:56:42 +00007953 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007954 }
7955
7956 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007957
Eli Friedmandcca6332009-06-01 01:22:52 +00007958 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7959 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007960
Chris Lattnerfd652912008-01-14 05:45:46 +00007961 // We want to consider the two function types to be the same for these
7962 // comparisons, just force one to the other.
7963 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7964 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007965
7966 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007967 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7968 LHSClass = Type::ConstantArray;
7969 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7970 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007971
John McCall8b07ec22010-05-15 11:32:37 +00007972 // ObjCInterfaces are just specialized ObjCObjects.
7973 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7974 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7975
Nate Begemance4d7fc2008-04-18 23:10:10 +00007976 // Canonicalize ExtVector -> Vector.
7977 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7978 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007979
Chris Lattner95554662008-04-07 05:43:21 +00007980 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007981 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007982 // Note that we only have special rules for turning block enum
7983 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007984 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007985 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007986 }
John McCall9dd450b2009-09-21 23:43:11 +00007987 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007988 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007989 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007990 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007991 if (OfBlockPointer && !BlockReturnType) {
7992 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7993 return LHS;
7994 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7995 return RHS;
7996 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007997
Eli Friedman47f77112008-08-22 00:56:42 +00007998 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007999 }
Eli Friedman47f77112008-08-22 00:56:42 +00008000
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008001 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008002 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008003#define TYPE(Class, Base)
8004#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008005#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008006#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8007#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8008#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008009 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008010
Richard Smith27d807c2013-04-30 13:56:41 +00008011 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008012 case Type::LValueReference:
8013 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008014 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008015 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008016
John McCall8b07ec22010-05-15 11:32:37 +00008017 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008018 case Type::IncompleteArray:
8019 case Type::VariableArray:
8020 case Type::FunctionProto:
8021 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008022 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008023
Chris Lattnerfd652912008-01-14 05:45:46 +00008024 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008025 {
8026 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008027 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8028 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008029 if (Unqualified) {
8030 LHSPointee = LHSPointee.getUnqualifiedType();
8031 RHSPointee = RHSPointee.getUnqualifiedType();
8032 }
8033 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8034 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008035 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008036 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008037 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008038 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008039 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008040 return getPointerType(ResultType);
8041 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008042 case Type::BlockPointer:
8043 {
8044 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008045 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8046 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008047 if (Unqualified) {
8048 LHSPointee = LHSPointee.getUnqualifiedType();
8049 RHSPointee = RHSPointee.getUnqualifiedType();
8050 }
8051 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8052 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008053 if (ResultType.isNull()) return QualType();
8054 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8055 return LHS;
8056 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8057 return RHS;
8058 return getBlockPointerType(ResultType);
8059 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008060 case Type::Atomic:
8061 {
8062 // Merge two pointer types, while trying to preserve typedef info
8063 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8064 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8065 if (Unqualified) {
8066 LHSValue = LHSValue.getUnqualifiedType();
8067 RHSValue = RHSValue.getUnqualifiedType();
8068 }
8069 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8070 Unqualified);
8071 if (ResultType.isNull()) return QualType();
8072 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8073 return LHS;
8074 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8075 return RHS;
8076 return getAtomicType(ResultType);
8077 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008078 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008079 {
8080 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8081 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8082 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8083 return QualType();
8084
8085 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8086 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008087 if (Unqualified) {
8088 LHSElem = LHSElem.getUnqualifiedType();
8089 RHSElem = RHSElem.getUnqualifiedType();
8090 }
8091
8092 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008093 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008094 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8095 return LHS;
8096 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8097 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008098 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8099 ArrayType::ArraySizeModifier(), 0);
8100 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8101 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008102 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8103 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008104 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8105 return LHS;
8106 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8107 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008108 if (LVAT) {
8109 // FIXME: This isn't correct! But tricky to implement because
8110 // the array's size has to be the size of LHS, but the type
8111 // has to be different.
8112 return LHS;
8113 }
8114 if (RVAT) {
8115 // FIXME: This isn't correct! But tricky to implement because
8116 // the array's size has to be the size of RHS, but the type
8117 // has to be different.
8118 return RHS;
8119 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008120 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8121 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008122 return getIncompleteArrayType(ResultType,
8123 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008124 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008125 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008126 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008127 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008128 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008129 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008130 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008131 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008132 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008133 case Type::Complex:
8134 // Distinct complex types are incompatible.
8135 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008136 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008137 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008138 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8139 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008140 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008141 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008142 case Type::ObjCObject: {
8143 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008144 // FIXME: This should be type compatibility, e.g. whether
8145 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008146 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8147 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8148 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008149 return LHS;
8150
Eli Friedman47f77112008-08-22 00:56:42 +00008151 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008152 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008153 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008154 if (OfBlockPointer) {
8155 if (canAssignObjCInterfacesInBlockPointer(
8156 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008157 RHS->getAs<ObjCObjectPointerType>(),
8158 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008159 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008160 return QualType();
8161 }
John McCall9dd450b2009-09-21 23:43:11 +00008162 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8163 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008164 return LHS;
8165
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008166 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008167 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008168 case Type::Pipe:
8169 {
8170 // Merge two pointer types, while trying to preserve typedef info
8171 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
8172 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
8173 if (Unqualified) {
8174 LHSValue = LHSValue.getUnqualifiedType();
8175 RHSValue = RHSValue.getUnqualifiedType();
8176 }
8177 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8178 Unqualified);
8179 if (ResultType.isNull()) return QualType();
8180 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8181 return LHS;
8182 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8183 return RHS;
8184 return getPipeType(ResultType);
8185 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008186 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008187
David Blaikie8a40f702012-01-17 06:56:22 +00008188 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008189}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008190
John McCall18afab72016-03-01 00:49:02 +00008191bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8192 const FunctionProtoType *firstFnType,
8193 const FunctionProtoType *secondFnType) {
8194 // Fast path: if the first type doesn't have ext parameter infos,
8195 // we match if and only if they second type also doesn't have them.
8196 if (!firstFnType->hasExtParameterInfos())
8197 return !secondFnType->hasExtParameterInfos();
8198
8199 // Otherwise, we can only match if the second type has them.
8200 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008201 return false;
John McCall18afab72016-03-01 00:49:02 +00008202
8203 auto firstEPI = firstFnType->getExtParameterInfos();
8204 auto secondEPI = secondFnType->getExtParameterInfos();
8205 assert(firstEPI.size() == secondEPI.size());
8206
8207 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8208 if (firstEPI[i] != secondEPI[i])
8209 return false;
8210 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008211 return true;
8212}
8213
Chandler Carruth21c90602015-12-30 03:24:14 +00008214void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8215 ObjCLayouts[CD] = nullptr;
8216}
8217
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008218/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8219/// 'RHS' attributes and returns the merged version; including for function
8220/// return types.
8221QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8222 QualType LHSCan = getCanonicalType(LHS),
8223 RHSCan = getCanonicalType(RHS);
8224 // If two types are identical, they are compatible.
8225 if (LHSCan == RHSCan)
8226 return LHS;
8227 if (RHSCan->isFunctionType()) {
8228 if (!LHSCan->isFunctionType())
8229 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008230 QualType OldReturnType =
8231 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008232 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008233 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008234 QualType ResReturnType =
8235 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8236 if (ResReturnType.isNull())
8237 return QualType();
8238 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8239 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8240 // In either case, use OldReturnType to build the new function type.
8241 const FunctionType *F = LHS->getAs<FunctionType>();
8242 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008243 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8244 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008245 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008246 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008247 return ResultType;
8248 }
8249 }
8250 return QualType();
8251 }
8252
8253 // If the qualifiers are different, the types can still be merged.
8254 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8255 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8256 if (LQuals != RQuals) {
8257 // If any of these qualifiers are different, we have a type mismatch.
8258 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8259 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8260 return QualType();
8261
8262 // Exactly one GC qualifier difference is allowed: __strong is
8263 // okay if the other type has no GC qualifier but is an Objective
8264 // C object pointer (i.e. implicitly strong by default). We fix
8265 // this by pretending that the unqualified type was actually
8266 // qualified __strong.
8267 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8268 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8269 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8270
8271 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8272 return QualType();
8273
8274 if (GC_L == Qualifiers::Strong)
8275 return LHS;
8276 if (GC_R == Qualifiers::Strong)
8277 return RHS;
8278 return QualType();
8279 }
8280
8281 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8282 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8283 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8284 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8285 if (ResQT == LHSBaseQT)
8286 return LHS;
8287 if (ResQT == RHSBaseQT)
8288 return RHS;
8289 }
8290 return QualType();
8291}
8292
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008293//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008294// Integer Predicates
8295//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008296
Jay Foad39c79802011-01-12 09:06:06 +00008297unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008298 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008299 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008300 if (T->isBooleanType())
8301 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008302 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008303 return (unsigned)getTypeSize(T);
8304}
8305
Abramo Bagnara13640492012-09-09 10:21:24 +00008306QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008307 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008308
8309 // Turn <4 x signed int> -> <4 x unsigned int>
8310 if (const VectorType *VTy = T->getAs<VectorType>())
8311 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008312 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008313
8314 // For enums, we return the unsigned version of the base type.
8315 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008316 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008317
8318 const BuiltinType *BTy = T->getAs<BuiltinType>();
8319 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008320 switch (BTy->getKind()) {
8321 case BuiltinType::Char_S:
8322 case BuiltinType::SChar:
8323 return UnsignedCharTy;
8324 case BuiltinType::Short:
8325 return UnsignedShortTy;
8326 case BuiltinType::Int:
8327 return UnsignedIntTy;
8328 case BuiltinType::Long:
8329 return UnsignedLongTy;
8330 case BuiltinType::LongLong:
8331 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008332 case BuiltinType::Int128:
8333 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008334 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008335 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008336 }
8337}
8338
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008339ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008340
Richard Smith1fa5d642013-05-11 05:45:24 +00008341void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8342 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008343
8344//===----------------------------------------------------------------------===//
8345// Builtin Type Computation
8346//===----------------------------------------------------------------------===//
8347
8348/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008349/// pointer over the consumed characters. This returns the resultant type. If
8350/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8351/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8352/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008353///
8354/// RequiresICE is filled in on return to indicate whether the value is required
8355/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008356static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008357 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008358 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008359 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008360 // Modifiers.
8361 int HowLong = 0;
8362 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008363 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008364
Chris Lattnerdc226c22010-10-01 22:42:38 +00008365 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008366 bool Done = false;
8367 while (!Done) {
8368 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008369 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008370 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008371 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008372 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008373 case 'S':
8374 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8375 assert(!Signed && "Can't use 'S' modifier multiple times!");
8376 Signed = true;
8377 break;
8378 case 'U':
8379 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008380 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008381 Unsigned = true;
8382 break;
8383 case 'L':
8384 assert(HowLong <= 2 && "Can't have LLLL modifier");
8385 ++HowLong;
8386 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008387 case 'W':
8388 // This modifier represents int64 type.
8389 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8390 switch (Context.getTargetInfo().getInt64Type()) {
8391 default:
8392 llvm_unreachable("Unexpected integer type");
8393 case TargetInfo::SignedLong:
8394 HowLong = 1;
8395 break;
8396 case TargetInfo::SignedLongLong:
8397 HowLong = 2;
8398 break;
8399 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008400 }
8401 }
8402
8403 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008404
Chris Lattnerecd79c62009-06-14 00:45:47 +00008405 // Read the base type.
8406 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008407 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008408 case 'v':
8409 assert(HowLong == 0 && !Signed && !Unsigned &&
8410 "Bad modifiers used with 'v'!");
8411 Type = Context.VoidTy;
8412 break;
Jack Carter24bef982013-08-15 15:16:57 +00008413 case 'h':
8414 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008415 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008416 Type = Context.HalfTy;
8417 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008418 case 'f':
8419 assert(HowLong == 0 && !Signed && !Unsigned &&
8420 "Bad modifiers used with 'f'!");
8421 Type = Context.FloatTy;
8422 break;
8423 case 'd':
8424 assert(HowLong < 2 && !Signed && !Unsigned &&
8425 "Bad modifiers used with 'd'!");
8426 if (HowLong)
8427 Type = Context.LongDoubleTy;
8428 else
8429 Type = Context.DoubleTy;
8430 break;
8431 case 's':
8432 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8433 if (Unsigned)
8434 Type = Context.UnsignedShortTy;
8435 else
8436 Type = Context.ShortTy;
8437 break;
8438 case 'i':
8439 if (HowLong == 3)
8440 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8441 else if (HowLong == 2)
8442 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8443 else if (HowLong == 1)
8444 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8445 else
8446 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8447 break;
8448 case 'c':
8449 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8450 if (Signed)
8451 Type = Context.SignedCharTy;
8452 else if (Unsigned)
8453 Type = Context.UnsignedCharTy;
8454 else
8455 Type = Context.CharTy;
8456 break;
8457 case 'b': // boolean
8458 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8459 Type = Context.BoolTy;
8460 break;
8461 case 'z': // size_t.
8462 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8463 Type = Context.getSizeType();
8464 break;
8465 case 'F':
8466 Type = Context.getCFConstantStringType();
8467 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008468 case 'G':
8469 Type = Context.getObjCIdType();
8470 break;
8471 case 'H':
8472 Type = Context.getObjCSelType();
8473 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008474 case 'M':
8475 Type = Context.getObjCSuperType();
8476 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008477 case 'a':
8478 Type = Context.getBuiltinVaListType();
8479 assert(!Type.isNull() && "builtin va list type not initialized!");
8480 break;
8481 case 'A':
8482 // This is a "reference" to a va_list; however, what exactly
8483 // this means depends on how va_list is defined. There are two
8484 // different kinds of va_list: ones passed by value, and ones
8485 // passed by reference. An example of a by-value va_list is
8486 // x86, where va_list is a char*. An example of by-ref va_list
8487 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8488 // we want this argument to be a char*&; for x86-64, we want
8489 // it to be a __va_list_tag*.
8490 Type = Context.getBuiltinVaListType();
8491 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008492 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008493 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008494 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008495 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008496 break;
8497 case 'V': {
8498 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008499 unsigned NumElements = strtoul(Str, &End, 10);
8500 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008501 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008502
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008503 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8504 RequiresICE, false);
8505 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008506
8507 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008508 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008509 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008510 break;
8511 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008512 case 'E': {
8513 char *End;
8514
8515 unsigned NumElements = strtoul(Str, &End, 10);
8516 assert(End != Str && "Missing vector size");
8517
8518 Str = End;
8519
8520 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8521 false);
8522 Type = Context.getExtVectorType(ElementType, NumElements);
8523 break;
8524 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008525 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008526 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8527 false);
8528 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008529 Type = Context.getComplexType(ElementType);
8530 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008531 }
8532 case 'Y' : {
8533 Type = Context.getPointerDiffType();
8534 break;
8535 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008536 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008537 Type = Context.getFILEType();
8538 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008539 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008540 return QualType();
8541 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008542 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008543 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008544 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008545 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008546 else
8547 Type = Context.getjmp_bufType();
8548
Mike Stump2adb4da2009-07-28 23:47:15 +00008549 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008550 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008551 return QualType();
8552 }
8553 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008554 case 'K':
8555 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8556 Type = Context.getucontext_tType();
8557
8558 if (Type.isNull()) {
8559 Error = ASTContext::GE_Missing_ucontext;
8560 return QualType();
8561 }
8562 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008563 case 'p':
8564 Type = Context.getProcessIDType();
8565 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008566 }
Mike Stump11289f42009-09-09 15:08:12 +00008567
Chris Lattnerdc226c22010-10-01 22:42:38 +00008568 // If there are modifiers and if we're allowed to parse them, go for it.
8569 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008570 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008571 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008572 default: Done = true; --Str; break;
8573 case '*':
8574 case '&': {
8575 // Both pointers and references can have their pointee types
8576 // qualified with an address space.
8577 char *End;
8578 unsigned AddrSpace = strtoul(Str, &End, 10);
8579 if (End != Str && AddrSpace != 0) {
8580 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8581 Str = End;
8582 }
8583 if (c == '*')
8584 Type = Context.getPointerType(Type);
8585 else
8586 Type = Context.getLValueReferenceType(Type);
8587 break;
8588 }
8589 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8590 case 'C':
8591 Type = Type.withConst();
8592 break;
8593 case 'D':
8594 Type = Context.getVolatileType(Type);
8595 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008596 case 'R':
8597 Type = Type.withRestrict();
8598 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008599 }
8600 }
Chris Lattner84733392010-10-01 07:13:18 +00008601
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008602 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008603 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008604
Chris Lattnerecd79c62009-06-14 00:45:47 +00008605 return Type;
8606}
8607
8608/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008609QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008610 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008611 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008612 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008613
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008614 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008615
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008616 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008617 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008618 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8619 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008620 if (Error != GE_None)
8621 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008622
8623 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8624
Chris Lattnerecd79c62009-06-14 00:45:47 +00008625 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008626 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008627 if (Error != GE_None)
8628 return QualType();
8629
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008630 // If this argument is required to be an IntegerConstantExpression and the
8631 // caller cares, fill in the bitmask we return.
8632 if (RequiresICE && IntegerConstantArgs)
8633 *IntegerConstantArgs |= 1 << ArgTypes.size();
8634
Chris Lattnerecd79c62009-06-14 00:45:47 +00008635 // Do array -> pointer decay. The builtin should use the decayed type.
8636 if (Ty->isArrayType())
8637 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008638
Chris Lattnerecd79c62009-06-14 00:45:47 +00008639 ArgTypes.push_back(Ty);
8640 }
8641
David Majnemerba3e5ec2015-03-13 18:26:17 +00008642 if (Id == Builtin::BI__GetExceptionInfo)
8643 return QualType();
8644
Chris Lattnerecd79c62009-06-14 00:45:47 +00008645 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8646 "'.' should only occur at end of builtin type list!");
8647
Reid Kleckner78af0702013-08-27 23:08:25 +00008648 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008649 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8650
8651 bool Variadic = (TypeStr[0] == '.');
8652
8653 // We really shouldn't be making a no-proto type here, especially in C++.
8654 if (ArgTypes.empty() && Variadic)
8655 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008656
John McCalldb40c7f2010-12-14 08:05:40 +00008657 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008658 EPI.ExtInfo = EI;
8659 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008660
Jordan Rose5c382722013-03-08 21:51:21 +00008661 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008662}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008663
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008664static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8665 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008666 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008667 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008668
Rafael Espindola3ae00052013-05-13 00:12:11 +00008669 GVALinkage External = GVA_StrongExternal;
8670 switch (FD->getTemplateSpecializationKind()) {
8671 case TSK_Undeclared:
8672 case TSK_ExplicitSpecialization:
8673 External = GVA_StrongExternal;
8674 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008675
Rafael Espindola3ae00052013-05-13 00:12:11 +00008676 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008677 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008678
David Majnemerc3d07332014-05-15 06:25:57 +00008679 // C++11 [temp.explicit]p10:
8680 // [ Note: The intent is that an inline function that is the subject of
8681 // an explicit instantiation declaration will still be implicitly
8682 // instantiated when used so that the body can be considered for
8683 // inlining, but that no out-of-line copy of the inline function would be
8684 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008685 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008686 return GVA_AvailableExternally;
8687
Rafael Espindola3ae00052013-05-13 00:12:11 +00008688 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008689 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008690 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008691 }
8692
8693 if (!FD->isInlined())
8694 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008695
David Majnemer3f021502015-10-08 04:53:31 +00008696 if ((!Context.getLangOpts().CPlusPlus &&
8697 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008698 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008699 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008700 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8701
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008702 // GNU or C99 inline semantics. Determine whether this symbol should be
8703 // externally visible.
8704 if (FD->isInlineDefinitionExternallyVisible())
8705 return External;
8706
8707 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008708 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008709 }
8710
David Majnemer54e3ba52014-04-02 23:17:29 +00008711 // Functions specified with extern and inline in -fms-compatibility mode
8712 // forcibly get emitted. While the body of the function cannot be later
8713 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008714 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008715 return GVA_StrongODR;
8716
David Majnemer27d69db2014-04-28 22:17:59 +00008717 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008718}
8719
Artem Belevichca2b9512016-05-02 20:30:03 +00008720static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8721 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008722 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8723 // dllexport/dllimport on inline functions.
8724 if (D->hasAttr<DLLImportAttr>()) {
8725 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8726 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008727 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008728 if (L == GVA_DiscardableODR)
8729 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008730 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8731 D->hasAttr<CUDAGlobalAttr>()) {
8732 // Device-side functions with __global__ attribute must always be
8733 // visible externally so they can be launched from host.
8734 if (L == GVA_DiscardableODR || L == GVA_Internal)
8735 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008736 }
8737 return L;
8738}
8739
8740GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008741 return adjustGVALinkageForAttributes(
8742 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008743}
8744
8745static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8746 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008747 if (!VD->isExternallyVisible())
8748 return GVA_Internal;
8749
David Majnemer27d69db2014-04-28 22:17:59 +00008750 if (VD->isStaticLocal()) {
8751 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8752 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8753 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8754 LexicalContext = LexicalContext->getLexicalParent();
8755
Richard Smith9e2341d2015-03-23 03:25:59 +00008756 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008757 // enclosing function.
8758 if (LexicalContext)
8759 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008760 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008761
8762 // GVA_StrongODR function linkage is stronger than what we need,
8763 // downgrade to GVA_DiscardableODR.
8764 // This allows us to discard the variable if we never end up needing it.
8765 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8766 : StaticLocalLinkage;
8767 }
8768
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008769 // MSVC treats in-class initialized static data members as definitions.
8770 // By giving them non-strong linkage, out-of-line definitions won't
8771 // cause link errors.
8772 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8773 return GVA_DiscardableODR;
8774
Richard Smithd9b90092016-07-02 01:32:16 +00008775 // Most non-template variables have strong linkage; inline variables are
8776 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8777 GVALinkage StrongLinkage;
8778 switch (Context.getInlineVariableDefinitionKind(VD)) {
8779 case ASTContext::InlineVariableDefinitionKind::None:
8780 StrongLinkage = GVA_StrongExternal;
8781 break;
8782 case ASTContext::InlineVariableDefinitionKind::Weak:
8783 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008784 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008785 break;
8786 case ASTContext::InlineVariableDefinitionKind::Strong:
8787 StrongLinkage = GVA_StrongODR;
8788 break;
8789 }
Richard Smith62f19e72016-06-25 00:15:56 +00008790
Richard Smith8809a0c2013-09-27 20:14:12 +00008791 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008792 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008793 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008794
David Majnemer6d1780c2015-07-17 23:36:49 +00008795 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008796 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8797 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008798 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008799 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008800
Rafael Espindola3ae00052013-05-13 00:12:11 +00008801 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008802 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008803
David Majnemer27d69db2014-04-28 22:17:59 +00008804 case TSK_ExplicitInstantiationDeclaration:
8805 return GVA_AvailableExternally;
8806
Rafael Espindola3ae00052013-05-13 00:12:11 +00008807 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008808 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008809 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008810
8811 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008812}
8813
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008814GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008815 return adjustGVALinkageForAttributes(
8816 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008817}
8818
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008819bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008820 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8821 if (!VD->isFileVarDecl())
8822 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008823 // Global named register variables (GNU extension) are never emitted.
8824 if (VD->getStorageClass() == SC_Register)
8825 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008826 if (VD->getDescribedVarTemplate() ||
8827 isa<VarTemplatePartialSpecializationDecl>(VD))
8828 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008829 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8830 // We never need to emit an uninstantiated function template.
8831 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8832 return false;
Nico Weber66220292016-03-02 17:28:48 +00008833 } else if (isa<PragmaCommentDecl>(D))
8834 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008835 else if (isa<OMPThreadPrivateDecl>(D) ||
8836 D->hasAttr<OMPDeclareTargetDeclAttr>())
8837 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008838 else if (isa<PragmaDetectMismatchDecl>(D))
8839 return true;
Nico Weber66220292016-03-02 17:28:48 +00008840 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008841 return !D->getDeclContext()->isDependentContext();
8842 else if (isa<OMPDeclareReductionDecl>(D))
8843 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00008844 else if (isa<ImportDecl>(D))
8845 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00008846 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008847 return false;
8848
8849 // If this is a member of a class template, we do not need to emit it.
8850 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008851 return false;
8852
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008853 // Weak references don't produce any output by themselves.
8854 if (D->hasAttr<WeakRefAttr>())
8855 return false;
8856
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008857 // Aliases and used decls are required.
8858 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8859 return true;
8860
8861 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8862 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008863 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008864 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008865
8866 // Constructors and destructors are required.
8867 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8868 return true;
8869
John McCall6bd2a892013-01-25 22:31:03 +00008870 // The key function for a class is required. This rule only comes
8871 // into play when inline functions can be key functions, though.
8872 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8873 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8874 const CXXRecordDecl *RD = MD->getParent();
8875 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8876 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8877 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8878 return true;
8879 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008880 }
8881 }
8882
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008883 // static, static inline, always_inline, and extern inline functions can
8884 // always be deferred. Normal inline functions can be deferred in C99/C++.
8885 // Implicit template instantiations can also be deferred in C++.
Justin Lebar606f01f2016-10-13 20:52:17 +00008886 return !isDiscardableGVALinkage(GetGVALinkageForFunction(FD));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008887 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008888
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008889 const VarDecl *VD = cast<VarDecl>(D);
8890 assert(VD->isFileVarDecl() && "Expected file scoped var");
8891
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008892 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8893 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008894 return false;
8895
Richard Smitha0e5e542012-11-12 21:38:00 +00008896 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00008897 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00008898 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008899
Richard Smitha0e5e542012-11-12 21:38:00 +00008900 // Variables that have destruction with side-effects are required.
8901 if (VD->getType().isDestructedType())
8902 return true;
8903
8904 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008905 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8906 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008907 return true;
8908
Richard Smithda383632016-08-15 01:33:41 +00008909 // Likewise, variables with tuple-like bindings are required if their
8910 // bindings have side-effects.
8911 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
8912 for (auto *BD : DD->bindings())
8913 if (auto *BindingVD = BD->getHoldingVar())
8914 if (DeclMustBeEmitted(BindingVD))
8915 return true;
8916
Richard Smitha0e5e542012-11-12 21:38:00 +00008917 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008918}
Charles Davis53c59df2010-08-16 03:33:14 +00008919
Reid Kleckner78af0702013-08-27 23:08:25 +00008920CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8921 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008922 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008923 if (IsCXXMethod)
8924 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008925
Alexey Bataeva7547182016-05-18 09:06:38 +00008926 switch (LangOpts.getDefaultCallingConv()) {
8927 case LangOptions::DCC_None:
8928 break;
8929 case LangOptions::DCC_CDecl:
8930 return CC_C;
8931 case LangOptions::DCC_FastCall:
8932 if (getTargetInfo().hasFeature("sse2"))
8933 return CC_X86FastCall;
8934 break;
8935 case LangOptions::DCC_StdCall:
8936 if (!IsVariadic)
8937 return CC_X86StdCall;
8938 break;
8939 case LangOptions::DCC_VectorCall:
8940 // __vectorcall cannot be applied to variadic functions.
8941 if (!IsVariadic)
8942 return CC_X86VectorCall;
8943 break;
8944 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008945 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008946}
8947
Jay Foad39c79802011-01-12 09:06:06 +00008948bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008949 // Pass through to the C++ ABI object
8950 return ABI->isNearlyEmpty(RD);
8951}
8952
Reid Kleckner96f8f932014-02-05 17:27:08 +00008953VTableContextBase *ASTContext::getVTableContext() {
8954 if (!VTContext.get()) {
8955 if (Target->getCXXABI().isMicrosoft())
8956 VTContext.reset(new MicrosoftVTableContext(*this));
8957 else
8958 VTContext.reset(new ItaniumVTableContext(*this));
8959 }
8960 return VTContext.get();
8961}
8962
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008963MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008964 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008965 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008966 case TargetCXXABI::GenericItanium:
8967 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008968 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008969 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008970 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008971 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008972 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008973 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008974 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008975 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008976 }
David Blaikie83d382b2011-09-23 05:06:16 +00008977 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008978}
8979
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008980CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008981
8982size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008983 return ASTRecordLayouts.getMemorySize() +
8984 llvm::capacity_in_bytes(ObjCLayouts) +
8985 llvm::capacity_in_bytes(KeyFunctions) +
8986 llvm::capacity_in_bytes(ObjCImpls) +
8987 llvm::capacity_in_bytes(BlockVarCopyInits) +
8988 llvm::capacity_in_bytes(DeclAttrs) +
8989 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8990 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8991 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8992 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8993 llvm::capacity_in_bytes(OverriddenMethods) +
8994 llvm::capacity_in_bytes(Types) +
8995 llvm::capacity_in_bytes(VariableArrayTypes) +
8996 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008997}
Ted Kremenek540017e2011-10-06 05:00:56 +00008998
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008999/// getIntTypeForBitwidth -
9000/// sets integer QualTy according to specified details:
9001/// bitwidth, signed/unsigned.
9002/// Returns empty type if there is no appropriate target types.
9003QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9004 unsigned Signed) const {
9005 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9006 CanQualType QualTy = getFromTargetType(Ty);
9007 if (!QualTy && DestWidth == 128)
9008 return Signed ? Int128Ty : UnsignedInt128Ty;
9009 return QualTy;
9010}
9011
9012/// getRealTypeForBitwidth -
9013/// sets floating point QualTy according to specified bitwidth.
9014/// Returns empty type if there is no appropriate target types.
9015QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9016 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9017 switch (Ty) {
9018 case TargetInfo::Float:
9019 return FloatTy;
9020 case TargetInfo::Double:
9021 return DoubleTy;
9022 case TargetInfo::LongDouble:
9023 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009024 case TargetInfo::Float128:
9025 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009026 case TargetInfo::NoFloat:
9027 return QualType();
9028 }
9029
9030 llvm_unreachable("Unhandled TargetInfo::RealType value");
9031}
9032
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009033void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9034 if (Number > 1)
9035 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009036}
9037
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009038unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009039 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009040 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009041}
9042
David Majnemer2206bf52014-03-05 08:57:59 +00009043void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9044 if (Number > 1)
9045 StaticLocalNumbers[VD] = Number;
9046}
9047
9048unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009049 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009050 return I != StaticLocalNumbers.end() ? I->second : 1;
9051}
9052
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009053MangleNumberingContext &
9054ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009055 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009056 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009057 if (!MCtx)
9058 MCtx = createMangleNumberingContext();
9059 return *MCtx;
9060}
9061
Justin Lebar20ebffc2016-10-10 16:26:19 +00009062std::unique_ptr<MangleNumberingContext>
9063ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009064 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009065}
9066
David Majnemere7a818f2015-03-06 18:53:55 +00009067const CXXConstructorDecl *
9068ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9069 return ABI->getCopyConstructorForExceptionObject(
9070 cast<CXXRecordDecl>(RD->getFirstDecl()));
9071}
9072
9073void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9074 CXXConstructorDecl *CD) {
9075 return ABI->addCopyConstructorForExceptionObject(
9076 cast<CXXRecordDecl>(RD->getFirstDecl()),
9077 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9078}
9079
David Majnemerdfa6d202015-03-11 18:36:39 +00009080void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
9081 unsigned ParmIdx, Expr *DAE) {
9082 ABI->addDefaultArgExprForConstructor(
9083 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
9084}
9085
9086Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
9087 unsigned ParmIdx) {
9088 return ABI->getDefaultArgExprForConstructor(
9089 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
9090}
9091
David Majnemer00350522015-08-31 18:48:39 +00009092void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9093 TypedefNameDecl *DD) {
9094 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9095}
9096
9097TypedefNameDecl *
9098ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9099 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9100}
9101
9102void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9103 DeclaratorDecl *DD) {
9104 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9105}
9106
9107DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9108 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9109}
9110
Ted Kremenek540017e2011-10-06 05:00:56 +00009111void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9112 ParamIndices[D] = index;
9113}
9114
9115unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9116 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9117 assert(I != ParamIndices.end() &&
9118 "ParmIndices lacks entry set by ParmVarDecl");
9119 return I->second;
9120}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009121
Richard Smithe6c01442013-06-05 00:46:14 +00009122APValue *
9123ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9124 bool MayCreate) {
9125 assert(E && E->getStorageDuration() == SD_Static &&
9126 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009127 if (MayCreate) {
9128 APValue *&MTVI = MaterializedTemporaryValues[E];
9129 if (!MTVI)
9130 MTVI = new (*this) APValue;
9131 return MTVI;
9132 }
Richard Smithe6c01442013-06-05 00:46:14 +00009133
David Majnemer2dcef9e2015-08-13 23:50:15 +00009134 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009135}
9136
Fariborz Jahanian615de762013-05-28 17:37:39 +00009137bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9138 const llvm::Triple &T = getTargetInfo().getTriple();
9139 if (!T.isOSDarwin())
9140 return false;
9141
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009142 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9143 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9144 return false;
9145
Fariborz Jahanian615de762013-05-28 17:37:39 +00009146 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9147 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9148 uint64_t Size = sizeChars.getQuantity();
9149 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9150 unsigned Align = alignChars.getQuantity();
9151 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9152 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9153}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009154
9155namespace {
9156
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009157ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9158 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009159 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009160 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009161 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009162 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009163 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009164}
9165
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009166/// Template specializations to abstract away from pointers and TypeLocs.
9167/// @{
9168template <typename T>
9169ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9170 return ast_type_traits::DynTypedNode::create(*Node);
9171}
9172template <>
9173ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9174 return ast_type_traits::DynTypedNode::create(Node);
9175}
9176template <>
9177ast_type_traits::DynTypedNode
9178createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9179 return ast_type_traits::DynTypedNode::create(Node);
9180}
9181/// @}
9182
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009183 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9184 /// parents as defined by the \c RecursiveASTVisitor.
9185 ///
9186 /// Note that the relationship described here is purely in terms of AST
9187 /// traversal - there are other relationships (for example declaration context)
9188 /// in the AST that are better modeled by special matchers.
9189 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009190 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009191 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009192 public:
9193 /// \brief Builds and returns the translation unit's parent map.
9194 ///
9195 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009196 static std::pair<ASTContext::ParentMapPointers *,
9197 ASTContext::ParentMapOtherNodes *>
9198 buildMap(TranslationUnitDecl &TU) {
9199 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9200 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009201 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009202 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009203 }
9204
9205 private:
9206 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9207
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009208 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9209 ASTContext::ParentMapOtherNodes *OtherParents)
9210 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009211
9212 bool shouldVisitTemplateInstantiations() const {
9213 return true;
9214 }
9215 bool shouldVisitImplicitCode() const {
9216 return true;
9217 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009218
Richard Smith85838722015-11-24 03:09:01 +00009219 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9220 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009221 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009222 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009223 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009224 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009225 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009226 // FIXME: Currently we add the same parent multiple times, but only
9227 // when no memoization data is available for the type.
9228 // For example when we visit all subexpressions of template
9229 // instantiations; this is suboptimal, but benign: the only way to
9230 // visit those is with hasAncestor / hasParent, and those do not create
9231 // new matches.
9232 // The plan is to enable DynTypedNode to be storable in a map or hash
9233 // map. The main problem there is to implement hash functions /
9234 // comparison operators for all types that DynTypedNode supports that
9235 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009236 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009237 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009238 if (const auto *D = ParentStack.back().get<Decl>())
9239 NodeOrVector = D;
9240 else if (const auto *S = ParentStack.back().get<Stmt>())
9241 NodeOrVector = S;
9242 else
9243 NodeOrVector =
9244 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009245 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009246 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9247 auto *Vector = new ASTContext::ParentVector(
9248 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009249 if (auto *Node =
9250 NodeOrVector
9251 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9252 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009253 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009254 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009255
9256 auto *Vector =
9257 NodeOrVector.template get<ASTContext::ParentVector *>();
9258 // Skip duplicates for types that have memoization data.
9259 // We must check that the type has memoization data before calling
9260 // std::find() because DynTypedNode::operator== can't compare all
9261 // types.
9262 bool Found = ParentStack.back().getMemoizationData() &&
9263 std::find(Vector->begin(), Vector->end(),
9264 ParentStack.back()) != Vector->end();
9265 if (!Found)
9266 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009267 }
9268 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009269 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009270 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009271 ParentStack.pop_back();
9272 return Result;
9273 }
9274
9275 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009276 return TraverseNode(DeclNode, DeclNode,
9277 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009278 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009279 }
9280
9281 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009282 return TraverseNode(StmtNode, StmtNode,
9283 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009284 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009285 }
9286
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009287 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009288 return TraverseNode(
9289 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9290 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9291 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009292 }
9293
9294 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9295 return TraverseNode(
9296 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009297 [&] {
9298 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9299 },
9300 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009301 }
9302
9303 ASTContext::ParentMapPointers *Parents;
9304 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009305 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9306
9307 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9308 };
9309
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009310} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009311
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009312template <typename NodeTy, typename MapTy>
9313static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9314 const MapTy &Map) {
9315 auto I = Map.find(Node);
9316 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009317 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009318 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009319 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009320 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009321 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009322 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009323}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009324
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009325ASTContext::DynTypedNodeList
9326ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9327 if (!PointerParents) {
9328 // We always need to run over the whole translation unit, as
9329 // hasAncestor can escape any subtree.
9330 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9331 PointerParents.reset(Maps.first);
9332 OtherParents.reset(Maps.second);
9333 }
9334 if (Node.getNodeKind().hasPointerIdentity())
9335 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9336 return getDynNodeFromMap(Node, *OtherParents);
9337}
9338
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009339bool
9340ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9341 const ObjCMethodDecl *MethodImpl) {
9342 // No point trying to match an unavailable/deprecated mothod.
9343 if (MethodDecl->hasAttr<UnavailableAttr>()
9344 || MethodDecl->hasAttr<DeprecatedAttr>())
9345 return false;
9346 if (MethodDecl->getObjCDeclQualifier() !=
9347 MethodImpl->getObjCDeclQualifier())
9348 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009349 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009350 return false;
9351
9352 if (MethodDecl->param_size() != MethodImpl->param_size())
9353 return false;
9354
9355 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9356 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9357 EF = MethodDecl->param_end();
9358 IM != EM && IF != EF; ++IM, ++IF) {
9359 const ParmVarDecl *DeclVar = (*IF);
9360 const ParmVarDecl *ImplVar = (*IM);
9361 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9362 return false;
9363 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9364 return false;
9365 }
9366 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9367
9368}
Richard Smith053f6c62014-05-16 23:01:30 +00009369
9370// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9371// doesn't include ASTContext.h
9372template
9373clang::LazyGenerationalUpdatePtr<
9374 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9375clang::LazyGenerationalUpdatePtr<
9376 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9377 const clang::ASTContext &Ctx, Decl *Value);