blob: 425aeac3c046c68bdf04924cdb2533a03df74e49 [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");
656 LLVM_CONSTEXPR Expr *const CanonRequiresClause = nullptr;
657
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();
797
Reid Kleckner588c9372014-02-19 23:44:52 +0000798 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000799}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000800
Manuel Klimek95403e62014-05-21 13:28:59 +0000801void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000802 if (!PointerParents) return;
803 for (const auto &Entry : *PointerParents) {
804 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
805 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
806 } else if (Entry.second.is<ParentVector *>()) {
807 delete Entry.second.get<ParentVector *>();
808 }
809 }
810 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000811 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
812 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000813 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000814 delete Entry.second.get<ParentVector *>();
815 }
816 }
817}
818
Douglas Gregor1a809332010-05-23 18:26:36 +0000819void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000820 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000821}
822
Mike Stump11289f42009-09-09 15:08:12 +0000823void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000824ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000825 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000826}
827
Chris Lattner4eb445d2007-01-26 01:27:23 +0000828void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000829 llvm::errs() << "\n*** AST Context Stats:\n";
830 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000831
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000833#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000834#define ABSTRACT_TYPE(Name, Parent)
835#include "clang/AST/TypeNodes.def"
836 0 // Extra
837 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000838
Chris Lattner4eb445d2007-01-26 01:27:23 +0000839 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
840 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000841 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000842 }
843
Douglas Gregora30d0462009-05-26 14:40:08 +0000844 unsigned Idx = 0;
845 unsigned TotalBytes = 0;
846#define TYPE(Name, Parent) \
847 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000848 llvm::errs() << " " << counts[Idx] << " " << #Name \
849 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000850 TotalBytes += counts[Idx] * sizeof(Name##Type); \
851 ++Idx;
852#define ABSTRACT_TYPE(Name, Parent)
853#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000854
Chandler Carruth3c147a72011-07-04 05:32:14 +0000855 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
856
Douglas Gregor7454c562010-07-02 20:37:36 +0000857 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000858 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
859 << NumImplicitDefaultConstructors
860 << " implicit default constructors created\n";
861 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
862 << NumImplicitCopyConstructors
863 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000864 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000865 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
866 << NumImplicitMoveConstructors
867 << " implicit move constructors created\n";
868 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
869 << NumImplicitCopyAssignmentOperators
870 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000871 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000872 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
873 << NumImplicitMoveAssignmentOperators
874 << " implicit move assignment operators created\n";
875 llvm::errs() << NumImplicitDestructorsDeclared << "/"
876 << NumImplicitDestructors
877 << " implicit destructors created\n";
878
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000879 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000880 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000881 ExternalSource->PrintStats();
882 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000883
Douglas Gregor5b11d492010-07-25 17:53:33 +0000884 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000885}
886
Richard Smith42413142015-05-15 20:05:43 +0000887void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
888 bool NotifyListeners) {
889 if (NotifyListeners)
890 if (auto *Listener = getASTMutationListener())
891 Listener->RedefinedHiddenDefinition(ND, M);
892
893 if (getLangOpts().ModulesLocalVisibility)
894 MergedDefModules[ND].push_back(M);
895 else
896 ND->setHidden(false);
897}
898
899void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
900 auto It = MergedDefModules.find(ND);
901 if (It == MergedDefModules.end())
902 return;
903
904 auto &Merged = It->second;
905 llvm::DenseSet<Module*> Found;
906 for (Module *&M : Merged)
907 if (!Found.insert(M).second)
908 M = nullptr;
909 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
910}
911
Richard Smithdc1f0422016-07-20 19:10:16 +0000912void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
913 if (LazyInitializers.empty())
914 return;
915
916 auto *Source = Ctx.getExternalSource();
917 assert(Source && "lazy initializers but no external source");
918
919 auto LazyInits = std::move(LazyInitializers);
920 LazyInitializers.clear();
921
922 for (auto ID : LazyInits)
923 Initializers.push_back(Source->GetExternalDecl(ID));
924
925 assert(LazyInitializers.empty() &&
926 "GetExternalDecl for lazy module initializer added more inits");
927}
928
929void ASTContext::addModuleInitializer(Module *M, Decl *D) {
930 // One special case: if we add a module initializer that imports another
931 // module, and that module's only initializer is an ImportDecl, simplify.
932 if (auto *ID = dyn_cast<ImportDecl>(D)) {
933 auto It = ModuleInitializers.find(ID->getImportedModule());
934
935 // Maybe the ImportDecl does nothing at all. (Common case.)
936 if (It == ModuleInitializers.end())
937 return;
938
939 // Maybe the ImportDecl only imports another ImportDecl.
940 auto &Imported = *It->second;
941 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
942 Imported.resolve(*this);
943 auto *OnlyDecl = Imported.Initializers.front();
944 if (isa<ImportDecl>(OnlyDecl))
945 D = OnlyDecl;
946 }
947 }
948
949 auto *&Inits = ModuleInitializers[M];
950 if (!Inits)
951 Inits = new (*this) PerModuleInitializers;
952 Inits->Initializers.push_back(D);
953}
954
955void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
956 auto *&Inits = ModuleInitializers[M];
957 if (!Inits)
958 Inits = new (*this) PerModuleInitializers;
959 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
960 IDs.begin(), IDs.end());
961}
962
963ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
964 auto It = ModuleInitializers.find(M);
965 if (It == ModuleInitializers.end())
966 return None;
967
968 auto *Inits = It->second;
969 Inits->resolve(*this);
970 return Inits->Initializers;
971}
972
Richard Smithf19e1272015-03-07 00:04:49 +0000973ExternCContextDecl *ASTContext::getExternCContextDecl() const {
974 if (!ExternCContext)
975 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
976
977 return ExternCContext;
978}
979
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000980BuiltinTemplateDecl *
981ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
982 const IdentifierInfo *II) const {
983 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
984 BuiltinTemplate->setImplicit();
985 TUDecl->addDecl(BuiltinTemplate);
986
987 return BuiltinTemplate;
988}
989
990BuiltinTemplateDecl *
991ASTContext::getMakeIntegerSeqDecl() const {
992 if (!MakeIntegerSeqDecl)
993 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
994 getMakeIntegerSeqName());
995 return MakeIntegerSeqDecl;
996}
997
Eric Fiselier6ad68552016-07-01 01:24:09 +0000998BuiltinTemplateDecl *
999ASTContext::getTypePackElementDecl() const {
1000 if (!TypePackElementDecl)
1001 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1002 getTypePackElementName());
1003 return TypePackElementDecl;
1004}
1005
Alp Toker2dea15b2013-12-17 01:22:38 +00001006RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1007 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001008 SourceLocation Loc;
1009 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001010 if (getLangOpts().CPlusPlus)
1011 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1012 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001013 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001014 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1015 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001016 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001017 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1018 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001019 return NewDecl;
1020}
1021
1022TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1023 StringRef Name) const {
1024 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1025 TypedefDecl *NewDecl = TypedefDecl::Create(
1026 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1027 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1028 NewDecl->setImplicit();
1029 return NewDecl;
1030}
1031
Douglas Gregor801c99d2011-08-12 06:49:56 +00001032TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001033 if (!Int128Decl)
1034 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001035 return Int128Decl;
1036}
1037
1038TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001039 if (!UInt128Decl)
1040 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001041 return UInt128Decl;
1042}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001043
John McCall48f2d582009-10-23 23:03:21 +00001044void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001045 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001046 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001047 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001048}
1049
Artem Belevichb5bc9232015-09-22 17:23:22 +00001050void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1051 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001052 assert((!this->Target || this->Target == &Target) &&
1053 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001054 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001055
Douglas Gregore8bbc122011-09-02 00:18:52 +00001056 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001057 this->AuxTarget = AuxTarget;
1058
Douglas Gregore8bbc122011-09-02 00:18:52 +00001059 ABI.reset(createCXXABI(Target));
1060 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001061 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001062
Chris Lattner970e54e2006-11-12 00:37:36 +00001063 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001064 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Chris Lattner970e54e2006-11-12 00:37:36 +00001066 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001067 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001068 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001069 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001070 InitBuiltinType(CharTy, BuiltinType::Char_S);
1071 else
1072 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001073 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001074 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1075 InitBuiltinType(ShortTy, BuiltinType::Short);
1076 InitBuiltinType(IntTy, BuiltinType::Int);
1077 InitBuiltinType(LongTy, BuiltinType::Long);
1078 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattner970e54e2006-11-12 00:37:36 +00001080 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001081 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1082 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1083 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1084 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1085 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Chris Lattner970e54e2006-11-12 00:37:36 +00001087 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001088 InitBuiltinType(FloatTy, BuiltinType::Float);
1089 InitBuiltinType(DoubleTy, BuiltinType::Double);
1090 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001091
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001092 // GNU extension, __float128 for IEEE quadruple precision
1093 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1094
Chris Lattnerf122cef2009-04-30 02:43:43 +00001095 // GNU extension, 128-bit integers.
1096 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1097 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1098
Hans Wennborg0d81e012013-05-10 10:08:40 +00001099 // C++ 3.9.1p5
1100 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1101 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1102 else // -fshort-wchar makes wchar_t be unsigned.
1103 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1104 if (LangOpts.CPlusPlus && LangOpts.WChar)
1105 WideCharTy = WCharTy;
1106 else {
1107 // C99 (or C++ using -fno-wchar).
1108 WideCharTy = getFromTargetType(Target.getWCharType());
1109 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001110
James Molloy36365542012-05-04 10:55:22 +00001111 WIntTy = getFromTargetType(Target.getWIntType());
1112
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001113 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1114 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1115 else // C99
1116 Char16Ty = getFromTargetType(Target.getChar16Type());
1117
1118 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1119 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1120 else // C99
1121 Char32Ty = getFromTargetType(Target.getChar32Type());
1122
Douglas Gregor4619e432008-12-05 23:32:09 +00001123 // Placeholder type for type-dependent expressions whose type is
1124 // completely unknown. No code should ever check a type against
1125 // DependentTy and users should never see it; however, it is here to
1126 // help diagnose failures to properly check for type-dependent
1127 // expressions.
1128 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129
John McCall36e7fe32010-10-12 00:20:44 +00001130 // Placeholder type for functions.
1131 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1132
John McCall0009fcc2011-04-26 20:42:42 +00001133 // Placeholder type for bound members.
1134 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1135
John McCall526ab472011-10-25 17:37:35 +00001136 // Placeholder type for pseudo-objects.
1137 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1138
John McCall31996342011-04-07 08:22:57 +00001139 // "any" type; useful for debugger-like clients.
1140 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1141
John McCall8a6b59a2011-10-17 18:09:15 +00001142 // Placeholder type for unbridged ARC casts.
1143 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1144
Eli Friedman34866c72012-08-31 00:14:07 +00001145 // Placeholder type for builtin functions.
1146 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1147
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001148 // Placeholder type for OMP array sections.
1149 if (LangOpts.OpenMP)
1150 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1151
Chris Lattner970e54e2006-11-12 00:37:36 +00001152 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001153 FloatComplexTy = getComplexType(FloatTy);
1154 DoubleComplexTy = getComplexType(DoubleTy);
1155 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001156 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001157
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001158 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001159 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1160 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001161 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001162
Alexey Bader954ba212016-04-08 13:40:33 +00001163 if (LangOpts.OpenCL) {
1164#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1165 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001166#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001167
Guy Benyei61054192013-02-07 10:55:47 +00001168 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001169 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001170 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1171 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1172 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1173 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001174 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001175
1176 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001177 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1178 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001179
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001180 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001181
1182 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001183
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001184 // void * type
1185 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001186
1187 // nullptr type (C++0x 2.14.7)
1188 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001189
1190 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1191 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001192
1193 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001194 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001195}
1196
David Blaikie9c902b52011-09-25 23:23:43 +00001197DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001198 return SourceMgr.getDiagnostics();
1199}
1200
Douglas Gregor561eceb2010-08-30 16:49:28 +00001201AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1202 AttrVec *&Result = DeclAttrs[D];
1203 if (!Result) {
1204 void *Mem = Allocate(sizeof(AttrVec));
1205 Result = new (Mem) AttrVec;
1206 }
1207
1208 return *Result;
1209}
1210
1211/// \brief Erase the attributes corresponding to the given declaration.
1212void ASTContext::eraseDeclAttrs(const Decl *D) {
1213 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1214 if (Pos != DeclAttrs.end()) {
1215 Pos->second->~AttrVec();
1216 DeclAttrs.erase(Pos);
1217 }
1218}
1219
Larisse Voufo39a1e502013-08-06 01:03:05 +00001220// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001221MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001222ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001223 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001224 return getTemplateOrSpecializationInfo(Var)
1225 .dyn_cast<MemberSpecializationInfo *>();
1226}
1227
1228ASTContext::TemplateOrSpecializationInfo
1229ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1230 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1231 TemplateOrInstantiation.find(Var);
1232 if (Pos == TemplateOrInstantiation.end())
1233 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001235 return Pos->second;
1236}
1237
Mike Stump11289f42009-09-09 15:08:12 +00001238void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001239ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001240 TemplateSpecializationKind TSK,
1241 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001242 assert(Inst->isStaticDataMember() && "Not a static data member");
1243 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001244 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1245 Tmpl, TSK, PointOfInstantiation));
1246}
1247
1248void
1249ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1250 TemplateOrSpecializationInfo TSI) {
1251 assert(!TemplateOrInstantiation[Inst] &&
1252 "Already noted what the variable was instantiated from");
1253 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001254}
1255
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001256FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1257 const FunctionDecl *FD){
1258 assert(FD && "Specialization is 0");
1259 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001260 = ClassScopeSpecializationPattern.find(FD);
1261 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001262 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001263
1264 return Pos->second;
1265}
1266
1267void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1268 FunctionDecl *Pattern) {
1269 assert(FD && "Specialization is 0");
1270 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001271 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001272}
1273
John McCalle61f2ba2009-11-18 02:36:19 +00001274NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001275ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001276 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001277 = InstantiatedFromUsingDecl.find(UUD);
1278 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001279 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001280
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001281 return Pos->second;
1282}
1283
1284void
John McCallb96ec562009-12-04 22:46:56 +00001285ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1286 assert((isa<UsingDecl>(Pattern) ||
1287 isa<UnresolvedUsingValueDecl>(Pattern) ||
1288 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1289 "pattern decl is not a using decl");
1290 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1291 InstantiatedFromUsingDecl[Inst] = Pattern;
1292}
1293
1294UsingShadowDecl *
1295ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1296 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1297 = InstantiatedFromUsingShadowDecl.find(Inst);
1298 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001299 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001300
1301 return Pos->second;
1302}
1303
1304void
1305ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1306 UsingShadowDecl *Pattern) {
1307 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1308 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001309}
1310
Anders Carlsson5da84842009-09-01 04:26:58 +00001311FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1312 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1313 = InstantiatedFromUnnamedFieldDecl.find(Field);
1314 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001315 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Anders Carlsson5da84842009-09-01 04:26:58 +00001317 return Pos->second;
1318}
1319
1320void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1321 FieldDecl *Tmpl) {
1322 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1323 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1324 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1325 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001326
Anders Carlsson5da84842009-09-01 04:26:58 +00001327 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1328}
1329
Douglas Gregor832940b2010-03-02 23:58:15 +00001330ASTContext::overridden_cxx_method_iterator
1331ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001332 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1333 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001334 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001335 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001336 return Pos->second.begin();
1337}
1338
1339ASTContext::overridden_cxx_method_iterator
1340ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001341 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1342 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001343 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001344 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001345 return Pos->second.end();
1346}
1347
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001348unsigned
1349ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001350 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1351 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001352 if (Pos == OverriddenMethods.end())
1353 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001354 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001355}
1356
Clement Courbet6ecaec82016-07-05 07:49:31 +00001357ASTContext::overridden_method_range
1358ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1359 return overridden_method_range(overridden_methods_begin(Method),
1360 overridden_methods_end(Method));
1361}
1362
Douglas Gregor832940b2010-03-02 23:58:15 +00001363void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1364 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001365 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001366 OverriddenMethods[Method].push_back(Overridden);
1367}
1368
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001369void ASTContext::getOverriddenMethods(
1370 const NamedDecl *D,
1371 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001372 assert(D);
1373
1374 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001375 Overridden.append(overridden_methods_begin(CXXMethod),
1376 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001377 return;
1378 }
1379
1380 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1381 if (!Method)
1382 return;
1383
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001384 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1385 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001386 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001387}
1388
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001389void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1390 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1391 assert(!Import->isFromASTFile() && "Non-local import declaration");
1392 if (!FirstLocalImport) {
1393 FirstLocalImport = Import;
1394 LastLocalImport = Import;
1395 return;
1396 }
1397
1398 LastLocalImport->NextLocalImport = Import;
1399 LastLocalImport = Import;
1400}
1401
Chris Lattner53cfe802007-07-18 17:52:12 +00001402//===----------------------------------------------------------------------===//
1403// Type Sizing and Analysis
1404//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001405
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001406/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1407/// scalar floating point type.
1408const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001409 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001410 assert(BT && "Not a floating point type!");
1411 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001412 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001413 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001414 case BuiltinType::Float: return Target->getFloatFormat();
1415 case BuiltinType::Double: return Target->getDoubleFormat();
1416 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001417 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001418 }
1419}
1420
Rafael Espindola71eccb32013-08-08 19:53:46 +00001421CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001422 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001423
John McCall94268702010-10-08 18:24:19 +00001424 bool UseAlignAttrOnly = false;
1425 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1426 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001427
John McCall94268702010-10-08 18:24:19 +00001428 // __attribute__((aligned)) can increase or decrease alignment
1429 // *except* on a struct or struct member, where it only increases
1430 // alignment unless 'packed' is also specified.
1431 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001432 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001433 // ignore that possibility; Sema should diagnose it.
1434 if (isa<FieldDecl>(D)) {
1435 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1436 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1437 } else {
1438 UseAlignAttrOnly = true;
1439 }
1440 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001441 else if (isa<FieldDecl>(D))
1442 UseAlignAttrOnly =
1443 D->hasAttr<PackedAttr>() ||
1444 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001445
John McCall4e819612011-01-20 07:57:12 +00001446 // If we're using the align attribute only, just ignore everything
1447 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001448 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001449 // do nothing
1450
John McCall94268702010-10-08 18:24:19 +00001451 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001452 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001453 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001454 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001455 T = RT->getPointeeType();
1456 else
1457 T = getPointerType(RT->getPointeeType());
1458 }
Richard Smithf6d70302014-06-10 23:34:28 +00001459 QualType BaseT = getBaseElementType(T);
1460 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001461 // Adjust alignments of declarations with array type by the
1462 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001463 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001464 unsigned MinWidth = Target->getLargeArrayMinWidth();
1465 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001466 if (isa<VariableArrayType>(arrayType))
1467 Align = std::max(Align, Target->getLargeArrayAlign());
1468 else if (isa<ConstantArrayType>(arrayType) &&
1469 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1470 Align = std::max(Align, Target->getLargeArrayAlign());
1471 }
John McCall33ddac02011-01-19 10:06:00 +00001472 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001473 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001474 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001475 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001476 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1477 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001478 }
John McCall4e819612011-01-20 07:57:12 +00001479
1480 // Fields can be subject to extra alignment constraints, like if
1481 // the field is packed, the struct is packed, or the struct has a
1482 // a max-field-alignment constraint (#pragma pack). So calculate
1483 // the actual alignment of the field within the struct, and then
1484 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001485 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1486 const RecordDecl *Parent = Field->getParent();
1487 // We can only produce a sensible answer if the record is valid.
1488 if (!Parent->isInvalidDecl()) {
1489 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001490
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001491 // Start with the record's overall alignment.
1492 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001493
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001494 // Use the GCD of that and the offset within the record.
1495 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1496 if (Offset > 0) {
1497 // Alignment is always a power of 2, so the GCD will be a power of 2,
1498 // which means we get to do this crazy thing instead of Euclid's.
1499 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1500 if (LowBitOfOffset < FieldAlign)
1501 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1502 }
1503
1504 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001505 }
Charles Davis3fc51072010-02-23 04:52:00 +00001506 }
Chris Lattner68061312009-01-24 21:53:27 +00001507 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001508
Ken Dyckcc56c542011-01-15 18:38:59 +00001509 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001510}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001511
John McCallf1249922012-08-21 04:10:00 +00001512// getTypeInfoDataSizeInChars - Return the size of a type, in
1513// chars. If the type is a record, its data size is returned. This is
1514// the size of the memcpy that's performed when assigning this type
1515// using a trivial copy/move assignment operator.
1516std::pair<CharUnits, CharUnits>
1517ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1518 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1519
1520 // In C++, objects can sometimes be allocated into the tail padding
1521 // of a base-class subobject. We decide whether that's possible
1522 // during class layout, so here we can just trust the layout results.
1523 if (getLangOpts().CPlusPlus) {
1524 if (const RecordType *RT = T->getAs<RecordType>()) {
1525 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1526 sizeAndAlign.first = layout.getDataSize();
1527 }
1528 }
1529
1530 return sizeAndAlign;
1531}
1532
Richard Trieu04d2d942013-05-14 21:59:17 +00001533/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1534/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1535std::pair<CharUnits, CharUnits>
1536static getConstantArrayInfoInChars(const ASTContext &Context,
1537 const ConstantArrayType *CAT) {
1538 std::pair<CharUnits, CharUnits> EltInfo =
1539 Context.getTypeInfoInChars(CAT->getElementType());
1540 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001541 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1542 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001543 "Overflow in array type char size evaluation");
1544 uint64_t Width = EltInfo.first.getQuantity() * Size;
1545 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001546 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1547 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001548 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001549 return std::make_pair(CharUnits::fromQuantity(Width),
1550 CharUnits::fromQuantity(Align));
1551}
1552
John McCall87fe5d52010-05-20 01:18:31 +00001553std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001554ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001555 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1556 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001557 TypeInfo Info = getTypeInfo(T);
1558 return std::make_pair(toCharUnitsFromBits(Info.Width),
1559 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001560}
1561
1562std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001563ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001564 return getTypeInfoInChars(T.getTypePtr());
1565}
1566
David Majnemer34b57492014-07-30 01:30:47 +00001567bool ASTContext::isAlignmentRequired(const Type *T) const {
1568 return getTypeInfo(T).AlignIsRequired;
1569}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001570
David Majnemer34b57492014-07-30 01:30:47 +00001571bool ASTContext::isAlignmentRequired(QualType T) const {
1572 return isAlignmentRequired(T.getTypePtr());
1573}
1574
1575TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001576 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1577 if (I != MemoizedTypeInfo.end())
1578 return I->second;
1579
1580 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1581 TypeInfo TI = getTypeInfoImpl(T);
1582 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001583 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001584}
1585
1586/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1587/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001588///
1589/// FIXME: Pointers into different addr spaces could have different sizes and
1590/// alignment requirements: getPointerInfo should take an AddrSpace, this
1591/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001592TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1593 uint64_t Width = 0;
1594 unsigned Align = 8;
1595 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001596 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001597#define TYPE(Class, Base)
1598#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001599#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001600#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001601#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1602 case Type::Class: \
1603 assert(!T->isDependentType() && "should not see dependent types here"); \
1604 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001605#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001606 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001607
Chris Lattner355332d2007-07-13 22:27:08 +00001608 case Type::FunctionNoProto:
1609 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001610 // GCC extension: alignof(function) = 32 bits
1611 Width = 0;
1612 Align = 32;
1613 break;
1614
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001615 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001616 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001617 Width = 0;
1618 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1619 break;
1620
Steve Naroff5c131802007-08-30 01:06:46 +00001621 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001622 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001623
David Majnemer34b57492014-07-30 01:30:47 +00001624 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001625 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001626 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001627 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001628 Width = EltInfo.Width * Size;
1629 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001630 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1631 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001632 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001633 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001634 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001635 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001636 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001637 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001638 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1639 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001640 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001641 // If the alignment is not a power of 2, round up to the next power of 2.
1642 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001643 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001644 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001645 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001646 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001647 // Adjust the alignment based on the target max.
1648 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1649 if (TargetVectorAlign && TargetVectorAlign < Align)
1650 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001651 break;
1652 }
Chris Lattner647fb222007-07-18 18:26:58 +00001653
Chris Lattner7570e9c2008-03-08 08:52:55 +00001654 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001655 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001656 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001657 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001658 // GCC extension: alignof(void) = 8 bits.
1659 Width = 0;
1660 Align = 8;
1661 break;
1662
Chris Lattner6a4f7452007-12-19 19:23:28 +00001663 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001664 Width = Target->getBoolWidth();
1665 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001666 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001667 case BuiltinType::Char_S:
1668 case BuiltinType::Char_U:
1669 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001670 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001671 Width = Target->getCharWidth();
1672 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001673 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001674 case BuiltinType::WChar_S:
1675 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001676 Width = Target->getWCharWidth();
1677 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001678 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001679 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001680 Width = Target->getChar16Width();
1681 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001682 break;
1683 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001684 Width = Target->getChar32Width();
1685 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001686 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001687 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001688 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001689 Width = Target->getShortWidth();
1690 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001691 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001692 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001693 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001694 Width = Target->getIntWidth();
1695 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001696 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001697 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001698 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001699 Width = Target->getLongWidth();
1700 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001701 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001702 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001703 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001704 Width = Target->getLongLongWidth();
1705 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001706 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001707 case BuiltinType::Int128:
1708 case BuiltinType::UInt128:
1709 Width = 128;
1710 Align = 128; // int128_t is 128-bit aligned on all targets.
1711 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001712 case BuiltinType::Half:
1713 Width = Target->getHalfWidth();
1714 Align = Target->getHalfAlign();
1715 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001716 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001717 Width = Target->getFloatWidth();
1718 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001719 break;
1720 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001721 Width = Target->getDoubleWidth();
1722 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001723 break;
1724 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001725 Width = Target->getLongDoubleWidth();
1726 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001727 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001728 case BuiltinType::Float128:
1729 Width = Target->getFloat128Width();
1730 Align = Target->getFloat128Align();
1731 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001732 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001733 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1734 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001735 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001736 case BuiltinType::ObjCId:
1737 case BuiltinType::ObjCClass:
1738 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001739 Width = Target->getPointerWidth(0);
1740 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001741 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001742 case BuiltinType::OCLSampler: {
1743 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1744 Width = Target->getPointerWidth(AS);
1745 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001746 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001747 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001748 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001749 case BuiltinType::OCLClkEvent:
1750 case BuiltinType::OCLQueue:
1751 case BuiltinType::OCLNDRange:
1752 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001753 // Currently these types are pointers to opaque types.
1754 Width = Target->getPointerWidth(0);
1755 Align = Target->getPointerAlign(0);
1756 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001757#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1758 case BuiltinType::Id:
1759#include "clang/Basic/OpenCLImageTypes.def"
1760 {
1761 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1762 Width = Target->getPointerWidth(AS);
1763 Align = Target->getPointerAlign(AS);
1764 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001765 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001766 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001767 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001768 Width = Target->getPointerWidth(0);
1769 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001770 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001771 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001772 unsigned AS = getTargetAddressSpace(
1773 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001774 Width = Target->getPointerWidth(AS);
1775 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001776 break;
1777 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001778 case Type::LValueReference:
1779 case Type::RValueReference: {
1780 // alignof and sizeof should never enter this code path here, so we go
1781 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001782 unsigned AS = getTargetAddressSpace(
1783 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001784 Width = Target->getPointerWidth(AS);
1785 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001786 break;
1787 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001788 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001789 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001790 Width = Target->getPointerWidth(AS);
1791 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001792 break;
1793 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001794 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001795 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001796 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001797 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001798 }
Chris Lattner647fb222007-07-18 18:26:58 +00001799 case Type::Complex: {
1800 // Complex types have the same alignment as their elements, but twice the
1801 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001802 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1803 Width = EltInfo.Width * 2;
1804 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001805 break;
1806 }
John McCall8b07ec22010-05-15 11:32:37 +00001807 case Type::ObjCObject:
1808 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001809 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001810 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001811 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001812 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001813 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001814 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001815 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001816 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001817 break;
1818 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001819 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001820 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001821 const TagType *TT = cast<TagType>(T);
1822
1823 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001824 Width = 8;
1825 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001826 break;
1827 }
Mike Stump11289f42009-09-09 15:08:12 +00001828
David Majnemer475b25e2015-01-21 10:54:38 +00001829 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1830 const EnumDecl *ED = ET->getDecl();
1831 TypeInfo Info =
1832 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1833 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1834 Info.Align = AttrAlign;
1835 Info.AlignIsRequired = true;
1836 }
1837 return Info;
1838 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001839
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001840 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001841 const RecordDecl *RD = RT->getDecl();
1842 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001843 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001844 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001845 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001846 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001847 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001848
Chris Lattner63d2b362009-10-22 05:17:15 +00001849 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001850 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1851 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001852
Richard Smith30482bc2011-02-20 03:19:35 +00001853 case Type::Auto: {
1854 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001855 assert(!A->getDeducedType().isNull() &&
1856 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001857 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001858 }
1859
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001860 case Type::Paren:
1861 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1862
Douglas Gregoref462e62009-04-30 17:32:17 +00001863 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001864 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001865 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001866 // If the typedef has an aligned attribute on it, it overrides any computed
1867 // alignment we have. This violates the GCC documentation (which says that
1868 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001869 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001870 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001871 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001872 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001873 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001874 AlignIsRequired = Info.AlignIsRequired;
1875 }
David Majnemer34b57492014-07-30 01:30:47 +00001876 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001877 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001878 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001879
Abramo Bagnara6150c882010-05-11 21:36:43 +00001880 case Type::Elaborated:
1881 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001882
John McCall81904512011-01-06 01:58:22 +00001883 case Type::Attributed:
1884 return getTypeInfo(
1885 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1886
Eli Friedman0dfb8892011-10-06 23:00:33 +00001887 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001888 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001889 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1890 Width = Info.Width;
1891 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001892
1893 // If the size of the type doesn't exceed the platform's max
1894 // atomic promotion width, make the size and alignment more
1895 // favorable to atomic operations:
1896 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1897 // Round the size up to a power of 2.
1898 if (!llvm::isPowerOf2_64(Width))
1899 Width = llvm::NextPowerOf2(Width);
1900
1901 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001902 Align = static_cast<unsigned>(Width);
1903 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001904 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001905 break;
1906
1907 case Type::Pipe: {
1908 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1909 Width = Info.Width;
1910 Align = Info.Align;
1911 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001912
Douglas Gregoref462e62009-04-30 17:32:17 +00001913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001915 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001916 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001917}
1918
Alexey Bataev00396512015-07-02 03:40:19 +00001919unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1920 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1921 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1922 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1923 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1924 getTargetInfo().getABI() == "elfv1-qpx" &&
1925 T->isSpecificBuiltinType(BuiltinType::Double))
1926 SimdAlign = 256;
1927 return SimdAlign;
1928}
1929
Ken Dyckcc56c542011-01-15 18:38:59 +00001930/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1931CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1932 return CharUnits::fromQuantity(BitSize / getCharWidth());
1933}
1934
Ken Dyckb0fcc592011-02-11 01:54:29 +00001935/// toBits - Convert a size in characters to a size in characters.
1936int64_t ASTContext::toBits(CharUnits CharSize) const {
1937 return CharSize.getQuantity() * getCharWidth();
1938}
1939
Ken Dyck8c89d592009-12-22 14:23:30 +00001940/// getTypeSizeInChars - Return the size of the specified type, in characters.
1941/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001942CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001943 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001944}
Jay Foad39c79802011-01-12 09:06:06 +00001945CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001946 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001947}
1948
Ken Dycka6046ab2010-01-26 17:25:18 +00001949/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001950/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001951CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001952 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001953}
Jay Foad39c79802011-01-12 09:06:06 +00001954CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001955 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001956}
1957
Chris Lattnera3402cd2009-01-27 18:08:34 +00001958/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1959/// type for the current target in bits. This can be different than the ABI
1960/// alignment in cases where it is beneficial for performance to overalign
1961/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001962unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001963 TypeInfo TI = getTypeInfo(T);
1964 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001965
David Majnemere1544562015-04-24 01:25:05 +00001966 T = T->getBaseElementTypeUnsafe();
1967
1968 // The preferred alignment of member pointers is that of a pointer.
1969 if (T->isMemberPointerType())
1970 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1971
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001972 if (!Target->allowsLargerPreferedTypeAlignment())
1973 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001974
Eli Friedman7ab09572009-05-25 21:27:19 +00001975 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001976 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001977 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001978 if (const EnumType *ET = T->getAs<EnumType>())
1979 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001980 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001981 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1982 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001983 // Don't increase the alignment if an alignment attribute was specified on a
1984 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001985 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001986 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001987
Chris Lattnera3402cd2009-01-27 18:08:34 +00001988 return ABIAlign;
1989}
1990
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001991/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1992/// for __attribute__((aligned)) on this target, to be used if no alignment
1993/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001994unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001995 return getTargetInfo().getDefaultAlignForAttributeAligned();
1996}
1997
Ulrich Weigandfa806422013-05-06 16:23:57 +00001998/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1999/// to a global variable of the specified type.
2000unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2001 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2002}
2003
2004/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2005/// should be given to a global variable of the specified type.
2006CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2007 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2008}
2009
David Majnemer08ef2ba2015-06-23 20:34:18 +00002010CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2011 CharUnits Offset = CharUnits::Zero();
2012 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2013 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2014 Offset += Layout->getBaseClassOffset(Base);
2015 Layout = &getASTRecordLayout(Base);
2016 }
2017 return Offset;
2018}
2019
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002020/// DeepCollectObjCIvars -
2021/// This routine first collects all declared, but not synthesized, ivars in
2022/// super class and then collects all ivars, including those synthesized for
2023/// current class. This routine is used for implementation of current class
2024/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002025///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002026void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2027 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002028 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002029 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2030 DeepCollectObjCIvars(SuperClass, false, Ivars);
2031 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002032 for (const auto *I : OI->ivars())
2033 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002034 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002035 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002036 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002037 Iv= Iv->getNextIvar())
2038 Ivars.push_back(Iv);
2039 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002040}
2041
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002042/// CollectInheritedProtocols - Collect all protocols in current class and
2043/// those inherited by it.
2044void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002045 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002046 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002047 // We can use protocol_iterator here instead of
2048 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002049 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002050 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002051 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002052
2053 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002054 for (const auto *Cat : OI->visible_categories())
2055 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002056
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002057 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2058 while (SD) {
2059 CollectInheritedProtocols(SD, Protocols);
2060 SD = SD->getSuperClass();
2061 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002062 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002063 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002064 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002065 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002066 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002067 // Insert the protocol.
2068 if (!Protocols.insert(
2069 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2070 return;
2071
2072 for (auto *Proto : OP->protocols())
2073 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002074 }
2075}
2076
Jay Foad39c79802011-01-12 09:06:06 +00002077unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002078 unsigned count = 0;
2079 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002080 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002081 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002082
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002083 // Count ivar defined in this class's implementation. This
2084 // includes synthesized ivars.
2085 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002086 count += ImplDecl->ivar_size();
2087
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002088 return count;
2089}
2090
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002091bool ASTContext::isSentinelNullExpr(const Expr *E) {
2092 if (!E)
2093 return false;
2094
2095 // nullptr_t is always treated as null.
2096 if (E->getType()->isNullPtrType()) return true;
2097
2098 if (E->getType()->isAnyPointerType() &&
2099 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2100 Expr::NPC_ValueDependentIsNull))
2101 return true;
2102
2103 // Unfortunately, __null has type 'int'.
2104 if (isa<GNUNullExpr>(E)) return true;
2105
2106 return false;
2107}
2108
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002109/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2110ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2111 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2112 I = ObjCImpls.find(D);
2113 if (I != ObjCImpls.end())
2114 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002115 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002116}
2117/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2118ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2119 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2120 I = ObjCImpls.find(D);
2121 if (I != ObjCImpls.end())
2122 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002123 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002124}
2125
2126/// \brief Set the implementation of ObjCInterfaceDecl.
2127void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2128 ObjCImplementationDecl *ImplD) {
2129 assert(IFaceD && ImplD && "Passed null params");
2130 ObjCImpls[IFaceD] = ImplD;
2131}
2132/// \brief Set the implementation of ObjCCategoryDecl.
2133void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2134 ObjCCategoryImplDecl *ImplD) {
2135 assert(CatD && ImplD && "Passed null params");
2136 ObjCImpls[CatD] = ImplD;
2137}
2138
Chandler Carruth21c90602015-12-30 03:24:14 +00002139const ObjCMethodDecl *
2140ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2141 return ObjCMethodRedecls.lookup(MD);
2142}
2143
2144void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2145 const ObjCMethodDecl *Redecl) {
2146 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2147 ObjCMethodRedecls[MD] = Redecl;
2148}
2149
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002150const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2151 const NamedDecl *ND) const {
2152 if (const ObjCInterfaceDecl *ID =
2153 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002154 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002155 if (const ObjCCategoryDecl *CD =
2156 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002157 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002158 if (const ObjCImplDecl *IMD =
2159 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002160 return IMD->getClassInterface();
2161
Craig Topper36250ad2014-05-12 05:36:57 +00002162 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002163}
2164
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002165/// \brief Get the copy initialization expression of VarDecl,or NULL if
2166/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002167Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002168 assert(VD && "Passed null params");
2169 assert(VD->hasAttr<BlocksAttr>() &&
2170 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002171 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002172 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002173 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002174}
2175
2176/// \brief Set the copy inialization expression of a block var decl.
2177void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2178 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002179 assert(VD->hasAttr<BlocksAttr>() &&
2180 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002181 BlockVarCopyInits[VD] = Init;
2182}
2183
John McCallbcd03502009-12-07 02:54:59 +00002184TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002185 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002186 if (!DataSize)
2187 DataSize = TypeLoc::getFullDataSizeForType(T);
2188 else
2189 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002190 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002191
John McCallbcd03502009-12-07 02:54:59 +00002192 TypeSourceInfo *TInfo =
2193 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2194 new (TInfo) TypeSourceInfo(T);
2195 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002196}
2197
John McCallbcd03502009-12-07 02:54:59 +00002198TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002199 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002200 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002201 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002202 return DI;
2203}
2204
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002205const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002206ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002207 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002208}
2209
2210const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002211ASTContext::getASTObjCImplementationLayout(
2212 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002213 return getObjCLayout(D->getClassInterface(), D);
2214}
2215
Chris Lattner983a8bb2007-07-13 22:13:22 +00002216//===----------------------------------------------------------------------===//
2217// Type creation/memoization methods
2218//===----------------------------------------------------------------------===//
2219
Jay Foad39c79802011-01-12 09:06:06 +00002220QualType
John McCall33ddac02011-01-19 10:06:00 +00002221ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2222 unsigned fastQuals = quals.getFastQualifiers();
2223 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002224
2225 // Check if we've already instantiated this type.
2226 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002227 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002228 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002229 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2230 assert(eq->getQualifiers() == quals);
2231 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002232 }
2233
John McCall33ddac02011-01-19 10:06:00 +00002234 // If the base type is not canonical, make the appropriate canonical type.
2235 QualType canon;
2236 if (!baseType->isCanonicalUnqualified()) {
2237 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002238 canonSplit.Quals.addConsistentQualifiers(quals);
2239 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002240
2241 // Re-find the insert position.
2242 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2243 }
2244
2245 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2246 ExtQualNodes.InsertNode(eq, insertPos);
2247 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002248}
2249
Jay Foad39c79802011-01-12 09:06:06 +00002250QualType
2251ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002252 QualType CanT = getCanonicalType(T);
2253 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002254 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002255
John McCall8ccfcb52009-09-24 19:53:00 +00002256 // If we are composing extended qualifiers together, merge together
2257 // into one ExtQuals node.
2258 QualifierCollector Quals;
2259 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002260
John McCall8ccfcb52009-09-24 19:53:00 +00002261 // If this type already has an address space specified, it cannot get
2262 // another one.
2263 assert(!Quals.hasAddressSpace() &&
2264 "Type cannot be in multiple addr spaces!");
2265 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002266
John McCall8ccfcb52009-09-24 19:53:00 +00002267 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002268}
2269
Chris Lattnerd60183d2009-02-18 22:53:11 +00002270QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002271 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002272 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002273 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002274 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002275
John McCall53fa7142010-12-24 02:08:15 +00002276 if (const PointerType *ptr = T->getAs<PointerType>()) {
2277 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002278 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002279 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2280 return getPointerType(ResultType);
2281 }
2282 }
Mike Stump11289f42009-09-09 15:08:12 +00002283
John McCall8ccfcb52009-09-24 19:53:00 +00002284 // If we are composing extended qualifiers together, merge together
2285 // into one ExtQuals node.
2286 QualifierCollector Quals;
2287 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002288
John McCall8ccfcb52009-09-24 19:53:00 +00002289 // If this type already has an ObjCGC specified, it cannot get
2290 // another one.
2291 assert(!Quals.hasObjCGCAttr() &&
2292 "Type cannot have multiple ObjCGCs!");
2293 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002294
John McCall8ccfcb52009-09-24 19:53:00 +00002295 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002296}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002297
John McCall4f5019e2010-12-19 02:44:49 +00002298const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2299 FunctionType::ExtInfo Info) {
2300 if (T->getExtInfo() == Info)
2301 return T;
2302
2303 QualType Result;
2304 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002305 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002306 } else {
2307 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2308 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2309 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002310 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002311 }
2312
2313 return cast<FunctionType>(Result.getTypePtr());
2314}
2315
Richard Smith2a7d4812013-05-04 07:00:32 +00002316void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2317 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002318 FD = FD->getMostRecentDecl();
2319 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002320 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2321 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002322 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002323 if (FunctionDecl *Next = FD->getPreviousDecl())
2324 FD = Next;
2325 else
2326 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002327 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002328 if (ASTMutationListener *L = getASTMutationListener())
2329 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002330}
2331
Richard Smith0b3a4622014-11-13 20:01:57 +00002332/// Get a function type and produce the equivalent function type with the
2333/// specified exception specification. Type sugar that can be present on a
2334/// declaration of a function with an exception specification is permitted
2335/// and preserved. Other type sugar (for instance, typedefs) is not.
2336static QualType getFunctionTypeWithExceptionSpec(
2337 ASTContext &Context, QualType Orig,
2338 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2339 // Might have some parens.
2340 if (auto *PT = dyn_cast<ParenType>(Orig))
2341 return Context.getParenType(
2342 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2343
2344 // Might have a calling-convention attribute.
2345 if (auto *AT = dyn_cast<AttributedType>(Orig))
2346 return Context.getAttributedType(
2347 AT->getAttrKind(),
2348 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2349 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2350 ESI));
2351
2352 // Anything else must be a function type. Rebuild it with the new exception
2353 // specification.
2354 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2355 return Context.getFunctionType(
2356 Proto->getReturnType(), Proto->getParamTypes(),
2357 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2358}
2359
2360void ASTContext::adjustExceptionSpec(
2361 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2362 bool AsWritten) {
2363 // Update the type.
2364 QualType Updated =
2365 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2366 FD->setType(Updated);
2367
2368 if (!AsWritten)
2369 return;
2370
2371 // Update the type in the type source information too.
2372 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2373 // If the type and the type-as-written differ, we may need to update
2374 // the type-as-written too.
2375 if (TSInfo->getType() != FD->getType())
2376 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2377
2378 // FIXME: When we get proper type location information for exceptions,
2379 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2380 // up the TypeSourceInfo;
2381 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2382 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2383 "TypeLoc size mismatch from updating exception specification");
2384 TSInfo->overrideType(Updated);
2385 }
2386}
2387
Chris Lattnerc6395932007-06-22 20:56:16 +00002388/// getComplexType - Return the uniqued reference to the type for a complex
2389/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002390QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002391 // Unique pointers, to guarantee there is only one pointer of a particular
2392 // structure.
2393 llvm::FoldingSetNodeID ID;
2394 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002395
Craig Topper36250ad2014-05-12 05:36:57 +00002396 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002397 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2398 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002399
Chris Lattnerc6395932007-06-22 20:56:16 +00002400 // If the pointee type isn't canonical, this won't be a canonical type either,
2401 // so fill in the canonical type field.
2402 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002403 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002404 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002405
Chris Lattnerc6395932007-06-22 20:56:16 +00002406 // Get the new insert position for the node we care about.
2407 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002408 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002409 }
John McCall90d1c2d2009-09-24 23:30:46 +00002410 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002411 Types.push_back(New);
2412 ComplexTypes.InsertNode(New, InsertPos);
2413 return QualType(New, 0);
2414}
2415
Chris Lattner970e54e2006-11-12 00:37:36 +00002416/// getPointerType - Return the uniqued reference to the type for a pointer to
2417/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002418QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002419 // Unique pointers, to guarantee there is only one pointer of a particular
2420 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002421 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002422 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002423
Craig Topper36250ad2014-05-12 05:36:57 +00002424 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002425 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002426 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002427
Chris Lattner7ccecb92006-11-12 08:50:50 +00002428 // If the pointee type isn't canonical, this won't be a canonical type either,
2429 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002430 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002431 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002432 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002433
Bob Wilsonc8541f22013-03-15 17:12:43 +00002434 // Get the new insert position for the node we care about.
2435 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002436 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002437 }
John McCall90d1c2d2009-09-24 23:30:46 +00002438 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002439 Types.push_back(New);
2440 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002441 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002442}
2443
Reid Kleckner0503a872013-12-05 01:23:43 +00002444QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2445 llvm::FoldingSetNodeID ID;
2446 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002447 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002448 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2449 if (AT)
2450 return QualType(AT, 0);
2451
2452 QualType Canonical = getCanonicalType(New);
2453
2454 // Get the new insert position for the node we care about.
2455 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002456 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002457
2458 AT = new (*this, TypeAlignment)
2459 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2460 Types.push_back(AT);
2461 AdjustedTypes.InsertNode(AT, InsertPos);
2462 return QualType(AT, 0);
2463}
2464
Reid Kleckner8a365022013-06-24 17:51:48 +00002465QualType ASTContext::getDecayedType(QualType T) const {
2466 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2467
Reid Kleckner8a365022013-06-24 17:51:48 +00002468 QualType Decayed;
2469
2470 // C99 6.7.5.3p7:
2471 // A declaration of a parameter as "array of type" shall be
2472 // adjusted to "qualified pointer to type", where the type
2473 // qualifiers (if any) are those specified within the [ and ] of
2474 // the array type derivation.
2475 if (T->isArrayType())
2476 Decayed = getArrayDecayedType(T);
2477
2478 // C99 6.7.5.3p8:
2479 // A declaration of a parameter as "function returning type"
2480 // shall be adjusted to "pointer to function returning type", as
2481 // in 6.3.2.1.
2482 if (T->isFunctionType())
2483 Decayed = getPointerType(T);
2484
Reid Kleckner0503a872013-12-05 01:23:43 +00002485 llvm::FoldingSetNodeID ID;
2486 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002487 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002488 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2489 if (AT)
2490 return QualType(AT, 0);
2491
Reid Kleckner8a365022013-06-24 17:51:48 +00002492 QualType Canonical = getCanonicalType(Decayed);
2493
2494 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002495 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002496 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002497
Reid Kleckner0503a872013-12-05 01:23:43 +00002498 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2499 Types.push_back(AT);
2500 AdjustedTypes.InsertNode(AT, InsertPos);
2501 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002502}
2503
Mike Stump11289f42009-09-09 15:08:12 +00002504/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002505/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002506QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002507 assert(T->isFunctionType() && "block of function types only");
2508 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002509 // structure.
2510 llvm::FoldingSetNodeID ID;
2511 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002512
Craig Topper36250ad2014-05-12 05:36:57 +00002513 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002514 if (BlockPointerType *PT =
2515 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2516 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002517
2518 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002519 // type either so fill in the canonical type field.
2520 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002521 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002522 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002523
Steve Naroffec33ed92008-08-27 16:04:49 +00002524 // Get the new insert position for the node we care about.
2525 BlockPointerType *NewIP =
2526 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002527 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002528 }
John McCall90d1c2d2009-09-24 23:30:46 +00002529 BlockPointerType *New
2530 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002531 Types.push_back(New);
2532 BlockPointerTypes.InsertNode(New, InsertPos);
2533 return QualType(New, 0);
2534}
2535
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002536/// getLValueReferenceType - Return the uniqued reference to the type for an
2537/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002538QualType
2539ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002540 assert(getCanonicalType(T) != OverloadTy &&
2541 "Unresolved overloaded function type");
2542
Bill Wendling3708c182007-05-27 10:15:43 +00002543 // Unique pointers, to guarantee there is only one pointer of a particular
2544 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002545 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002546 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002547
Craig Topper36250ad2014-05-12 05:36:57 +00002548 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002549 if (LValueReferenceType *RT =
2550 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002551 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002552
John McCallfc93cf92009-10-22 22:37:11 +00002553 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2554
Bill Wendling3708c182007-05-27 10:15:43 +00002555 // If the referencee type isn't canonical, this won't be a canonical type
2556 // either, so fill in the canonical type field.
2557 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002558 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2559 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2560 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002561
Bill Wendling3708c182007-05-27 10:15:43 +00002562 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002563 LValueReferenceType *NewIP =
2564 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002565 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002566 }
2567
John McCall90d1c2d2009-09-24 23:30:46 +00002568 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002569 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2570 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002571 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002572 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002573
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002574 return QualType(New, 0);
2575}
2576
2577/// getRValueReferenceType - Return the uniqued reference to the type for an
2578/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002579QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002580 // Unique pointers, to guarantee there is only one pointer of a particular
2581 // structure.
2582 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002583 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002584
Craig Topper36250ad2014-05-12 05:36:57 +00002585 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002586 if (RValueReferenceType *RT =
2587 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2588 return QualType(RT, 0);
2589
John McCallfc93cf92009-10-22 22:37:11 +00002590 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2591
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002592 // If the referencee type isn't canonical, this won't be a canonical type
2593 // either, so fill in the canonical type field.
2594 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002595 if (InnerRef || !T.isCanonical()) {
2596 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2597 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002598
2599 // Get the new insert position for the node we care about.
2600 RValueReferenceType *NewIP =
2601 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002602 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002603 }
2604
John McCall90d1c2d2009-09-24 23:30:46 +00002605 RValueReferenceType *New
2606 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002607 Types.push_back(New);
2608 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002609 return QualType(New, 0);
2610}
2611
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002612/// getMemberPointerType - Return the uniqued reference to the type for a
2613/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002614QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002615 // Unique pointers, to guarantee there is only one pointer of a particular
2616 // structure.
2617 llvm::FoldingSetNodeID ID;
2618 MemberPointerType::Profile(ID, T, Cls);
2619
Craig Topper36250ad2014-05-12 05:36:57 +00002620 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002621 if (MemberPointerType *PT =
2622 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2623 return QualType(PT, 0);
2624
2625 // If the pointee or class type isn't canonical, this won't be a canonical
2626 // type either, so fill in the canonical type field.
2627 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002628 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002629 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2630
2631 // Get the new insert position for the node we care about.
2632 MemberPointerType *NewIP =
2633 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002634 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002635 }
John McCall90d1c2d2009-09-24 23:30:46 +00002636 MemberPointerType *New
2637 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002638 Types.push_back(New);
2639 MemberPointerTypes.InsertNode(New, InsertPos);
2640 return QualType(New, 0);
2641}
2642
Mike Stump11289f42009-09-09 15:08:12 +00002643/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002644/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002645QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002646 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002647 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002648 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002649 assert((EltTy->isDependentType() ||
2650 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002651 "Constant array of VLAs is illegal!");
2652
Chris Lattnere2df3f92009-05-13 04:12:56 +00002653 // Convert the array size into a canonical width matching the pointer size for
2654 // the target.
2655 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002656 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002657 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002658
Chris Lattner23b7eb62007-06-15 23:05:46 +00002659 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002660 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002661
Craig Topper36250ad2014-05-12 05:36:57 +00002662 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002663 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002664 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002665 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002666
John McCall33ddac02011-01-19 10:06:00 +00002667 // If the element type isn't canonical or has qualifiers, this won't
2668 // be a canonical type either, so fill in the canonical type field.
2669 QualType Canon;
2670 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2671 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002672 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002673 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002674 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002675
Chris Lattner36f8e652007-01-27 08:31:04 +00002676 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002677 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002678 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002679 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002680 }
Mike Stump11289f42009-09-09 15:08:12 +00002681
John McCall90d1c2d2009-09-24 23:30:46 +00002682 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002683 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002684 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002685 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002686 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002687}
2688
John McCall06549462011-01-18 08:40:38 +00002689/// getVariableArrayDecayedType - Turns the given type, which may be
2690/// variably-modified, into the corresponding type with all the known
2691/// sizes replaced with [*].
2692QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2693 // Vastly most common case.
2694 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002695
John McCall06549462011-01-18 08:40:38 +00002696 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002697
John McCall06549462011-01-18 08:40:38 +00002698 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002699 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002700 switch (ty->getTypeClass()) {
2701#define TYPE(Class, Base)
2702#define ABSTRACT_TYPE(Class, Base)
2703#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2704#include "clang/AST/TypeNodes.def"
2705 llvm_unreachable("didn't desugar past all non-canonical types?");
2706
2707 // These types should never be variably-modified.
2708 case Type::Builtin:
2709 case Type::Complex:
2710 case Type::Vector:
2711 case Type::ExtVector:
2712 case Type::DependentSizedExtVector:
2713 case Type::ObjCObject:
2714 case Type::ObjCInterface:
2715 case Type::ObjCObjectPointer:
2716 case Type::Record:
2717 case Type::Enum:
2718 case Type::UnresolvedUsing:
2719 case Type::TypeOfExpr:
2720 case Type::TypeOf:
2721 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002722 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002723 case Type::DependentName:
2724 case Type::InjectedClassName:
2725 case Type::TemplateSpecialization:
2726 case Type::DependentTemplateSpecialization:
2727 case Type::TemplateTypeParm:
2728 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002729 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002730 case Type::PackExpansion:
2731 llvm_unreachable("type should never be variably-modified");
2732
2733 // These types can be variably-modified but should never need to
2734 // further decay.
2735 case Type::FunctionNoProto:
2736 case Type::FunctionProto:
2737 case Type::BlockPointer:
2738 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002739 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002740 return type;
2741
2742 // These types can be variably-modified. All these modifications
2743 // preserve structure except as noted by comments.
2744 // TODO: if we ever care about optimizing VLAs, there are no-op
2745 // optimizations available here.
2746 case Type::Pointer:
2747 result = getPointerType(getVariableArrayDecayedType(
2748 cast<PointerType>(ty)->getPointeeType()));
2749 break;
2750
2751 case Type::LValueReference: {
2752 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2753 result = getLValueReferenceType(
2754 getVariableArrayDecayedType(lv->getPointeeType()),
2755 lv->isSpelledAsLValue());
2756 break;
2757 }
2758
2759 case Type::RValueReference: {
2760 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2761 result = getRValueReferenceType(
2762 getVariableArrayDecayedType(lv->getPointeeType()));
2763 break;
2764 }
2765
Eli Friedman0dfb8892011-10-06 23:00:33 +00002766 case Type::Atomic: {
2767 const AtomicType *at = cast<AtomicType>(ty);
2768 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2769 break;
2770 }
2771
John McCall06549462011-01-18 08:40:38 +00002772 case Type::ConstantArray: {
2773 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2774 result = getConstantArrayType(
2775 getVariableArrayDecayedType(cat->getElementType()),
2776 cat->getSize(),
2777 cat->getSizeModifier(),
2778 cat->getIndexTypeCVRQualifiers());
2779 break;
2780 }
2781
2782 case Type::DependentSizedArray: {
2783 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2784 result = getDependentSizedArrayType(
2785 getVariableArrayDecayedType(dat->getElementType()),
2786 dat->getSizeExpr(),
2787 dat->getSizeModifier(),
2788 dat->getIndexTypeCVRQualifiers(),
2789 dat->getBracketsRange());
2790 break;
2791 }
2792
2793 // Turn incomplete types into [*] types.
2794 case Type::IncompleteArray: {
2795 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2796 result = getVariableArrayType(
2797 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002798 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002799 ArrayType::Normal,
2800 iat->getIndexTypeCVRQualifiers(),
2801 SourceRange());
2802 break;
2803 }
2804
2805 // Turn VLA types into [*] types.
2806 case Type::VariableArray: {
2807 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2808 result = getVariableArrayType(
2809 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002810 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002811 ArrayType::Star,
2812 vat->getIndexTypeCVRQualifiers(),
2813 vat->getBracketsRange());
2814 break;
2815 }
2816 }
2817
2818 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002819 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002820}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002821
Steve Naroffcadebd02007-08-30 18:14:25 +00002822/// getVariableArrayType - Returns a non-unique reference to the type for a
2823/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002824QualType ASTContext::getVariableArrayType(QualType EltTy,
2825 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002826 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002827 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002828 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002829 // Since we don't unique expressions, it isn't possible to unique VLA's
2830 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002831 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002832
John McCall33ddac02011-01-19 10:06:00 +00002833 // Be sure to pull qualifiers off the element type.
2834 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2835 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002836 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002837 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002838 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002839 }
2840
John McCall90d1c2d2009-09-24 23:30:46 +00002841 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002842 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002843
2844 VariableArrayTypes.push_back(New);
2845 Types.push_back(New);
2846 return QualType(New, 0);
2847}
2848
Douglas Gregor4619e432008-12-05 23:32:09 +00002849/// getDependentSizedArrayType - Returns a non-unique reference to
2850/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002851/// type.
John McCall33ddac02011-01-19 10:06:00 +00002852QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2853 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002854 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002855 unsigned elementTypeQuals,
2856 SourceRange brackets) const {
2857 assert((!numElements || numElements->isTypeDependent() ||
2858 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002859 "Size must be type- or value-dependent!");
2860
John McCall33ddac02011-01-19 10:06:00 +00002861 // Dependently-sized array types that do not have a specified number
2862 // of elements will have their sizes deduced from a dependent
2863 // initializer. We do no canonicalization here at all, which is okay
2864 // because they can't be used in most locations.
2865 if (!numElements) {
2866 DependentSizedArrayType *newType
2867 = new (*this, TypeAlignment)
2868 DependentSizedArrayType(*this, elementType, QualType(),
2869 numElements, ASM, elementTypeQuals,
2870 brackets);
2871 Types.push_back(newType);
2872 return QualType(newType, 0);
2873 }
2874
2875 // Otherwise, we actually build a new type every time, but we
2876 // also build a canonical type.
2877
2878 SplitQualType canonElementType = getCanonicalType(elementType).split();
2879
Craig Topper36250ad2014-05-12 05:36:57 +00002880 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002881 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002882 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002883 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002884 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002885
John McCall33ddac02011-01-19 10:06:00 +00002886 // Look for an existing type with these properties.
2887 DependentSizedArrayType *canonTy =
2888 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002889
John McCall33ddac02011-01-19 10:06:00 +00002890 // If we don't have one, build one.
2891 if (!canonTy) {
2892 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002893 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002894 QualType(), numElements, ASM, elementTypeQuals,
2895 brackets);
2896 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2897 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002898 }
2899
John McCall33ddac02011-01-19 10:06:00 +00002900 // Apply qualifiers from the element type to the array.
2901 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002902 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002903
David Majnemer16a74702015-07-24 05:54:19 +00002904 // If we didn't need extra canonicalization for the element type or the size
2905 // expression, then just use that as our result.
2906 if (QualType(canonElementType.Ty, 0) == elementType &&
2907 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002908 return canon;
2909
2910 // Otherwise, we need to build a type which follows the spelling
2911 // of the element type.
2912 DependentSizedArrayType *sugaredType
2913 = new (*this, TypeAlignment)
2914 DependentSizedArrayType(*this, elementType, canon, numElements,
2915 ASM, elementTypeQuals, brackets);
2916 Types.push_back(sugaredType);
2917 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002918}
2919
John McCall33ddac02011-01-19 10:06:00 +00002920QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002921 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002922 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002923 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002924 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002925
Craig Topper36250ad2014-05-12 05:36:57 +00002926 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002927 if (IncompleteArrayType *iat =
2928 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2929 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002930
2931 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002932 // either, so fill in the canonical type field. We also have to pull
2933 // qualifiers off the element type.
2934 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002935
John McCall33ddac02011-01-19 10:06:00 +00002936 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2937 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002938 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002939 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002940 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002941
2942 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002943 IncompleteArrayType *existing =
2944 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2945 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002946 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002947
John McCall33ddac02011-01-19 10:06:00 +00002948 IncompleteArrayType *newType = new (*this, TypeAlignment)
2949 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002950
John McCall33ddac02011-01-19 10:06:00 +00002951 IncompleteArrayTypes.InsertNode(newType, insertPos);
2952 Types.push_back(newType);
2953 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002954}
2955
Steve Naroff91fcddb2007-07-18 18:00:27 +00002956/// getVectorType - Return the unique reference to a vector type of
2957/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002958QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002959 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002960 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002961
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002962 // Check if we've already instantiated a vector of this type.
2963 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002964 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002965
Craig Topper36250ad2014-05-12 05:36:57 +00002966 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002967 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2968 return QualType(VTP, 0);
2969
2970 // If the element type isn't canonical, this won't be a canonical type either,
2971 // so fill in the canonical type field.
2972 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002973 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002974 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002975
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002976 // Get the new insert position for the node we care about.
2977 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002978 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002979 }
John McCall90d1c2d2009-09-24 23:30:46 +00002980 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002981 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002982 VectorTypes.InsertNode(New, InsertPos);
2983 Types.push_back(New);
2984 return QualType(New, 0);
2985}
2986
Nate Begemance4d7fc2008-04-18 23:10:10 +00002987/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002988/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002989QualType
2990ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002991 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002992
Steve Naroff91fcddb2007-07-18 18:00:27 +00002993 // Check if we've already instantiated a vector of this type.
2994 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002995 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002996 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002997 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002998 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2999 return QualType(VTP, 0);
3000
3001 // If the element type isn't canonical, this won't be a canonical type either,
3002 // so fill in the canonical type field.
3003 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003004 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003005 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003006
Steve Naroff91fcddb2007-07-18 18:00:27 +00003007 // Get the new insert position for the node we care about.
3008 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003009 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003010 }
John McCall90d1c2d2009-09-24 23:30:46 +00003011 ExtVectorType *New = new (*this, TypeAlignment)
3012 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003013 VectorTypes.InsertNode(New, InsertPos);
3014 Types.push_back(New);
3015 return QualType(New, 0);
3016}
3017
Jay Foad39c79802011-01-12 09:06:06 +00003018QualType
3019ASTContext::getDependentSizedExtVectorType(QualType vecType,
3020 Expr *SizeExpr,
3021 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003022 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003023 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003024 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003025
Craig Topper36250ad2014-05-12 05:36:57 +00003026 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003027 DependentSizedExtVectorType *Canon
3028 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3029 DependentSizedExtVectorType *New;
3030 if (Canon) {
3031 // We already have a canonical version of this array type; use it as
3032 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003033 New = new (*this, TypeAlignment)
3034 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3035 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003036 } else {
3037 QualType CanonVecTy = getCanonicalType(vecType);
3038 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003039 New = new (*this, TypeAlignment)
3040 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3041 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003042
3043 DependentSizedExtVectorType *CanonCheck
3044 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3045 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3046 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003047 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3048 } else {
3049 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3050 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003051 New = new (*this, TypeAlignment)
3052 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003053 }
3054 }
Mike Stump11289f42009-09-09 15:08:12 +00003055
Douglas Gregor758a8692009-06-17 21:51:59 +00003056 Types.push_back(New);
3057 return QualType(New, 0);
3058}
3059
John McCall18afab72016-03-01 00:49:02 +00003060/// \brief Determine whether \p T is canonical as the result type of a function.
3061static bool isCanonicalResultType(QualType T) {
3062 return T.isCanonical() &&
3063 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3064 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3065}
3066
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003067/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003068///
Jay Foad39c79802011-01-12 09:06:06 +00003069QualType
3070ASTContext::getFunctionNoProtoType(QualType ResultTy,
3071 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003072 // Unique functions, to guarantee there is only one function of a particular
3073 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003074 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003075 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003076
Craig Topper36250ad2014-05-12 05:36:57 +00003077 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003078 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003079 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003080 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003081
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003082 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003083 if (!isCanonicalResultType(ResultTy)) {
3084 Canonical =
3085 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003086
Chris Lattner47955de2007-01-27 08:37:20 +00003087 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003088 FunctionNoProtoType *NewIP =
3089 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003090 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003091 }
Mike Stump11289f42009-09-09 15:08:12 +00003092
John McCall90d1c2d2009-09-24 23:30:46 +00003093 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003094 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003095 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003096 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003097 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003098}
3099
Douglas Gregora602a152015-10-01 20:20:47 +00003100CanQualType
3101ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3102 CanQualType CanResultType = getCanonicalType(ResultType);
3103
3104 // Canonical result types do not have ARC lifetime qualifiers.
3105 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3106 Qualifiers Qs = CanResultType.getQualifiers();
3107 Qs.removeObjCLifetime();
3108 return CanQualType::CreateUnsafe(
3109 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3110 }
3111
3112 return CanResultType;
3113}
3114
Jay Foad39c79802011-01-12 09:06:06 +00003115QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003116ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003117 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003118 size_t NumArgs = ArgArray.size();
3119
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003120 // Unique functions, to guarantee there is only one function of a particular
3121 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003122 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003123 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3124 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003125
Craig Topper36250ad2014-05-12 05:36:57 +00003126 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003127 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003128 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003129 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003130
3131 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003132 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003133 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003134 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003135 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003136 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003137 isCanonical = false;
3138
3139 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003140 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003141 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003142 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003143 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003144 CanonicalArgs.reserve(NumArgs);
3145 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003146 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003147
John McCalldb40c7f2010-12-14 08:05:40 +00003148 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003149 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003150 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003151
Douglas Gregora602a152015-10-01 20:20:47 +00003152 // Adjust the canonical function result type.
3153 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003154 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003155
Chris Lattnerfd4de792007-01-27 01:15:32 +00003156 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003157 FunctionProtoType *NewIP =
3158 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003159 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003160 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003161
John McCall31168b02011-06-15 23:02:42 +00003162 // FunctionProtoType objects are allocated with extra bytes after
3163 // them for three variable size arrays at the end:
3164 // - parameter types
3165 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003166 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003167 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003168 // expression, or information used to resolve the exception
3169 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003170 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003171 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003172
Richard Smith8acb4282014-07-31 21:57:55 +00003173 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3174 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3175 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003176 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003177 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003178 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003179 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003180 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003181 }
John McCall18afab72016-03-01 00:49:02 +00003182
3183 // Put the ExtParameterInfos last. If all were equal, it would make
3184 // more sense to put these before the exception specification, because
3185 // it's much easier to skip past them compared to the elaborate switch
3186 // required to skip the exception specification. However, all is not
3187 // equal; ExtParameterInfos are used to model very uncommon features,
3188 // and it's better not to burden the more common paths.
3189 if (EPI.ExtParameterInfos) {
3190 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3191 }
John McCall31168b02011-06-15 23:02:42 +00003192
John McCalldb40c7f2010-12-14 08:05:40 +00003193 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003194 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003195 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003196 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003197 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003198 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003199}
Chris Lattneref51c202006-11-10 07:17:23 +00003200
Xiuli Pan9c14e282016-01-09 12:53:17 +00003201/// Return pipe type for the specified type.
3202QualType ASTContext::getPipeType(QualType T) const {
3203 llvm::FoldingSetNodeID ID;
3204 PipeType::Profile(ID, T);
3205
3206 void *InsertPos = 0;
3207 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3208 return QualType(PT, 0);
3209
3210 // If the pipe element type isn't canonical, this won't be a canonical type
3211 // either, so fill in the canonical type field.
3212 QualType Canonical;
3213 if (!T.isCanonical()) {
3214 Canonical = getPipeType(getCanonicalType(T));
3215
3216 // Get the new insert position for the node we care about.
3217 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3218 assert(!NewIP && "Shouldn't be in the map!");
3219 (void)NewIP;
3220 }
3221 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3222 Types.push_back(New);
3223 PipeTypes.InsertNode(New, InsertPos);
3224 return QualType(New, 0);
3225}
3226
John McCalle78aac42010-03-10 03:28:59 +00003227#ifndef NDEBUG
3228static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3229 if (!isa<CXXRecordDecl>(D)) return false;
3230 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3231 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3232 return true;
3233 if (RD->getDescribedClassTemplate() &&
3234 !isa<ClassTemplateSpecializationDecl>(RD))
3235 return true;
3236 return false;
3237}
3238#endif
3239
3240/// getInjectedClassNameType - Return the unique reference to the
3241/// injected class name type for the specified templated declaration.
3242QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003243 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003244 assert(NeedsInjectedClassNameType(Decl));
3245 if (Decl->TypeForDecl) {
3246 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003247 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003248 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3249 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3250 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3251 } else {
John McCall424cec92011-01-19 06:33:43 +00003252 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003253 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003254 Decl->TypeForDecl = newType;
3255 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003256 }
3257 return QualType(Decl->TypeForDecl, 0);
3258}
3259
Douglas Gregor83a586e2008-04-13 21:07:44 +00003260/// getTypeDeclType - Return the unique reference to the type for the
3261/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003262QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003263 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003264 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003265
Richard Smithdda56e42011-04-15 14:24:37 +00003266 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003267 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003268
John McCall96f0b5f2010-03-10 06:48:02 +00003269 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3270 "Template type parameter types are always available.");
3271
John McCall81e38502010-02-16 03:57:14 +00003272 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003273 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003274 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003275 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003276 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003277 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003278 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003279 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003280 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003281 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3282 Decl->TypeForDecl = newType;
3283 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003284 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003285 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003286
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003287 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003288}
3289
Chris Lattner32d920b2007-01-26 02:01:53 +00003290/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003291/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003292QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003293ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3294 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003295 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003296
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003297 if (Canonical.isNull())
3298 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003299 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003300 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003301 Decl->TypeForDecl = newType;
3302 Types.push_back(newType);
3303 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003304}
3305
Jay Foad39c79802011-01-12 09:06:06 +00003306QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003307 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3308
Douglas Gregorec9fd132012-01-14 16:38:05 +00003309 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003310 if (PrevDecl->TypeForDecl)
3311 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3312
John McCall424cec92011-01-19 06:33:43 +00003313 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3314 Decl->TypeForDecl = newType;
3315 Types.push_back(newType);
3316 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003317}
3318
Jay Foad39c79802011-01-12 09:06:06 +00003319QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003320 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3321
Douglas Gregorec9fd132012-01-14 16:38:05 +00003322 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003323 if (PrevDecl->TypeForDecl)
3324 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3325
John McCall424cec92011-01-19 06:33:43 +00003326 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3327 Decl->TypeForDecl = newType;
3328 Types.push_back(newType);
3329 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003330}
3331
John McCall81904512011-01-06 01:58:22 +00003332QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3333 QualType modifiedType,
3334 QualType equivalentType) {
3335 llvm::FoldingSetNodeID id;
3336 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3337
Craig Topper36250ad2014-05-12 05:36:57 +00003338 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003339 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3340 if (type) return QualType(type, 0);
3341
3342 QualType canon = getCanonicalType(equivalentType);
3343 type = new (*this, TypeAlignment)
3344 AttributedType(canon, attrKind, modifiedType, equivalentType);
3345
3346 Types.push_back(type);
3347 AttributedTypes.InsertNode(type, insertPos);
3348
3349 return QualType(type, 0);
3350}
3351
John McCallcebee162009-10-18 09:09:24 +00003352/// \brief Retrieve a substitution-result type.
3353QualType
3354ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003355 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003356 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003357 && "replacement types must always be canonical");
3358
3359 llvm::FoldingSetNodeID ID;
3360 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003361 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003362 SubstTemplateTypeParmType *SubstParm
3363 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3364
3365 if (!SubstParm) {
3366 SubstParm = new (*this, TypeAlignment)
3367 SubstTemplateTypeParmType(Parm, Replacement);
3368 Types.push_back(SubstParm);
3369 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3370 }
3371
3372 return QualType(SubstParm, 0);
3373}
3374
Douglas Gregorada4b792011-01-14 02:55:32 +00003375/// \brief Retrieve a
3376QualType ASTContext::getSubstTemplateTypeParmPackType(
3377 const TemplateTypeParmType *Parm,
3378 const TemplateArgument &ArgPack) {
3379#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003380 for (const auto &P : ArgPack.pack_elements()) {
3381 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3382 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003383 }
3384#endif
3385
3386 llvm::FoldingSetNodeID ID;
3387 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003388 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003389 if (SubstTemplateTypeParmPackType *SubstParm
3390 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3391 return QualType(SubstParm, 0);
3392
3393 QualType Canon;
3394 if (!Parm->isCanonicalUnqualified()) {
3395 Canon = getCanonicalType(QualType(Parm, 0));
3396 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3397 ArgPack);
3398 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3399 }
3400
3401 SubstTemplateTypeParmPackType *SubstParm
3402 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3403 ArgPack);
3404 Types.push_back(SubstParm);
3405 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3406 return QualType(SubstParm, 0);
3407}
3408
Douglas Gregoreff93e02009-02-05 23:33:38 +00003409/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003410/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003411/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003412QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003413 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003414 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003415 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003416 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003417 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003418 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003419 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3420
3421 if (TypeParm)
3422 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003423
Chandler Carruth08836322011-05-01 00:51:33 +00003424 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003425 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003426 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003427
3428 TemplateTypeParmType *TypeCheck
3429 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3430 assert(!TypeCheck && "Template type parameter canonical type broken");
3431 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003432 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003433 TypeParm = new (*this, TypeAlignment)
3434 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003435
3436 Types.push_back(TypeParm);
3437 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3438
3439 return QualType(TypeParm, 0);
3440}
3441
John McCalle78aac42010-03-10 03:28:59 +00003442TypeSourceInfo *
3443ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3444 SourceLocation NameLoc,
3445 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003446 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003447 assert(!Name.getAsDependentTemplateName() &&
3448 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003449 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003450
3451 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003452 TemplateSpecializationTypeLoc TL =
3453 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003454 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003455 TL.setTemplateNameLoc(NameLoc);
3456 TL.setLAngleLoc(Args.getLAngleLoc());
3457 TL.setRAngleLoc(Args.getRAngleLoc());
3458 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3459 TL.setArgLocInfo(i, Args[i].getLocInfo());
3460 return DI;
3461}
3462
Mike Stump11289f42009-09-09 15:08:12 +00003463QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003464ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003465 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003466 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003467 assert(!Template.getAsDependentTemplateName() &&
3468 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003469
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003470 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003471 ArgVec.reserve(Args.size());
3472 for (const TemplateArgumentLoc &Arg : Args.arguments())
3473 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003474
David Majnemer6fbeee32016-07-07 04:43:07 +00003475 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003476}
3477
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003478#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003479static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3480 for (const TemplateArgument &Arg : Args)
3481 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003482 return true;
3483
3484 return true;
3485}
3486#endif
3487
John McCall0ad16662009-10-29 08:12:44 +00003488QualType
3489ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003490 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003491 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003492 assert(!Template.getAsDependentTemplateName() &&
3493 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003494 // Look through qualified template names.
3495 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3496 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003497
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003498 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003499 Template.getAsTemplateDecl() &&
3500 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003501 QualType CanonType;
3502 if (!Underlying.isNull())
3503 CanonType = getCanonicalType(Underlying);
3504 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003505 // We can get here with an alias template when the specialization contains
3506 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003507 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003508 "Caller must compute aliased type");
3509 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003510 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003511 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003512
Douglas Gregora8e02e72009-07-28 23:00:59 +00003513 // Allocate the (non-canonical) template specialization type, but don't
3514 // try to unique it: these types typically have location information that
3515 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003516 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003517 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003518 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003519 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003520 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003521 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003522 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003523
Douglas Gregor8bf42052009-02-09 18:46:07 +00003524 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003525 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003526}
3527
David Majnemer6fbeee32016-07-07 04:43:07 +00003528QualType ASTContext::getCanonicalTemplateSpecializationType(
3529 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003530 assert(!Template.getAsDependentTemplateName() &&
3531 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003532
Douglas Gregore29139c2011-03-03 17:04:51 +00003533 // Look through qualified template names.
3534 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3535 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003536
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003537 // Build the canonical template specialization type.
3538 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003539 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003540 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003541 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003542 for (const TemplateArgument &Arg : Args)
3543 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003544
3545 // Determine whether this canonical template specialization type already
3546 // exists.
3547 llvm::FoldingSetNodeID ID;
3548 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003549 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003550
Craig Topper36250ad2014-05-12 05:36:57 +00003551 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003552 TemplateSpecializationType *Spec
3553 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3554
3555 if (!Spec) {
3556 // Allocate a new canonical template specialization type.
3557 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3558 sizeof(TemplateArgument) * NumArgs),
3559 TypeAlignment);
3560 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003561 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003562 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003563 Types.push_back(Spec);
3564 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3565 }
3566
3567 assert(Spec->isDependentType() &&
3568 "Non-dependent template-id type must have a canonical type");
3569 return QualType(Spec, 0);
3570}
3571
3572QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003573ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3574 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003575 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003576 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003577 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003578
Craig Topper36250ad2014-05-12 05:36:57 +00003579 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003580 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003581 if (T)
3582 return QualType(T, 0);
3583
Douglas Gregorc42075a2010-02-04 18:10:26 +00003584 QualType Canon = NamedType;
3585 if (!Canon.isCanonical()) {
3586 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003587 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3588 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003589 (void)CheckT;
3590 }
3591
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003592 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003593 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003594 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003595 return QualType(T, 0);
3596}
3597
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003598QualType
Jay Foad39c79802011-01-12 09:06:06 +00003599ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003600 llvm::FoldingSetNodeID ID;
3601 ParenType::Profile(ID, InnerType);
3602
Craig Topper36250ad2014-05-12 05:36:57 +00003603 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003604 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3605 if (T)
3606 return QualType(T, 0);
3607
3608 QualType Canon = InnerType;
3609 if (!Canon.isCanonical()) {
3610 Canon = getCanonicalType(InnerType);
3611 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3612 assert(!CheckT && "Paren canonical type broken");
3613 (void)CheckT;
3614 }
3615
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003616 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003617 Types.push_back(T);
3618 ParenTypes.InsertNode(T, InsertPos);
3619 return QualType(T, 0);
3620}
3621
Douglas Gregor02085352010-03-31 20:19:30 +00003622QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3623 NestedNameSpecifier *NNS,
3624 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003625 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003626 if (Canon.isNull()) {
3627 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003628 ElaboratedTypeKeyword CanonKeyword = Keyword;
3629 if (Keyword == ETK_None)
3630 CanonKeyword = ETK_Typename;
3631
3632 if (CanonNNS != NNS || CanonKeyword != Keyword)
3633 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003634 }
3635
3636 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003637 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003638
Craig Topper36250ad2014-05-12 05:36:57 +00003639 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003640 DependentNameType *T
3641 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003642 if (T)
3643 return QualType(T, 0);
3644
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003645 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003646 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003647 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003648 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003649}
3650
Mike Stump11289f42009-09-09 15:08:12 +00003651QualType
John McCallc392f372010-06-11 00:33:02 +00003652ASTContext::getDependentTemplateSpecializationType(
3653 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003654 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003655 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003656 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003657 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003658 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003659 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3660 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003661 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003662}
3663
3664QualType
3665ASTContext::getDependentTemplateSpecializationType(
3666 ElaboratedTypeKeyword Keyword,
3667 NestedNameSpecifier *NNS,
3668 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003669 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003670 assert((!NNS || NNS->isDependent()) &&
3671 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003672
Douglas Gregorc42075a2010-02-04 18:10:26 +00003673 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003674 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003675 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003676
Craig Topper36250ad2014-05-12 05:36:57 +00003677 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003678 DependentTemplateSpecializationType *T
3679 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003680 if (T)
3681 return QualType(T, 0);
3682
John McCallc392f372010-06-11 00:33:02 +00003683 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003684
John McCallc392f372010-06-11 00:33:02 +00003685 ElaboratedTypeKeyword CanonKeyword = Keyword;
3686 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3687
3688 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003689 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003690 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003691 for (unsigned I = 0; I != NumArgs; ++I) {
3692 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3693 if (!CanonArgs[I].structurallyEquals(Args[I]))
3694 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003695 }
3696
John McCallc392f372010-06-11 00:33:02 +00003697 QualType Canon;
3698 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3699 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003700 Name,
3701 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003702
3703 // Find the insert position again.
3704 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3705 }
3706
3707 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3708 sizeof(TemplateArgument) * NumArgs),
3709 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003710 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003711 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003712 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003713 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003714 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003715}
3716
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003717QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003718 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003719 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003720 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003721
3722 assert(Pattern->containsUnexpandedParameterPack() &&
3723 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003724 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003725 PackExpansionType *T
3726 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3727 if (T)
3728 return QualType(T, 0);
3729
3730 QualType Canon;
3731 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003732 Canon = getCanonicalType(Pattern);
3733 // The canonical type might not contain an unexpanded parameter pack, if it
3734 // contains an alias template specialization which ignores one of its
3735 // parameters.
3736 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003737 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003738
Richard Smith68eea502012-07-16 00:20:35 +00003739 // Find the insert position again, in case we inserted an element into
3740 // PackExpansionTypes and invalidated our insert position.
3741 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3742 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003743 }
3744
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003745 T = new (*this, TypeAlignment)
3746 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003747 Types.push_back(T);
3748 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003749 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003750}
3751
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003752/// CmpProtocolNames - Comparison predicate for sorting protocols
3753/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003754static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3755 ObjCProtocolDecl *const *RHS) {
3756 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003757}
3758
Craig Topper1f26d5b2016-01-03 19:43:23 +00003759static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3760 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003761
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003762 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3763 return false;
3764
Craig Topper1f26d5b2016-01-03 19:43:23 +00003765 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003766 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003767 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003768 return false;
3769 return true;
3770}
3771
Craig Topper6a8c1512015-10-22 01:56:18 +00003772static void
3773SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003774 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003775 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003776
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003777 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003778 for (ObjCProtocolDecl *&P : Protocols)
3779 P = P->getCanonicalDecl();
3780
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003781 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003782 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3783 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003784}
3785
John McCall8b07ec22010-05-15 11:32:37 +00003786QualType ASTContext::getObjCObjectType(QualType BaseType,
3787 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003788 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003789 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003790 llvm::makeArrayRef(Protocols, NumProtocols),
3791 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003792}
3793
3794QualType ASTContext::getObjCObjectType(
3795 QualType baseType,
3796 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003797 ArrayRef<ObjCProtocolDecl *> protocols,
3798 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003799 // If the base type is an interface and there aren't any protocols or
3800 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003801 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3802 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003803 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003804
3805 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003806 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003807 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003808 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003809 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3810 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003811
Douglas Gregore9d95f12015-07-07 03:57:35 +00003812 // Determine the type arguments to be used for canonicalization,
3813 // which may be explicitly specified here or written on the base
3814 // type.
3815 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3816 if (effectiveTypeArgs.empty()) {
3817 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3818 effectiveTypeArgs = baseObject->getTypeArgs();
3819 }
John McCallfc93cf92009-10-22 22:37:11 +00003820
Douglas Gregore9d95f12015-07-07 03:57:35 +00003821 // Build the canonical type, which has the canonical base type and a
3822 // sorted-and-uniqued list of protocols and the type arguments
3823 // canonicalized.
3824 QualType canonical;
3825 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3826 effectiveTypeArgs.end(),
3827 [&](QualType type) {
3828 return type.isCanonical();
3829 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003830 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003831 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3832 // Determine the canonical type arguments.
3833 ArrayRef<QualType> canonTypeArgs;
3834 SmallVector<QualType, 4> canonTypeArgsVec;
3835 if (!typeArgsAreCanonical) {
3836 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3837 for (auto typeArg : effectiveTypeArgs)
3838 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3839 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003840 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003841 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003842 }
3843
Douglas Gregore9d95f12015-07-07 03:57:35 +00003844 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3845 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3846 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003847 canonProtocolsVec.append(protocols.begin(), protocols.end());
3848 SortAndUniqueProtocols(canonProtocolsVec);
3849 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003850 } else {
3851 canonProtocols = protocols;
3852 }
3853
3854 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003855 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003856
John McCallfc93cf92009-10-22 22:37:11 +00003857 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003858 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3859 }
3860
Douglas Gregore9d95f12015-07-07 03:57:35 +00003861 unsigned size = sizeof(ObjCObjectTypeImpl);
3862 size += typeArgs.size() * sizeof(QualType);
3863 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3864 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003865 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003866 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3867 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003868
3869 Types.push_back(T);
3870 ObjCObjectTypes.InsertNode(T, InsertPos);
3871 return QualType(T, 0);
3872}
3873
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003874/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3875/// protocol list adopt all protocols in QT's qualified-id protocol
3876/// list.
3877bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3878 ObjCInterfaceDecl *IC) {
3879 if (!QT->isObjCQualifiedIdType())
3880 return false;
3881
3882 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3883 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003884 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003885 if (!IC->ClassImplementsProtocol(Proto, false))
3886 return false;
3887 }
3888 return true;
3889 }
3890 return false;
3891}
3892
3893/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3894/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3895/// of protocols.
3896bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3897 ObjCInterfaceDecl *IDecl) {
3898 if (!QT->isObjCQualifiedIdType())
3899 return false;
3900 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3901 if (!OPT)
3902 return false;
3903 if (!IDecl->hasDefinition())
3904 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003905 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3906 CollectInheritedProtocols(IDecl, InheritedProtocols);
3907 if (InheritedProtocols.empty())
3908 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003909 // Check that if every protocol in list of id<plist> conforms to a protcol
3910 // of IDecl's, then bridge casting is ok.
3911 bool Conforms = false;
3912 for (auto *Proto : OPT->quals()) {
3913 Conforms = false;
3914 for (auto *PI : InheritedProtocols) {
3915 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3916 Conforms = true;
3917 break;
3918 }
3919 }
3920 if (!Conforms)
3921 break;
3922 }
3923 if (Conforms)
3924 return true;
3925
Aaron Ballman83731462014-03-17 16:14:00 +00003926 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003927 // If both the right and left sides have qualifiers.
3928 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003929 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003930 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003931 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003932 break;
3933 }
3934 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003935 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003936 }
3937 return true;
3938}
3939
John McCall8b07ec22010-05-15 11:32:37 +00003940/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3941/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003942QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003943 llvm::FoldingSetNodeID ID;
3944 ObjCObjectPointerType::Profile(ID, ObjectT);
3945
Craig Topper36250ad2014-05-12 05:36:57 +00003946 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003947 if (ObjCObjectPointerType *QT =
3948 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3949 return QualType(QT, 0);
3950
3951 // Find the canonical object type.
3952 QualType Canonical;
3953 if (!ObjectT.isCanonical()) {
3954 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3955
3956 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003957 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3958 }
3959
Douglas Gregorf85bee62010-02-08 22:59:26 +00003960 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003961 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3962 ObjCObjectPointerType *QType =
3963 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003964
Steve Narofffb4330f2009-06-17 22:40:22 +00003965 Types.push_back(QType);
3966 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003967 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003968}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003969
Douglas Gregor1c283312010-08-11 12:19:30 +00003970/// getObjCInterfaceType - Return the unique reference to the type for the
3971/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003972QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3973 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003974 if (Decl->TypeForDecl)
3975 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003976
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003977 if (PrevDecl) {
3978 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3979 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3980 return QualType(PrevDecl->TypeForDecl, 0);
3981 }
3982
Douglas Gregor7671e532011-12-16 16:34:57 +00003983 // Prefer the definition, if there is one.
3984 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3985 Decl = Def;
3986
Douglas Gregor1c283312010-08-11 12:19:30 +00003987 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3988 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3989 Decl->TypeForDecl = T;
3990 Types.push_back(T);
3991 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003992}
3993
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003994/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3995/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003996/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003997/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003998/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003999QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004000 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004001 if (tofExpr->isTypeDependent()) {
4002 llvm::FoldingSetNodeID ID;
4003 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004004
Craig Topper36250ad2014-05-12 05:36:57 +00004005 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004006 DependentTypeOfExprType *Canon
4007 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4008 if (Canon) {
4009 // We already have a "canonical" version of an identical, dependent
4010 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004011 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004012 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004013 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004014 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004015 Canon
4016 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004017 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4018 toe = Canon;
4019 }
4020 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004021 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004022 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004023 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004024 Types.push_back(toe);
4025 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004026}
4027
Steve Naroffa773cd52007-08-01 18:02:17 +00004028/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004029/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004030/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004031/// an issue. This doesn't affect the type checker, since it operates
4032/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004033QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004034 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004035 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004036 Types.push_back(tot);
4037 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004038}
4039
Richard Smith8eb1d322014-06-05 20:13:13 +00004040/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4041/// nodes. This would never be helpful, since each such type has its own
4042/// expression, and would not give a significant memory saving, since there
4043/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004044QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004045 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004046
4047 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004048 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004049 // unique dependent type. Two such decltype-specifiers refer to the same
4050 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004051 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004052 llvm::FoldingSetNodeID ID;
4053 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004054
Craig Topper36250ad2014-05-12 05:36:57 +00004055 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004056 DependentDecltypeType *Canon
4057 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004058 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004059 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004060 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004061 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004062 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004063 dt = new (*this, TypeAlignment)
4064 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004065 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004066 dt = new (*this, TypeAlignment)
4067 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004068 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004069 Types.push_back(dt);
4070 return QualType(dt, 0);
4071}
4072
Alexis Hunte852b102011-05-24 22:41:36 +00004073/// getUnaryTransformationType - We don't unique these, since the memory
4074/// savings are minimal and these are rare.
4075QualType ASTContext::getUnaryTransformType(QualType BaseType,
4076 QualType UnderlyingType,
4077 UnaryTransformType::UTTKind Kind)
4078 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004079 UnaryTransformType *ut = nullptr;
4080
4081 if (BaseType->isDependentType()) {
4082 // Look in the folding set for an existing type.
4083 llvm::FoldingSetNodeID ID;
4084 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4085
4086 void *InsertPos = nullptr;
4087 DependentUnaryTransformType *Canon
4088 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4089
4090 if (!Canon) {
4091 // Build a new, canonical __underlying_type(type) type.
4092 Canon = new (*this, TypeAlignment)
4093 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4094 Kind);
4095 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4096 }
4097 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4098 QualType(), Kind,
4099 QualType(Canon, 0));
4100 } else {
4101 QualType CanonType = getCanonicalType(UnderlyingType);
4102 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4103 UnderlyingType, Kind,
4104 CanonType);
4105 }
4106 Types.push_back(ut);
4107 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004108}
4109
Richard Smith2a7d4812013-05-04 07:00:32 +00004110/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4111/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4112/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004113QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004114 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004115 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004116 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004117
Richard Smith2a7d4812013-05-04 07:00:32 +00004118 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004119 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004120 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004121 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004122 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4123 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004124
Richard Smith74aeef52013-04-26 16:15:35 +00004125 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004126 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004127 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004128 Types.push_back(AT);
4129 if (InsertPos)
4130 AutoTypes.InsertNode(AT, InsertPos);
4131 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004132}
4133
Eli Friedman0dfb8892011-10-06 23:00:33 +00004134/// getAtomicType - Return the uniqued reference to the atomic type for
4135/// the given value type.
4136QualType ASTContext::getAtomicType(QualType T) const {
4137 // Unique pointers, to guarantee there is only one pointer of a particular
4138 // structure.
4139 llvm::FoldingSetNodeID ID;
4140 AtomicType::Profile(ID, T);
4141
Craig Topper36250ad2014-05-12 05:36:57 +00004142 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004143 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4144 return QualType(AT, 0);
4145
4146 // If the atomic value type isn't canonical, this won't be a canonical type
4147 // either, so fill in the canonical type field.
4148 QualType Canonical;
4149 if (!T.isCanonical()) {
4150 Canonical = getAtomicType(getCanonicalType(T));
4151
4152 // Get the new insert position for the node we care about.
4153 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004154 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004155 }
4156 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4157 Types.push_back(New);
4158 AtomicTypes.InsertNode(New, InsertPos);
4159 return QualType(New, 0);
4160}
4161
Richard Smith02e85f32011-04-14 22:09:26 +00004162/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4163QualType ASTContext::getAutoDeductType() const {
4164 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004165 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004166 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004167 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004168 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004169 return AutoDeductTy;
4170}
4171
4172/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4173QualType ASTContext::getAutoRRefDeductType() const {
4174 if (AutoRRefDeductTy.isNull())
4175 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4176 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4177 return AutoRRefDeductTy;
4178}
4179
Chris Lattnerfb072462007-01-23 05:45:31 +00004180/// getTagDeclType - Return the unique reference to the type for the
4181/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004182QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004183 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004184 // FIXME: What is the design on getTagDeclType when it requires casting
4185 // away const? mutable?
4186 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004187}
4188
Mike Stump11289f42009-09-09 15:08:12 +00004189/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4190/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4191/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004192CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004193 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004194}
Chris Lattnerfb072462007-01-23 05:45:31 +00004195
Hans Wennborg27541db2011-10-27 08:29:09 +00004196/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4197CanQualType ASTContext::getIntMaxType() const {
4198 return getFromTargetType(Target->getIntMaxType());
4199}
4200
4201/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4202CanQualType ASTContext::getUIntMaxType() const {
4203 return getFromTargetType(Target->getUIntMaxType());
4204}
4205
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004206/// getSignedWCharType - Return the type of "signed wchar_t".
4207/// Used when in C++, as a GCC extension.
4208QualType ASTContext::getSignedWCharType() const {
4209 // FIXME: derive from "Target" ?
4210 return WCharTy;
4211}
4212
4213/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4214/// Used when in C++, as a GCC extension.
4215QualType ASTContext::getUnsignedWCharType() const {
4216 // FIXME: derive from "Target" ?
4217 return UnsignedIntTy;
4218}
4219
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004220QualType ASTContext::getIntPtrType() const {
4221 return getFromTargetType(Target->getIntPtrType());
4222}
4223
4224QualType ASTContext::getUIntPtrType() const {
4225 return getCorrespondingUnsignedType(getIntPtrType());
4226}
4227
Hans Wennborg27541db2011-10-27 08:29:09 +00004228/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004229/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4230QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004231 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004232}
4233
Eli Friedman4e91899e2012-11-27 02:58:24 +00004234/// \brief Return the unique type for "pid_t" defined in
4235/// <sys/types.h>. We need this to compute the correct type for vfork().
4236QualType ASTContext::getProcessIDType() const {
4237 return getFromTargetType(Target->getProcessIDType());
4238}
4239
Chris Lattnera21ad802008-04-02 05:18:44 +00004240//===----------------------------------------------------------------------===//
4241// Type Operators
4242//===----------------------------------------------------------------------===//
4243
Jay Foad39c79802011-01-12 09:06:06 +00004244CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004245 // Push qualifiers into arrays, and then discard any remaining
4246 // qualifiers.
4247 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004248 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004249 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004250 QualType Result;
4251 if (isa<ArrayType>(Ty)) {
4252 Result = getArrayDecayedType(QualType(Ty,0));
4253 } else if (isa<FunctionType>(Ty)) {
4254 Result = getPointerType(QualType(Ty, 0));
4255 } else {
4256 Result = QualType(Ty, 0);
4257 }
4258
4259 return CanQualType::CreateUnsafe(Result);
4260}
4261
John McCall6c9dd522011-01-18 07:41:22 +00004262QualType ASTContext::getUnqualifiedArrayType(QualType type,
4263 Qualifiers &quals) {
4264 SplitQualType splitType = type.getSplitUnqualifiedType();
4265
4266 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4267 // the unqualified desugared type and then drops it on the floor.
4268 // We then have to strip that sugar back off with
4269 // getUnqualifiedDesugaredType(), which is silly.
4270 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004271 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004272
4273 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004274 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004275 quals = splitType.Quals;
4276 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004277 }
4278
John McCall6c9dd522011-01-18 07:41:22 +00004279 // Otherwise, recurse on the array's element type.
4280 QualType elementType = AT->getElementType();
4281 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4282
4283 // If that didn't change the element type, AT has no qualifiers, so we
4284 // can just use the results in splitType.
4285 if (elementType == unqualElementType) {
4286 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004287 quals = splitType.Quals;
4288 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004289 }
4290
4291 // Otherwise, add in the qualifiers from the outermost type, then
4292 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004293 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004294
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004295 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004296 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004297 CAT->getSizeModifier(), 0);
4298 }
4299
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004300 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004301 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004302 }
4303
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004304 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004305 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004306 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004307 VAT->getSizeModifier(),
4308 VAT->getIndexTypeCVRQualifiers(),
4309 VAT->getBracketsRange());
4310 }
4311
4312 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004313 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004314 DSAT->getSizeModifier(), 0,
4315 SourceRange());
4316}
4317
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004318/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4319/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4320/// they point to and return true. If T1 and T2 aren't pointer types
4321/// or pointer-to-member types, or if they are not similar at this
4322/// level, returns false and leaves T1 and T2 unchanged. Top-level
4323/// qualifiers on T1 and T2 are ignored. This function will typically
4324/// be called in a loop that successively "unwraps" pointer and
4325/// pointer-to-member types to compare them at each level.
4326bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4327 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4328 *T2PtrType = T2->getAs<PointerType>();
4329 if (T1PtrType && T2PtrType) {
4330 T1 = T1PtrType->getPointeeType();
4331 T2 = T2PtrType->getPointeeType();
4332 return true;
4333 }
4334
4335 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4336 *T2MPType = T2->getAs<MemberPointerType>();
4337 if (T1MPType && T2MPType &&
4338 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4339 QualType(T2MPType->getClass(), 0))) {
4340 T1 = T1MPType->getPointeeType();
4341 T2 = T2MPType->getPointeeType();
4342 return true;
4343 }
4344
David Blaikiebbafb8a2012-03-11 07:00:24 +00004345 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004346 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4347 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4348 if (T1OPType && T2OPType) {
4349 T1 = T1OPType->getPointeeType();
4350 T2 = T2OPType->getPointeeType();
4351 return true;
4352 }
4353 }
4354
4355 // FIXME: Block pointers, too?
4356
4357 return false;
4358}
4359
Jay Foad39c79802011-01-12 09:06:06 +00004360DeclarationNameInfo
4361ASTContext::getNameForTemplate(TemplateName Name,
4362 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004363 switch (Name.getKind()) {
4364 case TemplateName::QualifiedTemplate:
4365 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004366 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004367 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4368 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004369
John McCalld9dfe3a2011-06-30 08:33:18 +00004370 case TemplateName::OverloadedTemplate: {
4371 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4372 // DNInfo work in progress: CHECKME: what about DNLoc?
4373 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4374 }
4375
4376 case TemplateName::DependentTemplate: {
4377 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004378 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004379 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004380 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4381 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004382 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004383 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4384 // DNInfo work in progress: FIXME: source locations?
4385 DeclarationNameLoc DNLoc;
4386 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4387 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4388 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004389 }
4390 }
4391
John McCalld9dfe3a2011-06-30 08:33:18 +00004392 case TemplateName::SubstTemplateTemplateParm: {
4393 SubstTemplateTemplateParmStorage *subst
4394 = Name.getAsSubstTemplateTemplateParm();
4395 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4396 NameLoc);
4397 }
4398
4399 case TemplateName::SubstTemplateTemplateParmPack: {
4400 SubstTemplateTemplateParmPackStorage *subst
4401 = Name.getAsSubstTemplateTemplateParmPack();
4402 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4403 NameLoc);
4404 }
4405 }
4406
4407 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004408}
4409
Jay Foad39c79802011-01-12 09:06:06 +00004410TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004411 switch (Name.getKind()) {
4412 case TemplateName::QualifiedTemplate:
4413 case TemplateName::Template: {
4414 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004415 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004416 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004417 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4418
4419 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004420 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004421 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004422
John McCalld9dfe3a2011-06-30 08:33:18 +00004423 case TemplateName::OverloadedTemplate:
4424 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004425
John McCalld9dfe3a2011-06-30 08:33:18 +00004426 case TemplateName::DependentTemplate: {
4427 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4428 assert(DTN && "Non-dependent template names must refer to template decls.");
4429 return DTN->CanonicalTemplateName;
4430 }
4431
4432 case TemplateName::SubstTemplateTemplateParm: {
4433 SubstTemplateTemplateParmStorage *subst
4434 = Name.getAsSubstTemplateTemplateParm();
4435 return getCanonicalTemplateName(subst->getReplacement());
4436 }
4437
4438 case TemplateName::SubstTemplateTemplateParmPack: {
4439 SubstTemplateTemplateParmPackStorage *subst
4440 = Name.getAsSubstTemplateTemplateParmPack();
4441 TemplateTemplateParmDecl *canonParameter
4442 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4443 TemplateArgument canonArgPack
4444 = getCanonicalTemplateArgument(subst->getArgumentPack());
4445 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4446 }
4447 }
4448
4449 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004450}
4451
Douglas Gregoradee3e32009-11-11 23:06:43 +00004452bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4453 X = getCanonicalTemplateName(X);
4454 Y = getCanonicalTemplateName(Y);
4455 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4456}
4457
Mike Stump11289f42009-09-09 15:08:12 +00004458TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004459ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004460 switch (Arg.getKind()) {
4461 case TemplateArgument::Null:
4462 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004463
Douglas Gregora8e02e72009-07-28 23:00:59 +00004464 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004465 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004466
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004467 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004468 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004469 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004470 }
Mike Stump11289f42009-09-09 15:08:12 +00004471
Eli Friedmanb826a002012-09-26 02:36:12 +00004472 case TemplateArgument::NullPtr:
4473 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4474 /*isNullPtr*/true);
4475
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004476 case TemplateArgument::Template:
4477 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004478
4479 case TemplateArgument::TemplateExpansion:
4480 return TemplateArgument(getCanonicalTemplateName(
4481 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004482 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004483
Douglas Gregora8e02e72009-07-28 23:00:59 +00004484 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004485 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004486
Douglas Gregora8e02e72009-07-28 23:00:59 +00004487 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004488 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004489
Douglas Gregora8e02e72009-07-28 23:00:59 +00004490 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004491 if (Arg.pack_size() == 0)
4492 return Arg;
4493
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004494 TemplateArgument *CanonArgs
4495 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004496 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004497 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004498 AEnd = Arg.pack_end();
4499 A != AEnd; (void)++A, ++Idx)
4500 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004501
Benjamin Kramercce63472015-08-05 09:40:22 +00004502 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004503 }
4504 }
4505
4506 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004507 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004508}
4509
Douglas Gregor333489b2009-03-27 23:10:48 +00004510NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004511ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004512 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004513 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004514
4515 switch (NNS->getKind()) {
4516 case NestedNameSpecifier::Identifier:
4517 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004518 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004519 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4520 NNS->getAsIdentifier());
4521
4522 case NestedNameSpecifier::Namespace:
4523 // A namespace is canonical; build a nested-name-specifier with
4524 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004525 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004526 NNS->getAsNamespace()->getOriginalNamespace());
4527
4528 case NestedNameSpecifier::NamespaceAlias:
4529 // A namespace is canonical; build a nested-name-specifier with
4530 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004531 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004532 NNS->getAsNamespaceAlias()->getNamespace()
4533 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004534
4535 case NestedNameSpecifier::TypeSpec:
4536 case NestedNameSpecifier::TypeSpecWithTemplate: {
4537 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004538
4539 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4540 // break it apart into its prefix and identifier, then reconsititute those
4541 // as the canonical nested-name-specifier. This is required to canonicalize
4542 // a dependent nested-name-specifier involving typedefs of dependent-name
4543 // types, e.g.,
4544 // typedef typename T::type T1;
4545 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004546 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4547 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004548 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004549
Eli Friedman5358a0a2012-03-03 04:09:56 +00004550 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4551 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4552 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004553 return NestedNameSpecifier::Create(*this, nullptr, false,
4554 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004555 }
4556
4557 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004558 case NestedNameSpecifier::Super:
4559 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004560 return NNS;
4561 }
4562
David Blaikie8a40f702012-01-17 06:56:22 +00004563 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004564}
4565
Jay Foad39c79802011-01-12 09:06:06 +00004566const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004567 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004568 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004569 // Handle the common positive case fast.
4570 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4571 return AT;
4572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
John McCall8ccfcb52009-09-24 19:53:00 +00004574 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004575 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004576 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004577
John McCall8ccfcb52009-09-24 19:53:00 +00004578 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004579 // implements C99 6.7.3p8: "If the specification of an array type includes
4580 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004581
Chris Lattner7adf0762008-08-04 07:31:14 +00004582 // If we get here, we either have type qualifiers on the type, or we have
4583 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004584 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004585
John McCall33ddac02011-01-19 10:06:00 +00004586 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004587 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004588
Chris Lattner7adf0762008-08-04 07:31:14 +00004589 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004590 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004591 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004592 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004593
Chris Lattner7adf0762008-08-04 07:31:14 +00004594 // Otherwise, we have an array and we have qualifiers on it. Push the
4595 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004596 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004597
Chris Lattner7adf0762008-08-04 07:31:14 +00004598 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4599 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4600 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004601 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004602 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4603 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4604 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004605 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004606
Mike Stump11289f42009-09-09 15:08:12 +00004607 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004608 = dyn_cast<DependentSizedArrayType>(ATy))
4609 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004610 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004611 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004612 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004613 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004614 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004615
Chris Lattner7adf0762008-08-04 07:31:14 +00004616 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004617 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004618 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004619 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004620 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004621 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004622}
4623
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004624QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004625 if (T->isArrayType() || T->isFunctionType())
4626 return getDecayedType(T);
4627 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004628}
4629
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004630QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004631 T = getVariableArrayDecayedType(T);
4632 T = getAdjustedParameterType(T);
4633 return T.getUnqualifiedType();
4634}
4635
David Majnemerd09a51c2015-03-03 01:50:05 +00004636QualType ASTContext::getExceptionObjectType(QualType T) const {
4637 // C++ [except.throw]p3:
4638 // A throw-expression initializes a temporary object, called the exception
4639 // object, the type of which is determined by removing any top-level
4640 // cv-qualifiers from the static type of the operand of throw and adjusting
4641 // the type from "array of T" or "function returning T" to "pointer to T"
4642 // or "pointer to function returning T", [...]
4643 T = getVariableArrayDecayedType(T);
4644 if (T->isArrayType() || T->isFunctionType())
4645 T = getDecayedType(T);
4646 return T.getUnqualifiedType();
4647}
4648
Chris Lattnera21ad802008-04-02 05:18:44 +00004649/// getArrayDecayedType - Return the properly qualified result of decaying the
4650/// specified array type to a pointer. This operation is non-trivial when
4651/// handling typedefs etc. The canonical type of "T" must be an array type,
4652/// this returns a pointer to a properly qualified element of the array.
4653///
4654/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004655QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004656 // Get the element type with 'getAsArrayType' so that we don't lose any
4657 // typedefs in the element type of the array. This also handles propagation
4658 // of type qualifiers from the array type into the element type if present
4659 // (C99 6.7.3p8).
4660 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4661 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004662
Chris Lattner7adf0762008-08-04 07:31:14 +00004663 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004664
4665 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004666 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004667}
4668
John McCall33ddac02011-01-19 10:06:00 +00004669QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4670 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004671}
4672
John McCall33ddac02011-01-19 10:06:00 +00004673QualType ASTContext::getBaseElementType(QualType type) const {
4674 Qualifiers qs;
4675 while (true) {
4676 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004677 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004678 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004679
John McCall33ddac02011-01-19 10:06:00 +00004680 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004681 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004682 }
Mike Stump11289f42009-09-09 15:08:12 +00004683
John McCall33ddac02011-01-19 10:06:00 +00004684 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004685}
4686
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004687/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004688uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004689ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4690 uint64_t ElementCount = 1;
4691 do {
4692 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004693 CA = dyn_cast_or_null<ConstantArrayType>(
4694 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004695 } while (CA);
4696 return ElementCount;
4697}
4698
Steve Naroff0af91202007-04-27 21:51:21 +00004699/// getFloatingRank - Return a relative rank for floating point types.
4700/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004701static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004702 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004703 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004704
John McCall9dd450b2009-09-21 23:43:11 +00004705 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4706 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004707 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004708 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004709 case BuiltinType::Float: return FloatRank;
4710 case BuiltinType::Double: return DoubleRank;
4711 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004712 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00004713 }
4714}
4715
Mike Stump11289f42009-09-09 15:08:12 +00004716/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4717/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004718/// 'typeDomain' is a real floating point or complex type.
4719/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004720QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4721 QualType Domain) const {
4722 FloatingRank EltRank = getFloatingRank(Size);
4723 if (Domain->isComplexType()) {
4724 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004725 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004726 case FloatRank: return FloatComplexTy;
4727 case DoubleRank: return DoubleComplexTy;
4728 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004729 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004730 }
Steve Naroff0af91202007-04-27 21:51:21 +00004731 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004732
4733 assert(Domain->isRealFloatingType() && "Unknown domain!");
4734 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004735 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004736 case FloatRank: return FloatTy;
4737 case DoubleRank: return DoubleTy;
4738 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004739 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00004740 }
David Blaikief47fa302012-01-17 02:30:50 +00004741 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004742}
4743
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004744/// getFloatingTypeOrder - Compare the rank of the two specified floating
4745/// point types, ignoring the domain of the type (i.e. 'double' ==
4746/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004747/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004748int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004749 FloatingRank LHSR = getFloatingRank(LHS);
4750 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004751
Chris Lattnerb90739d2008-04-06 23:38:49 +00004752 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004753 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004754 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004755 return 1;
4756 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004757}
4758
Chris Lattner76a00cf2008-04-06 22:59:24 +00004759/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4760/// routine will assert if passed a built-in type that isn't an integer or enum,
4761/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004762unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004763 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004764
Chris Lattner76a00cf2008-04-06 22:59:24 +00004765 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004766 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004767 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004768 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004769 case BuiltinType::Char_S:
4770 case BuiltinType::Char_U:
4771 case BuiltinType::SChar:
4772 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004773 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004774 case BuiltinType::Short:
4775 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004776 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004777 case BuiltinType::Int:
4778 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004779 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004780 case BuiltinType::Long:
4781 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004782 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004783 case BuiltinType::LongLong:
4784 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004785 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004786 case BuiltinType::Int128:
4787 case BuiltinType::UInt128:
4788 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004789 }
4790}
4791
Eli Friedman629ffb92009-08-20 04:21:42 +00004792/// \brief Whether this is a promotable bitfield reference according
4793/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4794///
4795/// \returns the type this bit-field will promote to, or NULL if no
4796/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004797QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004798 if (E->isTypeDependent() || E->isValueDependent())
4799 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004800
4801 // FIXME: We should not do this unless E->refersToBitField() is true. This
4802 // matters in C where getSourceBitField() will find bit-fields for various
4803 // cases where the source expression is not a bit-field designator.
4804
John McCalld25db7e2013-05-06 21:39:12 +00004805 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004806 if (!Field)
4807 return QualType();
4808
4809 QualType FT = Field->getType();
4810
Richard Smithcaf33902011-10-10 18:28:20 +00004811 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004812 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004813 // C++ [conv.prom]p5:
4814 // A prvalue for an integral bit-field can be converted to a prvalue of type
4815 // int if int can represent all the values of the bit-field; otherwise, it
4816 // can be converted to unsigned int if unsigned int can represent all the
4817 // values of the bit-field. If the bit-field is larger yet, no integral
4818 // promotion applies to it.
4819 // C11 6.3.1.1/2:
4820 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4821 // If an int can represent all values of the original type (as restricted by
4822 // the width, for a bit-field), the value is converted to an int; otherwise,
4823 // it is converted to an unsigned int.
4824 //
4825 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4826 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004827 if (BitWidth < IntSize)
4828 return IntTy;
4829
4830 if (BitWidth == IntSize)
4831 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4832
4833 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004834 // like the base type. GCC has some weird bugs in this area that we
4835 // deliberately do not follow (GCC follows a pre-standard resolution to
4836 // C's DR315 which treats bit-width as being part of the type, and this leaks
4837 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004838 return QualType();
4839}
4840
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004841/// getPromotedIntegerType - Returns the type that Promotable will
4842/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4843/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004844QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004845 assert(!Promotable.isNull());
4846 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004847 if (const EnumType *ET = Promotable->getAs<EnumType>())
4848 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004849
4850 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4851 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4852 // (3.9.1) can be converted to a prvalue of the first of the following
4853 // types that can represent all the values of its underlying type:
4854 // int, unsigned int, long int, unsigned long int, long long int, or
4855 // unsigned long long int [...]
4856 // FIXME: Is there some better way to compute this?
4857 if (BT->getKind() == BuiltinType::WChar_S ||
4858 BT->getKind() == BuiltinType::WChar_U ||
4859 BT->getKind() == BuiltinType::Char16 ||
4860 BT->getKind() == BuiltinType::Char32) {
4861 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4862 uint64_t FromSize = getTypeSize(BT);
4863 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4864 LongLongTy, UnsignedLongLongTy };
4865 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4866 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4867 if (FromSize < ToSize ||
4868 (FromSize == ToSize &&
4869 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4870 return PromoteTypes[Idx];
4871 }
4872 llvm_unreachable("char type should fit into long long");
4873 }
4874 }
4875
4876 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004877 if (Promotable->isSignedIntegerType())
4878 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004879 uint64_t PromotableSize = getIntWidth(Promotable);
4880 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004881 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4882 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4883}
4884
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004885/// \brief Recurses in pointer/array types until it finds an objc retainable
4886/// type and returns its ownership.
4887Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4888 while (!T.isNull()) {
4889 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4890 return T.getObjCLifetime();
4891 if (T->isArrayType())
4892 T = getBaseElementType(T);
4893 else if (const PointerType *PT = T->getAs<PointerType>())
4894 T = PT->getPointeeType();
4895 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004896 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004897 else
4898 break;
4899 }
4900
4901 return Qualifiers::OCL_None;
4902}
4903
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004904static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4905 // Incomplete enum types are not treated as integer types.
4906 // FIXME: In C++, enum types are never integer types.
4907 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4908 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004909 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004910}
4911
Mike Stump11289f42009-09-09 15:08:12 +00004912/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004913/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004914/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004915int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004916 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4917 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004918
4919 // Unwrap enums to their underlying type.
4920 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4921 LHSC = getIntegerTypeForEnum(ET);
4922 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4923 RHSC = getIntegerTypeForEnum(ET);
4924
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004925 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004926
Chris Lattner76a00cf2008-04-06 22:59:24 +00004927 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4928 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004929
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004930 unsigned LHSRank = getIntegerRank(LHSC);
4931 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004932
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004933 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4934 if (LHSRank == RHSRank) return 0;
4935 return LHSRank > RHSRank ? 1 : -1;
4936 }
Mike Stump11289f42009-09-09 15:08:12 +00004937
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004938 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4939 if (LHSUnsigned) {
4940 // If the unsigned [LHS] type is larger, return it.
4941 if (LHSRank >= RHSRank)
4942 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004943
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004944 // If the signed type can represent all values of the unsigned type, it
4945 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004946 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004947 return -1;
4948 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004949
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004950 // If the unsigned [RHS] type is larger, return it.
4951 if (RHSRank >= LHSRank)
4952 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004953
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004954 // If the signed type can represent all values of the unsigned type, it
4955 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004956 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004957 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004958}
Anders Carlsson98f07902007-08-17 05:31:46 +00004959
Ben Langmuirf5416742016-02-04 00:55:24 +00004960TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004961 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004962 assert(!CFConstantStringTagDecl &&
4963 "tag and typedef should be initialized together");
4964 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4965 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004966
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004967 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00004968 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00004969
Anders Carlsson98f07902007-08-17 05:31:46 +00004970 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004971 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004972 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004973 // int flags;
4974 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004975 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00004976 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004977 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004978 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00004979 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004980 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004981 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00004982
Anders Carlsson98f07902007-08-17 05:31:46 +00004983 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004984 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004985 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004986 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00004987 SourceLocation(),
4988 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00004989 FieldTypes[i], /*TInfo=*/nullptr,
4990 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004991 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004992 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004993 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00004994 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004995 }
4996
Ben Langmuirf5416742016-02-04 00:55:24 +00004997 CFConstantStringTagDecl->completeDefinition();
4998 // This type is designed to be compatible with NSConstantString, but cannot
4999 // use the same name, since NSConstantString is an interface.
5000 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5001 CFConstantStringTypeDecl =
5002 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005003 }
Mike Stump11289f42009-09-09 15:08:12 +00005004
Quentin Colombet043406b2016-02-03 22:41:00 +00005005 return CFConstantStringTypeDecl;
5006}
5007
Ben Langmuirf5416742016-02-04 00:55:24 +00005008RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5009 if (!CFConstantStringTagDecl)
5010 getCFConstantStringDecl(); // Build the tag and the typedef.
5011 return CFConstantStringTagDecl;
5012}
5013
Quentin Colombet043406b2016-02-03 22:41:00 +00005014// getCFConstantStringType - Return the type used for constant CFStrings.
5015QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005016 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005017}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005018
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005019QualType ASTContext::getObjCSuperType() const {
5020 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005021 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005022 TUDecl->addDecl(ObjCSuperTypeDecl);
5023 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5024 }
5025 return ObjCSuperType;
5026}
5027
Douglas Gregor512b0772009-04-23 22:29:11 +00005028void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005029 const TypedefType *TD = T->getAs<TypedefType>();
5030 assert(TD && "Invalid CFConstantStringType");
5031 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5032 auto TagType =
5033 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5034 assert(TagType && "Invalid CFConstantStringType");
5035 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005036}
5037
Jay Foad39c79802011-01-12 09:06:06 +00005038QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005039 if (BlockDescriptorType)
5040 return getTagDeclType(BlockDescriptorType);
5041
Alp Toker2dea15b2013-12-17 01:22:38 +00005042 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005043 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005044 RD = buildImplicitRecord("__block_descriptor");
5045 RD->startDefinition();
5046
Mike Stumpd0153282009-10-20 02:12:22 +00005047 QualType FieldTypes[] = {
5048 UnsignedLongTy,
5049 UnsignedLongTy,
5050 };
5051
Craig Topperd6d31ac2013-07-15 08:24:27 +00005052 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005053 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005054 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005055 };
5056
5057 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005058 FieldDecl *Field = FieldDecl::Create(
5059 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005060 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5061 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005062 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005063 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005064 }
5065
Alp Toker2dea15b2013-12-17 01:22:38 +00005066 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005067
Alp Toker2dea15b2013-12-17 01:22:38 +00005068 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005069
5070 return getTagDeclType(BlockDescriptorType);
5071}
5072
Jay Foad39c79802011-01-12 09:06:06 +00005073QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005074 if (BlockDescriptorExtendedType)
5075 return getTagDeclType(BlockDescriptorExtendedType);
5076
Alp Toker2dea15b2013-12-17 01:22:38 +00005077 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005078 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005079 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5080 RD->startDefinition();
5081
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005082 QualType FieldTypes[] = {
5083 UnsignedLongTy,
5084 UnsignedLongTy,
5085 getPointerType(VoidPtrTy),
5086 getPointerType(VoidPtrTy)
5087 };
5088
Craig Topperd6d31ac2013-07-15 08:24:27 +00005089 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005090 "reserved",
5091 "Size",
5092 "CopyFuncPtr",
5093 "DestroyFuncPtr"
5094 };
5095
5096 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005097 FieldDecl *Field = FieldDecl::Create(
5098 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005099 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5100 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005101 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005102 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005103 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005104 }
5105
Alp Toker2dea15b2013-12-17 01:22:38 +00005106 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005107
Alp Toker2dea15b2013-12-17 01:22:38 +00005108 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005109 return getTagDeclType(BlockDescriptorExtendedType);
5110}
5111
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005112/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5113/// requires copy/dispose. Note that this must match the logic
5114/// in buildByrefHelpers.
5115bool ASTContext::BlockRequiresCopying(QualType Ty,
5116 const VarDecl *D) {
5117 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5118 const Expr *copyExpr = getBlockVarCopyInits(D);
5119 if (!copyExpr && record->hasTrivialDestructor()) return false;
5120
Mike Stump94967902009-10-21 18:16:27 +00005121 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005122 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005123
5124 if (!Ty->isObjCRetainableType()) return false;
5125
5126 Qualifiers qs = Ty.getQualifiers();
5127
5128 // If we have lifetime, that dominates.
5129 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005130 switch (lifetime) {
5131 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5132
5133 // These are just bits as far as the runtime is concerned.
5134 case Qualifiers::OCL_ExplicitNone:
5135 case Qualifiers::OCL_Autoreleasing:
5136 return false;
5137
5138 // Tell the runtime that this is ARC __weak, called by the
5139 // byref routines.
5140 case Qualifiers::OCL_Weak:
5141 // ARC __strong __block variables need to be retained.
5142 case Qualifiers::OCL_Strong:
5143 return true;
5144 }
5145 llvm_unreachable("fell out of lifetime switch!");
5146 }
5147 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5148 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005149}
5150
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005151bool ASTContext::getByrefLifetime(QualType Ty,
5152 Qualifiers::ObjCLifetime &LifeTime,
5153 bool &HasByrefExtendedLayout) const {
5154
5155 if (!getLangOpts().ObjC1 ||
5156 getLangOpts().getGC() != LangOptions::NonGC)
5157 return false;
5158
5159 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005160 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005161 HasByrefExtendedLayout = true;
5162 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005163 } else if ((LifeTime = Ty.getObjCLifetime())) {
5164 // Honor the ARC qualifiers.
5165 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5166 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005167 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005168 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005169 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005170 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005171 return true;
5172}
5173
Douglas Gregorbab8a962011-09-08 01:46:34 +00005174TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5175 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005176 ObjCInstanceTypeDecl =
5177 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005178 return ObjCInstanceTypeDecl;
5179}
5180
Anders Carlsson18acd442007-10-29 06:33:42 +00005181// This returns true if a type has been typedefed to BOOL:
5182// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005183static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005184 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005185 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5186 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005187
Anders Carlssond8499822007-10-29 05:01:08 +00005188 return false;
5189}
5190
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005191/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005192/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005193CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005194 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5195 return CharUnits::Zero();
5196
Ken Dyck40775002010-01-11 17:06:35 +00005197 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005198
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005199 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005200 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005201 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005202 // Treat arrays as pointers, since that's how they're passed in.
5203 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005204 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005205 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005206}
5207
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005208bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005209 return getTargetInfo().getCXXABI().isMicrosoft() &&
5210 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005211 VD->getType()->isIntegralOrEnumerationType() &&
5212 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005213}
5214
Richard Smithd9b90092016-07-02 01:32:16 +00005215ASTContext::InlineVariableDefinitionKind
5216ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5217 if (!VD->isInline())
5218 return InlineVariableDefinitionKind::None;
5219
5220 // In almost all cases, it's a weak definition.
5221 auto *First = VD->getFirstDecl();
5222 if (!First->isConstexpr() || First->isInlineSpecified() ||
5223 !VD->isStaticDataMember())
5224 return InlineVariableDefinitionKind::Weak;
5225
5226 // If there's a file-context declaration in this translation unit, it's a
5227 // non-discardable definition.
5228 for (auto *D : VD->redecls())
5229 if (D->getLexicalDeclContext()->isFileContext())
5230 return InlineVariableDefinitionKind::Strong;
5231
5232 // If we've not seen one yet, we don't know.
5233 return InlineVariableDefinitionKind::WeakUnknown;
5234}
5235
Ken Dyck40775002010-01-11 17:06:35 +00005236static inline
5237std::string charUnitsToString(const CharUnits &CU) {
5238 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005239}
5240
John McCall351762c2011-02-07 10:33:21 +00005241/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005242/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005243std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5244 std::string S;
5245
David Chisnall950a9512009-11-17 19:33:30 +00005246 const BlockDecl *Decl = Expr->getBlockDecl();
5247 QualType BlockTy =
5248 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5249 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005250 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005251 getObjCEncodingForMethodParameter(
5252 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5253 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005254 else
Alp Toker314cc812014-01-25 16:55:45 +00005255 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005256 // Compute size of all parameters.
5257 // Start with computing size of a pointer in number of bytes.
5258 // FIXME: There might(should) be a better way of doing this computation!
5259 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005260 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5261 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005262 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005263 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005264 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005265 if (sz.isZero())
5266 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005267 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005268 ParmOffset += sz;
5269 }
5270 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005271 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005272 // Block pointer and offset.
5273 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005274
5275 // Argument types.
5276 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005277 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005278 QualType PType = PVDecl->getOriginalType();
5279 if (const ArrayType *AT =
5280 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5281 // Use array's original type only if it has known number of
5282 // elements.
5283 if (!isa<ConstantArrayType>(AT))
5284 PType = PVDecl->getType();
5285 } else if (PType->isFunctionType())
5286 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005287 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005288 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5289 S, true /*Extended*/);
5290 else
5291 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005292 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005293 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005294 }
John McCall351762c2011-02-07 10:33:21 +00005295
5296 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005297}
5298
Douglas Gregora9d84932011-05-27 01:19:52 +00005299bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005300 std::string& S) {
5301 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005302 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005303 CharUnits ParmOffset;
5304 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005305 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005306 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005307 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005308 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005309 continue;
5310
David Chisnall50e4eba2010-12-30 14:05:53 +00005311 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005312 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005313 ParmOffset += sz;
5314 }
5315 S += charUnitsToString(ParmOffset);
5316 ParmOffset = CharUnits::Zero();
5317
5318 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005319 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005320 QualType PType = PVDecl->getOriginalType();
5321 if (const ArrayType *AT =
5322 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5323 // Use array's original type only if it has known number of
5324 // elements.
5325 if (!isa<ConstantArrayType>(AT))
5326 PType = PVDecl->getType();
5327 } else if (PType->isFunctionType())
5328 PType = PVDecl->getType();
5329 getObjCEncodingForType(PType, S);
5330 S += charUnitsToString(ParmOffset);
5331 ParmOffset += getObjCEncodingTypeSize(PType);
5332 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005333
5334 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005335}
5336
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005337/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5338/// method parameter or return type. If Extended, include class names and
5339/// block object types.
5340void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5341 QualType T, std::string& S,
5342 bool Extended) const {
5343 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5344 getObjCEncodingForTypeQualifier(QT, S);
5345 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005346 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005347 true /*OutermostType*/,
5348 false /*EncodingProperty*/,
5349 false /*StructField*/,
5350 Extended /*EncodeBlockParameters*/,
5351 Extended /*EncodeClassNames*/);
5352}
5353
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005354/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005355/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005356bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005357 std::string& S,
5358 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005359 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005360 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005361 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5362 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005363 // Compute size of all parameters.
5364 // Start with computing size of a pointer in number of bytes.
5365 // FIXME: There might(should) be a better way of doing this computation!
5366 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005367 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005368 // The first two arguments (self and _cmd) are pointers; account for
5369 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005370 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005371 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005372 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005373 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005374 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005375 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005376 continue;
5377
Ken Dyck40775002010-01-11 17:06:35 +00005378 assert (sz.isPositive() &&
5379 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005380 ParmOffset += sz;
5381 }
Ken Dyck40775002010-01-11 17:06:35 +00005382 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005383 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005384 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005385
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005386 // Argument types.
5387 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005388 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005389 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005390 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005391 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005392 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005393 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5394 // Use array's original type only if it has known number of
5395 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005396 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005397 PType = PVDecl->getType();
5398 } else if (PType->isFunctionType())
5399 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005400 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5401 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005402 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005403 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005404 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005405
5406 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005407}
5408
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005409ObjCPropertyImplDecl *
5410ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5411 const ObjCPropertyDecl *PD,
5412 const Decl *Container) const {
5413 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005414 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005415 if (const ObjCCategoryImplDecl *CID =
5416 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005417 for (auto *PID : CID->property_impls())
5418 if (PID->getPropertyDecl() == PD)
5419 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005420 } else {
5421 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5422 for (auto *PID : OID->property_impls())
5423 if (PID->getPropertyDecl() == PD)
5424 return PID;
5425 }
5426 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005427}
5428
Daniel Dunbar4932b362008-08-28 04:38:10 +00005429/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005430/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005431/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5432/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005433/// Property attributes are stored as a comma-delimited C string. The simple
5434/// attributes readonly and bycopy are encoded as single characters. The
5435/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5436/// encoded as single characters, followed by an identifier. Property types
5437/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005438/// these attributes are defined by the following enumeration:
5439/// @code
5440/// enum PropertyAttributes {
5441/// kPropertyReadOnly = 'R', // property is read-only.
5442/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5443/// kPropertyByref = '&', // property is a reference to the value last assigned
5444/// kPropertyDynamic = 'D', // property is dynamic
5445/// kPropertyGetter = 'G', // followed by getter selector name
5446/// kPropertySetter = 'S', // followed by setter selector name
5447/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005448/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005449/// kPropertyWeak = 'W' // 'weak' property
5450/// kPropertyStrong = 'P' // property GC'able
5451/// kPropertyNonAtomic = 'N' // property non-atomic
5452/// };
5453/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005454void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005455 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005456 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005457 // Collect information from the property implementation decl(s).
5458 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005459 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005460
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005461 if (ObjCPropertyImplDecl *PropertyImpDecl =
5462 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5463 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5464 Dynamic = true;
5465 else
5466 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005467 }
5468
5469 // FIXME: This is not very efficient.
5470 S = "T";
5471
5472 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005473 // GCC has some special rules regarding encoding of properties which
5474 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005475 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005476
5477 if (PD->isReadOnly()) {
5478 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005479 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5480 S += ",C";
5481 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5482 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005483 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5484 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005485 } else {
5486 switch (PD->getSetterKind()) {
5487 case ObjCPropertyDecl::Assign: break;
5488 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005489 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005490 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005491 }
5492 }
5493
5494 // It really isn't clear at all what this means, since properties
5495 // are "dynamic by default".
5496 if (Dynamic)
5497 S += ",D";
5498
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005499 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5500 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005501
Daniel Dunbar4932b362008-08-28 04:38:10 +00005502 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5503 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005504 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005505 }
5506
5507 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5508 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005509 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005510 }
5511
5512 if (SynthesizePID) {
5513 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5514 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005515 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005516 }
5517
5518 // FIXME: OBJCGC: weak & strong
5519}
5520
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005521/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005522/// Another legacy compatibility encoding: 32-bit longs are encoded as
5523/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005524/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5525///
5526void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005527 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005528 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005529 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005530 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005531 else
Jay Foad39c79802011-01-12 09:06:06 +00005532 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005533 PointeeTy = IntTy;
5534 }
5535 }
5536}
5537
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005538void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005539 const FieldDecl *Field,
5540 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005541 // We follow the behavior of gcc, expanding structures which are
5542 // directly pointed to, and expanding embedded structures. Note that
5543 // these rules are sufficient to prevent recursive encoding of the
5544 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005545 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005546 true /* outermost type */, false, false,
5547 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005548}
5549
Joe Groff98ac7d22014-07-07 22:25:15 +00005550void ASTContext::getObjCEncodingForPropertyType(QualType T,
5551 std::string& S) const {
5552 // Encode result type.
5553 // GCC has some special rules regarding encoding of properties which
5554 // closely resembles encoding of ivars.
5555 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5556 true /* outermost type */,
5557 true /* encoding property */);
5558}
5559
John McCall393a78d2012-12-20 02:45:14 +00005560static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5561 BuiltinType::Kind kind) {
5562 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005563 case BuiltinType::Void: return 'v';
5564 case BuiltinType::Bool: return 'B';
5565 case BuiltinType::Char_U:
5566 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005567 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005568 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005569 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005570 case BuiltinType::UInt: return 'I';
5571 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005572 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005573 case BuiltinType::UInt128: return 'T';
5574 case BuiltinType::ULongLong: return 'Q';
5575 case BuiltinType::Char_S:
5576 case BuiltinType::SChar: return 'c';
5577 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005578 case BuiltinType::WChar_S:
5579 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005580 case BuiltinType::Int: return 'i';
5581 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005582 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005583 case BuiltinType::LongLong: return 'q';
5584 case BuiltinType::Int128: return 't';
5585 case BuiltinType::Float: return 'f';
5586 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005587 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005588 case BuiltinType::NullPtr: return '*'; // like char*
5589
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005590 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005591 case BuiltinType::Half:
5592 // FIXME: potentially need @encodes for these!
5593 return ' ';
5594
5595 case BuiltinType::ObjCId:
5596 case BuiltinType::ObjCClass:
5597 case BuiltinType::ObjCSel:
5598 llvm_unreachable("@encoding ObjC primitive type");
5599
5600 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005601#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5602 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005603#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005604 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005605 case BuiltinType::OCLClkEvent:
5606 case BuiltinType::OCLQueue:
5607 case BuiltinType::OCLNDRange:
5608 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005609 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005610 case BuiltinType::Dependent:
5611#define BUILTIN_TYPE(KIND, ID)
5612#define PLACEHOLDER_TYPE(KIND, ID) \
5613 case BuiltinType::KIND:
5614#include "clang/AST/BuiltinTypes.def"
5615 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005616 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005617 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005618}
5619
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005620static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5621 EnumDecl *Enum = ET->getDecl();
5622
5623 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5624 if (!Enum->isFixed())
5625 return 'i';
5626
5627 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005628 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5629 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005630}
5631
Jay Foad39c79802011-01-12 09:06:06 +00005632static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005633 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005634 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005635 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005636 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5637 // The GNU runtime requires more information; bitfields are encoded as b,
5638 // then the offset (in bits) of the first element, then the type of the
5639 // bitfield, then the size in bits. For example, in this structure:
5640 //
5641 // struct
5642 // {
5643 // int integer;
5644 // int flags:2;
5645 // };
5646 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5647 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5648 // information is not especially sensible, but we're stuck with it for
5649 // compatibility with GCC, although providing it breaks anything that
5650 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005651 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005652 const RecordDecl *RD = FD->getParent();
5653 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005654 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005655 if (const EnumType *ET = T->getAs<EnumType>())
5656 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005657 else {
5658 const BuiltinType *BT = T->castAs<BuiltinType>();
5659 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5660 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005661 }
Richard Smithcaf33902011-10-10 18:28:20 +00005662 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005663}
5664
Daniel Dunbar07d07852009-10-18 21:17:35 +00005665// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005666void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5667 bool ExpandPointedToStructures,
5668 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005669 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005670 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005671 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005672 bool StructField,
5673 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005674 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005675 bool EncodePointerToObjCTypedef,
5676 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005677 CanQualType CT = getCanonicalType(T);
5678 switch (CT->getTypeClass()) {
5679 case Type::Builtin:
5680 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005681 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005682 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005683 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5684 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5685 else
5686 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005687 return;
Mike Stump11289f42009-09-09 15:08:12 +00005688
John McCall393a78d2012-12-20 02:45:14 +00005689 case Type::Complex: {
5690 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005691 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005692 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005693 return;
5694 }
John McCall393a78d2012-12-20 02:45:14 +00005695
5696 case Type::Atomic: {
5697 const AtomicType *AT = T->castAs<AtomicType>();
5698 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005699 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005700 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005701 }
John McCall393a78d2012-12-20 02:45:14 +00005702
5703 // encoding for pointer or reference types.
5704 case Type::Pointer:
5705 case Type::LValueReference:
5706 case Type::RValueReference: {
5707 QualType PointeeTy;
5708 if (isa<PointerType>(CT)) {
5709 const PointerType *PT = T->castAs<PointerType>();
5710 if (PT->isObjCSelType()) {
5711 S += ':';
5712 return;
5713 }
5714 PointeeTy = PT->getPointeeType();
5715 } else {
5716 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5717 }
5718
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005719 bool isReadOnly = false;
5720 // For historical/compatibility reasons, the read-only qualifier of the
5721 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5722 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005723 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005724 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005725 if (OutermostType && T.isConstQualified()) {
5726 isReadOnly = true;
5727 S += 'r';
5728 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005729 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005730 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005731 while (P->getAs<PointerType>())
5732 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005733 if (P.isConstQualified()) {
5734 isReadOnly = true;
5735 S += 'r';
5736 }
5737 }
5738 if (isReadOnly) {
5739 // Another legacy compatibility encoding. Some ObjC qualifier and type
5740 // combinations need to be rearranged.
5741 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005742 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005743 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005744 }
Mike Stump11289f42009-09-09 15:08:12 +00005745
Anders Carlssond8499822007-10-29 05:01:08 +00005746 if (PointeeTy->isCharType()) {
5747 // char pointer types should be encoded as '*' unless it is a
5748 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005749 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005750 S += '*';
5751 return;
5752 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005753 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005754 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5755 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5756 S += '#';
5757 return;
5758 }
5759 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5760 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5761 S += '@';
5762 return;
5763 }
5764 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005765 }
Anders Carlssond8499822007-10-29 05:01:08 +00005766 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005767 getLegacyIntegralTypeEncoding(PointeeTy);
5768
Mike Stump11289f42009-09-09 15:08:12 +00005769 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005770 nullptr, false, false, false, false, false, false,
5771 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005772 return;
5773 }
John McCall393a78d2012-12-20 02:45:14 +00005774
5775 case Type::ConstantArray:
5776 case Type::IncompleteArray:
5777 case Type::VariableArray: {
5778 const ArrayType *AT = cast<ArrayType>(CT);
5779
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005780 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005781 // Incomplete arrays are encoded as a pointer to the array element.
5782 S += '^';
5783
Mike Stump11289f42009-09-09 15:08:12 +00005784 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005785 false, ExpandStructures, FD);
5786 } else {
5787 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005788
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005789 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5790 S += llvm::utostr(CAT->getSize().getZExtValue());
5791 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005792 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005793 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5794 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005795 S += '0';
5796 }
Mike Stump11289f42009-09-09 15:08:12 +00005797
5798 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005799 false, ExpandStructures, FD,
5800 false, false, false, false, false, false,
5801 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005802 S += ']';
5803 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005804 return;
5805 }
Mike Stump11289f42009-09-09 15:08:12 +00005806
John McCall393a78d2012-12-20 02:45:14 +00005807 case Type::FunctionNoProto:
5808 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005809 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005810 return;
Mike Stump11289f42009-09-09 15:08:12 +00005811
John McCall393a78d2012-12-20 02:45:14 +00005812 case Type::Record: {
5813 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005814 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005815 // Anonymous structures print as '?'
5816 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5817 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005818 if (ClassTemplateSpecializationDecl *Spec
5819 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5820 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005821 llvm::raw_string_ostream OS(S);
5822 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00005823 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005824 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005825 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005826 } else {
5827 S += '?';
5828 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005829 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005830 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005831 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005832 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005833 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005834 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005835 if (FD) {
5836 S += '"';
5837 S += Field->getNameAsString();
5838 S += '"';
5839 }
Mike Stump11289f42009-09-09 15:08:12 +00005840
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005841 // Special case bit-fields.
5842 if (Field->isBitField()) {
5843 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005844 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005845 } else {
5846 QualType qt = Field->getType();
5847 getLegacyIntegralTypeEncoding(qt);
5848 getObjCEncodingForTypeImpl(qt, S, false, true,
5849 FD, /*OutermostType*/false,
5850 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005851 /*StructField*/true,
5852 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005853 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005854 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005855 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005856 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005857 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005858 return;
5859 }
Mike Stump11289f42009-09-09 15:08:12 +00005860
John McCall393a78d2012-12-20 02:45:14 +00005861 case Type::BlockPointer: {
5862 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005863 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005864 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005865 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005866
5867 S += '<';
5868 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005869 getObjCEncodingForTypeImpl(
5870 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5871 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005872 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5873 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005874 // Block self
5875 S += "@?";
5876 // Block parameters
5877 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005878 for (const auto &I : FPT->param_types())
5879 getObjCEncodingForTypeImpl(
5880 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5881 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005882 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5883 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005884 }
5885 S += '>';
5886 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005887 return;
5888 }
Mike Stump11289f42009-09-09 15:08:12 +00005889
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005890 case Type::ObjCObject: {
5891 // hack to match legacy encoding of *id and *Class
5892 QualType Ty = getObjCObjectPointerType(CT);
5893 if (Ty->isObjCIdType()) {
5894 S += "{objc_object=}";
5895 return;
5896 }
5897 else if (Ty->isObjCClassType()) {
5898 S += "{objc_class=}";
5899 return;
5900 }
5901 }
5902
John McCall393a78d2012-12-20 02:45:14 +00005903 case Type::ObjCInterface: {
5904 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005905 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005906 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005907 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005908 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00005909 if (ExpandStructures) {
5910 S += '=';
5911 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5912 DeepCollectObjCIvars(OI, true, Ivars);
5913 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5914 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5915 if (Field->isBitField())
5916 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5917 else
5918 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5919 false, false, false, false, false,
5920 EncodePointerToObjCTypedef,
5921 NotEncodedT);
5922 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005923 }
5924 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005925 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005926 }
Mike Stump11289f42009-09-09 15:08:12 +00005927
John McCall393a78d2012-12-20 02:45:14 +00005928 case Type::ObjCObjectPointer: {
5929 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005930 if (OPT->isObjCIdType()) {
5931 S += '@';
5932 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005933 }
Mike Stump11289f42009-09-09 15:08:12 +00005934
Steve Narofff0c86112009-10-28 22:03:49 +00005935 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5936 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5937 // Since this is a binary compatibility issue, need to consult with runtime
5938 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005939 S += '#';
5940 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005941 }
Mike Stump11289f42009-09-09 15:08:12 +00005942
Chris Lattnere7cabb92009-07-13 00:10:46 +00005943 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005944 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005945 ExpandPointedToStructures,
5946 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005947 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005948 // Note that we do extended encoding of protocol qualifer list
5949 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005950 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005951 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005952 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005953 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005954 S += '>';
5955 }
5956 S += '"';
5957 }
5958 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005959 }
Mike Stump11289f42009-09-09 15:08:12 +00005960
Chris Lattnere7cabb92009-07-13 00:10:46 +00005961 QualType PointeeTy = OPT->getPointeeType();
5962 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005963 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5964 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005965 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005966 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005967 // {...};
5968 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005969 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005970 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005971 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5972 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5973 DeepCollectObjCIvars(OI, true, Ivars);
5974 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5975 if (cast<FieldDecl>(Ivars[i]) == FD) {
5976 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005977 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005978 S += '}';
5979 return;
5980 }
5981 }
5982 }
Mike Stump11289f42009-09-09 15:08:12 +00005983 getObjCEncodingForTypeImpl(PointeeTy, S,
5984 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005985 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005986 false, false, false, false, false,
5987 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005988 return;
5989 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005990
5991 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005992 if (OPT->getInterfaceDecl() &&
5993 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005994 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005995 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005996 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005997 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005998 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005999 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006000 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006001 S += '"';
6002 }
6003 return;
6004 }
Mike Stump11289f42009-09-09 15:08:12 +00006005
John McCalla9e6e8d2010-05-17 23:56:34 +00006006 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006007 // FIXME: we shoul do better than that. 'M' is available.
6008 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006009 // This matches gcc's encoding, even though technically it is insufficient.
6010 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006011 case Type::Vector:
6012 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006013 // Until we have a coherent encoding of these three types, issue warning.
6014 { if (NotEncodedT)
6015 *NotEncodedT = T;
6016 return;
6017 }
6018
6019 // We could see an undeduced auto type here during error recovery.
6020 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006021 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00006022 return;
6023
Xiuli Pan9c14e282016-01-09 12:53:17 +00006024 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006025#define ABSTRACT_TYPE(KIND, BASE)
6026#define TYPE(KIND, BASE)
6027#define DEPENDENT_TYPE(KIND, BASE) \
6028 case Type::KIND:
6029#define NON_CANONICAL_TYPE(KIND, BASE) \
6030 case Type::KIND:
6031#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6032 case Type::KIND:
6033#include "clang/AST/TypeNodes.def"
6034 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006035 }
John McCall393a78d2012-12-20 02:45:14 +00006036 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006037}
6038
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006039void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6040 std::string &S,
6041 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006042 bool includeVBases,
6043 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006044 assert(RDecl && "Expected non-null RecordDecl");
6045 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006046 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006047 return;
6048
6049 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6050 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6051 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6052
6053 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006054 for (const auto &BI : CXXRec->bases()) {
6055 if (!BI.isVirtual()) {
6056 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006057 if (base->isEmpty())
6058 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006059 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006060 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6061 std::make_pair(offs, base));
6062 }
6063 }
6064 }
6065
6066 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006067 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006068 uint64_t offs = layout.getFieldOffset(i);
6069 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006070 std::make_pair(offs, Field));
6071 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006072 }
6073
6074 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006075 for (const auto &BI : CXXRec->vbases()) {
6076 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006077 if (base->isEmpty())
6078 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006079 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006080 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6081 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006082 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6083 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006084 }
6085 }
6086
6087 CharUnits size;
6088 if (CXXRec) {
6089 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6090 } else {
6091 size = layout.getSize();
6092 }
6093
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006094#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006095 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006096#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006097 std::multimap<uint64_t, NamedDecl *>::iterator
6098 CurLayObj = FieldOrBaseOffsets.begin();
6099
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006100 if (CXXRec && CXXRec->isDynamicClass() &&
6101 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006102 if (FD) {
6103 S += "\"_vptr$";
6104 std::string recname = CXXRec->getNameAsString();
6105 if (recname.empty()) recname = "?";
6106 S += recname;
6107 S += '"';
6108 }
6109 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006110#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006111 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006112#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006113 }
6114
6115 if (!RDecl->hasFlexibleArrayMember()) {
6116 // Mark the end of the structure.
6117 uint64_t offs = toBits(size);
6118 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006119 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006120 }
6121
6122 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006123#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006124 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006125 if (CurOffs < CurLayObj->first) {
6126 uint64_t padding = CurLayObj->first - CurOffs;
6127 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6128 // packing/alignment of members is different that normal, in which case
6129 // the encoding will be out-of-sync with the real layout.
6130 // If the runtime switches to just consider the size of types without
6131 // taking into account alignment, we could make padding explicit in the
6132 // encoding (e.g. using arrays of chars). The encoding strings would be
6133 // longer then though.
6134 CurOffs += padding;
6135 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006136#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006137
6138 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006139 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006140 break; // reached end of structure.
6141
6142 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6143 // We expand the bases without their virtual bases since those are going
6144 // in the initial structure. Note that this differs from gcc which
6145 // expands virtual bases each time one is encountered in the hierarchy,
6146 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006147 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6148 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006149 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006150#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006151 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006152#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006153 } else {
6154 FieldDecl *field = cast<FieldDecl>(dcl);
6155 if (FD) {
6156 S += '"';
6157 S += field->getNameAsString();
6158 S += '"';
6159 }
6160
6161 if (field->isBitField()) {
6162 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006163#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006164 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006165#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006166 } else {
6167 QualType qt = field->getType();
6168 getLegacyIntegralTypeEncoding(qt);
6169 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6170 /*OutermostType*/false,
6171 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006172 /*StructField*/true,
6173 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006174#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006175 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006176#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006177 }
6178 }
6179 }
6180}
6181
Mike Stump11289f42009-09-09 15:08:12 +00006182void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006183 std::string& S) const {
6184 if (QT & Decl::OBJC_TQ_In)
6185 S += 'n';
6186 if (QT & Decl::OBJC_TQ_Inout)
6187 S += 'N';
6188 if (QT & Decl::OBJC_TQ_Out)
6189 S += 'o';
6190 if (QT & Decl::OBJC_TQ_Bycopy)
6191 S += 'O';
6192 if (QT & Decl::OBJC_TQ_Byref)
6193 S += 'R';
6194 if (QT & Decl::OBJC_TQ_Oneway)
6195 S += 'V';
6196}
6197
Douglas Gregor3ea72692011-08-12 05:46:01 +00006198TypedefDecl *ASTContext::getObjCIdDecl() const {
6199 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006200 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006201 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006202 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006203 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006204 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006205}
6206
Douglas Gregor52e02802011-08-12 06:17:30 +00006207TypedefDecl *ASTContext::getObjCSelDecl() const {
6208 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006209 QualType T = getPointerType(ObjCBuiltinSelTy);
6210 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006211 }
6212 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006213}
6214
Douglas Gregor0a586182011-08-12 05:59:41 +00006215TypedefDecl *ASTContext::getObjCClassDecl() const {
6216 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006217 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006218 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006219 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006220 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006221 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006222}
6223
Douglas Gregord53ae832012-01-17 18:09:05 +00006224ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6225 if (!ObjCProtocolClassDecl) {
6226 ObjCProtocolClassDecl
6227 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6228 SourceLocation(),
6229 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006230 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006231 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006232 SourceLocation(), true);
6233 }
6234
6235 return ObjCProtocolClassDecl;
6236}
6237
Meador Inge5d3fb222012-06-16 03:34:49 +00006238//===----------------------------------------------------------------------===//
6239// __builtin_va_list Construction Functions
6240//===----------------------------------------------------------------------===//
6241
Charles Davisc7d5c942015-09-17 20:55:33 +00006242static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6243 StringRef Name) {
6244 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006245 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006246 return Context->buildImplicitTypedef(T, Name);
6247}
6248
6249static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6250 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6251}
6252
6253static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6254 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006255}
6256
6257static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6258 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006259 QualType T = Context->getPointerType(Context->VoidTy);
6260 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006261}
6262
Tim Northover9bb857a2013-01-31 12:13:10 +00006263static TypedefDecl *
6264CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006265 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006266 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006267 if (Context->getLangOpts().CPlusPlus) {
6268 // namespace std { struct __va_list {
6269 NamespaceDecl *NS;
6270 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6271 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006272 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006273 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006274 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006275 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006276 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006277 }
6278
6279 VaListTagDecl->startDefinition();
6280
6281 const size_t NumFields = 5;
6282 QualType FieldTypes[NumFields];
6283 const char *FieldNames[NumFields];
6284
6285 // void *__stack;
6286 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6287 FieldNames[0] = "__stack";
6288
6289 // void *__gr_top;
6290 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6291 FieldNames[1] = "__gr_top";
6292
6293 // void *__vr_top;
6294 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6295 FieldNames[2] = "__vr_top";
6296
6297 // int __gr_offs;
6298 FieldTypes[3] = Context->IntTy;
6299 FieldNames[3] = "__gr_offs";
6300
6301 // int __vr_offs;
6302 FieldTypes[4] = Context->IntTy;
6303 FieldNames[4] = "__vr_offs";
6304
6305 // Create fields
6306 for (unsigned i = 0; i < NumFields; ++i) {
6307 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6308 VaListTagDecl,
6309 SourceLocation(),
6310 SourceLocation(),
6311 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006312 FieldTypes[i], /*TInfo=*/nullptr,
6313 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006314 /*Mutable=*/false,
6315 ICIS_NoInit);
6316 Field->setAccess(AS_public);
6317 VaListTagDecl->addDecl(Field);
6318 }
6319 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006320 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006321 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006322
6323 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006324 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006325}
6326
Meador Inge5d3fb222012-06-16 03:34:49 +00006327static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6328 // typedef struct __va_list_tag {
6329 RecordDecl *VaListTagDecl;
6330
Alp Toker2dea15b2013-12-17 01:22:38 +00006331 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006332 VaListTagDecl->startDefinition();
6333
6334 const size_t NumFields = 5;
6335 QualType FieldTypes[NumFields];
6336 const char *FieldNames[NumFields];
6337
6338 // unsigned char gpr;
6339 FieldTypes[0] = Context->UnsignedCharTy;
6340 FieldNames[0] = "gpr";
6341
6342 // unsigned char fpr;
6343 FieldTypes[1] = Context->UnsignedCharTy;
6344 FieldNames[1] = "fpr";
6345
6346 // unsigned short reserved;
6347 FieldTypes[2] = Context->UnsignedShortTy;
6348 FieldNames[2] = "reserved";
6349
6350 // void* overflow_arg_area;
6351 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6352 FieldNames[3] = "overflow_arg_area";
6353
6354 // void* reg_save_area;
6355 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6356 FieldNames[4] = "reg_save_area";
6357
6358 // Create fields
6359 for (unsigned i = 0; i < NumFields; ++i) {
6360 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6361 SourceLocation(),
6362 SourceLocation(),
6363 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006364 FieldTypes[i], /*TInfo=*/nullptr,
6365 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006366 /*Mutable=*/false,
6367 ICIS_NoInit);
6368 Field->setAccess(AS_public);
6369 VaListTagDecl->addDecl(Field);
6370 }
6371 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006372 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006373 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6374
6375 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006376 TypedefDecl *VaListTagTypedefDecl =
6377 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6378
Meador Inge5d3fb222012-06-16 03:34:49 +00006379 QualType VaListTagTypedefType =
6380 Context->getTypedefType(VaListTagTypedefDecl);
6381
6382 // typedef __va_list_tag __builtin_va_list[1];
6383 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6384 QualType VaListTagArrayType
6385 = Context->getConstantArrayType(VaListTagTypedefType,
6386 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006387 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006388}
6389
6390static TypedefDecl *
6391CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006392 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006393 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006394 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006395 VaListTagDecl->startDefinition();
6396
6397 const size_t NumFields = 4;
6398 QualType FieldTypes[NumFields];
6399 const char *FieldNames[NumFields];
6400
6401 // unsigned gp_offset;
6402 FieldTypes[0] = Context->UnsignedIntTy;
6403 FieldNames[0] = "gp_offset";
6404
6405 // unsigned fp_offset;
6406 FieldTypes[1] = Context->UnsignedIntTy;
6407 FieldNames[1] = "fp_offset";
6408
6409 // void* overflow_arg_area;
6410 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6411 FieldNames[2] = "overflow_arg_area";
6412
6413 // void* reg_save_area;
6414 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6415 FieldNames[3] = "reg_save_area";
6416
6417 // Create fields
6418 for (unsigned i = 0; i < NumFields; ++i) {
6419 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6420 VaListTagDecl,
6421 SourceLocation(),
6422 SourceLocation(),
6423 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006424 FieldTypes[i], /*TInfo=*/nullptr,
6425 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006426 /*Mutable=*/false,
6427 ICIS_NoInit);
6428 Field->setAccess(AS_public);
6429 VaListTagDecl->addDecl(Field);
6430 }
6431 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006432 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006433 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6434
Richard Smith9b88a4c2015-07-27 05:40:23 +00006435 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006436
Richard Smith9b88a4c2015-07-27 05:40:23 +00006437 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006438 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006439 QualType VaListTagArrayType =
6440 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006441 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006442}
6443
6444static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6445 // typedef int __builtin_va_list[4];
6446 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6447 QualType IntArrayType
6448 = Context->getConstantArrayType(Context->IntTy,
6449 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006450 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006451}
6452
Logan Chien57086ce2012-10-10 06:56:20 +00006453static TypedefDecl *
6454CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006455 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006456 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006457 if (Context->getLangOpts().CPlusPlus) {
6458 // namespace std { struct __va_list {
6459 NamespaceDecl *NS;
6460 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6461 Context->getTranslationUnitDecl(),
6462 /*Inline*/false, SourceLocation(),
6463 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006464 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006465 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006466 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006467 }
6468
6469 VaListDecl->startDefinition();
6470
6471 // void * __ap;
6472 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6473 VaListDecl,
6474 SourceLocation(),
6475 SourceLocation(),
6476 &Context->Idents.get("__ap"),
6477 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006478 /*TInfo=*/nullptr,
6479 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006480 /*Mutable=*/false,
6481 ICIS_NoInit);
6482 Field->setAccess(AS_public);
6483 VaListDecl->addDecl(Field);
6484
6485 // };
6486 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006487 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006488
6489 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006490 QualType T = Context->getRecordType(VaListDecl);
6491 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006492}
6493
Ulrich Weigand47445072013-05-06 16:26:41 +00006494static TypedefDecl *
6495CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006496 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006497 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006498 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006499 VaListTagDecl->startDefinition();
6500
6501 const size_t NumFields = 4;
6502 QualType FieldTypes[NumFields];
6503 const char *FieldNames[NumFields];
6504
6505 // long __gpr;
6506 FieldTypes[0] = Context->LongTy;
6507 FieldNames[0] = "__gpr";
6508
6509 // long __fpr;
6510 FieldTypes[1] = Context->LongTy;
6511 FieldNames[1] = "__fpr";
6512
6513 // void *__overflow_arg_area;
6514 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6515 FieldNames[2] = "__overflow_arg_area";
6516
6517 // void *__reg_save_area;
6518 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6519 FieldNames[3] = "__reg_save_area";
6520
6521 // Create fields
6522 for (unsigned i = 0; i < NumFields; ++i) {
6523 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6524 VaListTagDecl,
6525 SourceLocation(),
6526 SourceLocation(),
6527 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006528 FieldTypes[i], /*TInfo=*/nullptr,
6529 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006530 /*Mutable=*/false,
6531 ICIS_NoInit);
6532 Field->setAccess(AS_public);
6533 VaListTagDecl->addDecl(Field);
6534 }
6535 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006536 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006537 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006538
Richard Smith9b88a4c2015-07-27 05:40:23 +00006539 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006540
6541 // typedef __va_list_tag __builtin_va_list[1];
6542 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006543 QualType VaListTagArrayType =
6544 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006545
Alp Toker56b5cc92013-12-15 10:36:26 +00006546 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006547}
6548
Meador Inge5d3fb222012-06-16 03:34:49 +00006549static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6550 TargetInfo::BuiltinVaListKind Kind) {
6551 switch (Kind) {
6552 case TargetInfo::CharPtrBuiltinVaList:
6553 return CreateCharPtrBuiltinVaListDecl(Context);
6554 case TargetInfo::VoidPtrBuiltinVaList:
6555 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006556 case TargetInfo::AArch64ABIBuiltinVaList:
6557 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006558 case TargetInfo::PowerABIBuiltinVaList:
6559 return CreatePowerABIBuiltinVaListDecl(Context);
6560 case TargetInfo::X86_64ABIBuiltinVaList:
6561 return CreateX86_64ABIBuiltinVaListDecl(Context);
6562 case TargetInfo::PNaClABIBuiltinVaList:
6563 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006564 case TargetInfo::AAPCSABIBuiltinVaList:
6565 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006566 case TargetInfo::SystemZBuiltinVaList:
6567 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006568 }
6569
6570 llvm_unreachable("Unhandled __builtin_va_list type kind");
6571}
6572
6573TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006574 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006575 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006576 assert(BuiltinVaListDecl->isImplicit());
6577 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006578
6579 return BuiltinVaListDecl;
6580}
6581
Richard Smith9b88a4c2015-07-27 05:40:23 +00006582Decl *ASTContext::getVaListTagDecl() const {
6583 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006584 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006585 if (!VaListTagDecl)
6586 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006587
Richard Smith9b88a4c2015-07-27 05:40:23 +00006588 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006589}
6590
Charles Davisc7d5c942015-09-17 20:55:33 +00006591TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6592 if (!BuiltinMSVaListDecl)
6593 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6594
6595 return BuiltinMSVaListDecl;
6596}
6597
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006598void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006599 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006600 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006601
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006602 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006603}
6604
John McCalld28ae272009-12-02 08:04:21 +00006605/// \brief Retrieve the template name that corresponds to a non-empty
6606/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006607TemplateName
6608ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6609 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006610 unsigned size = End - Begin;
6611 assert(size > 1 && "set is not overloaded!");
6612
6613 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6614 size * sizeof(FunctionTemplateDecl*));
6615 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6616
6617 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006618 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006619 NamedDecl *D = *I;
6620 assert(isa<FunctionTemplateDecl>(D) ||
6621 (isa<UsingShadowDecl>(D) &&
6622 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6623 *Storage++ = D;
6624 }
6625
6626 return TemplateName(OT);
6627}
6628
Douglas Gregordc572a32009-03-30 22:58:21 +00006629/// \brief Retrieve the template name that represents a qualified
6630/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006631TemplateName
6632ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6633 bool TemplateKeyword,
6634 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006635 assert(NNS && "Missing nested-name-specifier in qualified template name");
6636
Douglas Gregorc42075a2010-02-04 18:10:26 +00006637 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006638 llvm::FoldingSetNodeID ID;
6639 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6640
Craig Topper36250ad2014-05-12 05:36:57 +00006641 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006642 QualifiedTemplateName *QTN =
6643 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6644 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006645 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6646 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006647 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6648 }
6649
6650 return TemplateName(QTN);
6651}
6652
6653/// \brief Retrieve the template name that represents a dependent
6654/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006655TemplateName
6656ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6657 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006658 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006659 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006660
6661 llvm::FoldingSetNodeID ID;
6662 DependentTemplateName::Profile(ID, NNS, Name);
6663
Craig Topper36250ad2014-05-12 05:36:57 +00006664 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006665 DependentTemplateName *QTN =
6666 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6667
6668 if (QTN)
6669 return TemplateName(QTN);
6670
6671 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6672 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006673 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6674 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006675 } else {
6676 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006677 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6678 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006679 DependentTemplateName *CheckQTN =
6680 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6681 assert(!CheckQTN && "Dependent type name canonicalization broken");
6682 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006683 }
6684
6685 DependentTemplateNames.InsertNode(QTN, InsertPos);
6686 return TemplateName(QTN);
6687}
6688
Douglas Gregor71395fa2009-11-04 00:56:37 +00006689/// \brief Retrieve the template name that represents a dependent
6690/// template name such as \c MetaFun::template operator+.
6691TemplateName
6692ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006693 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006694 assert((!NNS || NNS->isDependent()) &&
6695 "Nested name specifier must be dependent");
6696
6697 llvm::FoldingSetNodeID ID;
6698 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006699
6700 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006701 DependentTemplateName *QTN
6702 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006703
6704 if (QTN)
6705 return TemplateName(QTN);
6706
6707 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6708 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006709 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6710 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006711 } else {
6712 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006713 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6714 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006715
6716 DependentTemplateName *CheckQTN
6717 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6718 assert(!CheckQTN && "Dependent template name canonicalization broken");
6719 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006720 }
6721
6722 DependentTemplateNames.InsertNode(QTN, InsertPos);
6723 return TemplateName(QTN);
6724}
6725
Douglas Gregor5590be02011-01-15 06:45:20 +00006726TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006727ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6728 TemplateName replacement) const {
6729 llvm::FoldingSetNodeID ID;
6730 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006731
6732 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006733 SubstTemplateTemplateParmStorage *subst
6734 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6735
6736 if (!subst) {
6737 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6738 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6739 }
6740
6741 return TemplateName(subst);
6742}
6743
6744TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006745ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6746 const TemplateArgument &ArgPack) const {
6747 ASTContext &Self = const_cast<ASTContext &>(*this);
6748 llvm::FoldingSetNodeID ID;
6749 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006750
6751 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006752 SubstTemplateTemplateParmPackStorage *Subst
6753 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6754
6755 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006756 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006757 ArgPack.pack_size(),
6758 ArgPack.pack_begin());
6759 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6760 }
6761
6762 return TemplateName(Subst);
6763}
6764
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006765/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006766/// TargetInfo, produce the corresponding type. The unsigned @p Type
6767/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006768CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006769 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006770 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006771 case TargetInfo::SignedChar: return SignedCharTy;
6772 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006773 case TargetInfo::SignedShort: return ShortTy;
6774 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6775 case TargetInfo::SignedInt: return IntTy;
6776 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6777 case TargetInfo::SignedLong: return LongTy;
6778 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6779 case TargetInfo::SignedLongLong: return LongLongTy;
6780 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6781 }
6782
David Blaikie83d382b2011-09-23 05:06:16 +00006783 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006784}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006785
6786//===----------------------------------------------------------------------===//
6787// Type Predicates.
6788//===----------------------------------------------------------------------===//
6789
Fariborz Jahanian96207692009-02-18 21:49:28 +00006790/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6791/// garbage collection attribute.
6792///
John McCall553d45a2011-01-12 00:34:59 +00006793Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006794 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006795 return Qualifiers::GCNone;
6796
David Blaikiebbafb8a2012-03-11 07:00:24 +00006797 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006798 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6799
6800 // Default behaviour under objective-C's gc is for ObjC pointers
6801 // (or pointers to them) be treated as though they were declared
6802 // as __strong.
6803 if (GCAttrs == Qualifiers::GCNone) {
6804 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6805 return Qualifiers::Strong;
6806 else if (Ty->isPointerType())
6807 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6808 } else {
6809 // It's not valid to set GC attributes on anything that isn't a
6810 // pointer.
6811#ifndef NDEBUG
6812 QualType CT = Ty->getCanonicalTypeInternal();
6813 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6814 CT = AT->getElementType();
6815 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6816#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006817 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006818 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006819}
6820
Chris Lattner49af6a42008-04-07 06:51:04 +00006821//===----------------------------------------------------------------------===//
6822// Type Compatibility Testing
6823//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006824
Mike Stump11289f42009-09-09 15:08:12 +00006825/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006826/// compatible.
6827static bool areCompatVectorTypes(const VectorType *LHS,
6828 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006829 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006830 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006831 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006832}
6833
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006834bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6835 QualType SecondVec) {
6836 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6837 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6838
6839 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6840 return true;
6841
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006842 // Treat Neon vector types and most AltiVec vector types as if they are the
6843 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006844 const VectorType *First = FirstVec->getAs<VectorType>();
6845 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006846 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006847 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006848 First->getVectorKind() != VectorType::AltiVecPixel &&
6849 First->getVectorKind() != VectorType::AltiVecBool &&
6850 Second->getVectorKind() != VectorType::AltiVecPixel &&
6851 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006852 return true;
6853
6854 return false;
6855}
6856
Steve Naroff8e6aee52009-07-23 01:01:38 +00006857//===----------------------------------------------------------------------===//
6858// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6859//===----------------------------------------------------------------------===//
6860
6861/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6862/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006863bool
6864ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6865 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006866 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006867 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006868 for (auto *PI : rProto->protocols())
6869 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006870 return true;
6871 return false;
6872}
6873
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006874/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6875/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006876bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6877 QualType rhs) {
6878 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6879 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6880 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6881
Aaron Ballman83731462014-03-17 16:14:00 +00006882 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006883 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006884 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006885 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6886 match = true;
6887 break;
6888 }
6889 }
6890 if (!match)
6891 return false;
6892 }
6893 return true;
6894}
6895
Steve Naroff8e6aee52009-07-23 01:01:38 +00006896/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6897/// ObjCQualifiedIDType.
6898bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6899 bool compare) {
6900 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006901 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006902 lhs->isObjCIdType() || lhs->isObjCClassType())
6903 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006904 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006905 rhs->isObjCIdType() || rhs->isObjCClassType())
6906 return true;
6907
6908 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006909 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006910
Steve Naroff8e6aee52009-07-23 01:01:38 +00006911 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006912
Steve Naroff8e6aee52009-07-23 01:01:38 +00006913 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006914 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006915 // make sure we check the class hierarchy.
6916 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006917 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006918 // when comparing an id<P> on lhs with a static type on rhs,
6919 // see if static class implements all of id's protocols, directly or
6920 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006921 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006922 return false;
6923 }
6924 }
6925 // If there are no qualifiers and no interface, we have an 'id'.
6926 return true;
6927 }
Mike Stump11289f42009-09-09 15:08:12 +00006928 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006929 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006930 bool match = false;
6931
6932 // when comparing an id<P> on lhs with a static type on rhs,
6933 // see if static class implements all of id's protocols, directly or
6934 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006935 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006936 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6937 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6938 match = true;
6939 break;
6940 }
6941 }
Mike Stump11289f42009-09-09 15:08:12 +00006942 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006943 // make sure we check the class hierarchy.
6944 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006945 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006946 // when comparing an id<P> on lhs with a static type on rhs,
6947 // see if static class implements all of id's protocols, directly or
6948 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006949 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006950 match = true;
6951 break;
6952 }
6953 }
6954 }
6955 if (!match)
6956 return false;
6957 }
Mike Stump11289f42009-09-09 15:08:12 +00006958
Steve Naroff8e6aee52009-07-23 01:01:38 +00006959 return true;
6960 }
Mike Stump11289f42009-09-09 15:08:12 +00006961
Steve Naroff8e6aee52009-07-23 01:01:38 +00006962 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6963 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6964
Mike Stump11289f42009-09-09 15:08:12 +00006965 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006966 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006967 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006968 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006969 bool match = false;
6970
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006971 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006972 // see if static class implements all of id's protocols, directly or
6973 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006974 // First, lhs protocols in the qualifier list must be found, direct
6975 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006976 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006977 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6978 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6979 match = true;
6980 break;
6981 }
6982 }
6983 if (!match)
6984 return false;
6985 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006986
6987 // Static class's protocols, or its super class or category protocols
6988 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6989 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6990 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6991 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6992 // This is rather dubious but matches gcc's behavior. If lhs has
6993 // no type qualifier and its class has no static protocol(s)
6994 // assume that it is mismatch.
6995 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6996 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006997 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006998 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006999 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007000 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7001 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7002 match = true;
7003 break;
7004 }
7005 }
7006 if (!match)
7007 return false;
7008 }
7009 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007010 return true;
7011 }
7012 return false;
7013}
7014
Eli Friedman47f77112008-08-22 00:56:42 +00007015/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007016/// compatible for assignment from RHS to LHS. This handles validation of any
7017/// protocol qualifiers on the LHS or RHS.
7018///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007019bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7020 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007021 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7022 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7023
Steve Naroff1329fa02009-07-15 18:40:39 +00007024 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007025 if (LHS->isObjCUnqualifiedIdOrClass() ||
7026 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007027 return true;
7028
Douglas Gregorab209d82015-07-07 03:58:42 +00007029 // Function object that propagates a successful result or handles
7030 // __kindof types.
7031 auto finish = [&](bool succeeded) -> bool {
7032 if (succeeded)
7033 return true;
7034
7035 if (!RHS->isKindOfType())
7036 return false;
7037
7038 // Strip off __kindof and protocol qualifiers, then check whether
7039 // we can assign the other way.
7040 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7041 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7042 };
7043
7044 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7045 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7046 QualType(RHSOPT,0),
7047 false));
7048 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007049
Douglas Gregorab209d82015-07-07 03:58:42 +00007050 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7051 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7052 QualType(RHSOPT,0)));
7053 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007054
John McCall8b07ec22010-05-15 11:32:37 +00007055 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007056 if (LHS->getInterface() && RHS->getInterface()) {
7057 return finish(canAssignObjCInterfaces(LHS, RHS));
7058 }
Mike Stump11289f42009-09-09 15:08:12 +00007059
Steve Naroff8e6aee52009-07-23 01:01:38 +00007060 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007061}
7062
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007063/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007064/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007065/// arguments in block literals. When passed as arguments, passing 'A*' where
7066/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7067/// not OK. For the return type, the opposite is not OK.
7068bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7069 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007070 const ObjCObjectPointerType *RHSOPT,
7071 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007072
7073 // Function object that propagates a successful result or handles
7074 // __kindof types.
7075 auto finish = [&](bool succeeded) -> bool {
7076 if (succeeded)
7077 return true;
7078
7079 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7080 if (!Expected->isKindOfType())
7081 return false;
7082
7083 // Strip off __kindof and protocol qualifiers, then check whether
7084 // we can assign the other way.
7085 return canAssignObjCInterfacesInBlockPointer(
7086 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7087 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7088 BlockReturnType);
7089 };
7090
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007091 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007092 return true;
7093
7094 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007095 return finish(RHSOPT->isObjCBuiltinType() ||
7096 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007097 }
7098
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007099 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007100 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7101 QualType(RHSOPT,0),
7102 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007103
7104 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7105 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7106 if (LHS && RHS) { // We have 2 user-defined types.
7107 if (LHS != RHS) {
7108 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007109 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007110 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007111 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007112 }
7113 else
7114 return true;
7115 }
7116 return false;
7117}
7118
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007119/// Comparison routine for Objective-C protocols to be used with
7120/// llvm::array_pod_sort.
7121static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7122 ObjCProtocolDecl * const *rhs) {
7123 return (*lhs)->getName().compare((*rhs)->getName());
7124
7125}
7126
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007127/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007128/// of protocols inherited from two distinct objective-c pointer objects with
7129/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007130/// It is used to build composite qualifier list of the composite type of
7131/// the conditional expression involving two objective-c pointer objects.
7132static
7133void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007134 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007135 const ObjCObjectPointerType *LHSOPT,
7136 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007137 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007138
John McCall8b07ec22010-05-15 11:32:37 +00007139 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7140 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7141 assert(LHS->getInterface() && "LHS must have an interface base");
7142 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007143
7144 // Add all of the protocols for the LHS.
7145 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7146
7147 // Start with the protocol qualifiers.
7148 for (auto proto : LHS->quals()) {
7149 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007150 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007151
7152 // Also add the protocols associated with the LHS interface.
7153 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7154
7155 // Add all of the protocls for the RHS.
7156 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7157
7158 // Start with the protocol qualifiers.
7159 for (auto proto : RHS->quals()) {
7160 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007161 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007162
7163 // Also add the protocols associated with the RHS interface.
7164 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7165
7166 // Compute the intersection of the collected protocol sets.
7167 for (auto proto : LHSProtocolSet) {
7168 if (RHSProtocolSet.count(proto))
7169 IntersectionSet.push_back(proto);
7170 }
7171
7172 // Compute the set of protocols that is implied by either the common type or
7173 // the protocols within the intersection.
7174 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7175 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7176
7177 // Remove any implied protocols from the list of inherited protocols.
7178 if (!ImpliedProtocols.empty()) {
7179 IntersectionSet.erase(
7180 std::remove_if(IntersectionSet.begin(),
7181 IntersectionSet.end(),
7182 [&](ObjCProtocolDecl *proto) -> bool {
7183 return ImpliedProtocols.count(proto) > 0;
7184 }),
7185 IntersectionSet.end());
7186 }
7187
7188 // Sort the remaining protocols by name.
7189 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7190 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007191}
7192
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007193/// Determine whether the first type is a subtype of the second.
7194static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7195 QualType rhs) {
7196 // Common case: two object pointers.
7197 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7198 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7199 if (lhsOPT && rhsOPT)
7200 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7201
7202 // Two block pointers.
7203 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7204 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7205 if (lhsBlock && rhsBlock)
7206 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7207
7208 // If either is an unqualified 'id' and the other is a block, it's
7209 // acceptable.
7210 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7211 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7212 return true;
7213
7214 return false;
7215}
7216
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007217// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007218static bool sameObjCTypeArgs(ASTContext &ctx,
7219 const ObjCInterfaceDecl *iface,
7220 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007221 ArrayRef<QualType> rhsArgs,
7222 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007223 if (lhsArgs.size() != rhsArgs.size())
7224 return false;
7225
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007226 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007227 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007228 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7229 continue;
7230
7231 switch (typeParams->begin()[i]->getVariance()) {
7232 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007233 if (!stripKindOf ||
7234 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7235 rhsArgs[i].stripObjCKindOfType(ctx))) {
7236 return false;
7237 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007238 break;
7239
7240 case ObjCTypeParamVariance::Covariant:
7241 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7242 return false;
7243 break;
7244
7245 case ObjCTypeParamVariance::Contravariant:
7246 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7247 return false;
7248 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007249 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007250 }
7251
7252 return true;
7253}
7254
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007255QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007256 const ObjCObjectPointerType *Lptr,
7257 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007258 const ObjCObjectType *LHS = Lptr->getObjectType();
7259 const ObjCObjectType *RHS = Rptr->getObjectType();
7260 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7261 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007262
7263 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007264 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007265
Manman Renc46f7d12016-05-06 19:35:02 +00007266 // When either LHS or RHS is a kindof type, we should return a kindof type.
7267 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7268 // kindof(A).
7269 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7270
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007271 // Follow the left-hand side up the class hierarchy until we either hit a
7272 // root or find the RHS. Record the ancestors in case we don't find it.
7273 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7274 LHSAncestors;
7275 while (true) {
7276 // Record this ancestor. We'll need this if the common type isn't in the
7277 // path from the LHS to the root.
7278 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007279
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007280 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7281 // Get the type arguments.
7282 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7283 bool anyChanges = false;
7284 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7285 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007286 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7287 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007288 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007289 return QualType();
7290 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7291 // If only one has type arguments, the result will not have type
7292 // arguments.
7293 LHSTypeArgs = { };
7294 anyChanges = true;
7295 }
7296
7297 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007298 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007299 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7300 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007301 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007302 anyChanges = true;
7303
7304 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007305 // If we need to return a kindof type but LHS is not a kindof type, we
7306 // build a new result type.
7307 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007308 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007309 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007310 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007311 return getObjCObjectPointerType(Result);
7312 }
7313
7314 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007315 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007316
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007317 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007318 QualType LHSSuperType = LHS->getSuperClassType();
7319 if (LHSSuperType.isNull())
7320 break;
7321
7322 LHS = LHSSuperType->castAs<ObjCObjectType>();
7323 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007324
7325 // We didn't find anything by following the LHS to its root; now check
7326 // the RHS against the cached set of ancestors.
7327 while (true) {
7328 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7329 if (KnownLHS != LHSAncestors.end()) {
7330 LHS = KnownLHS->second;
7331
7332 // Get the type arguments.
7333 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7334 bool anyChanges = false;
7335 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7336 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007337 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7338 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007339 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007340 return QualType();
7341 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7342 // If only one has type arguments, the result will not have type
7343 // arguments.
7344 RHSTypeArgs = { };
7345 anyChanges = true;
7346 }
7347
7348 // Compute the intersection of protocols.
7349 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7350 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7351 Protocols);
7352 if (!Protocols.empty())
7353 anyChanges = true;
7354
Manman Renc46f7d12016-05-06 19:35:02 +00007355 // If we need to return a kindof type but RHS is not a kindof type, we
7356 // build a new result type.
7357 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007358 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007359 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007360 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007361 return getObjCObjectPointerType(Result);
7362 }
7363
7364 return getObjCObjectPointerType(QualType(RHS, 0));
7365 }
7366
7367 // Find the superclass of the RHS.
7368 QualType RHSSuperType = RHS->getSuperClassType();
7369 if (RHSSuperType.isNull())
7370 break;
7371
7372 RHS = RHSSuperType->castAs<ObjCObjectType>();
7373 }
7374
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007375 return QualType();
7376}
7377
John McCall8b07ec22010-05-15 11:32:37 +00007378bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7379 const ObjCObjectType *RHS) {
7380 assert(LHS->getInterface() && "LHS is not an interface type");
7381 assert(RHS->getInterface() && "RHS is not an interface type");
7382
Chris Lattner49af6a42008-04-07 06:51:04 +00007383 // Verify that the base decls are compatible: the RHS must be a subclass of
7384 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007385 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7386 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7387 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007388 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007389
Douglas Gregore83b9562015-07-07 03:57:53 +00007390 // If the LHS has protocol qualifiers, determine whether all of them are
7391 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7392 // LHS).
7393 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007394 // OK if conversion of LHS to SuperClass results in narrowing of types
7395 // ; i.e., SuperClass may implement at least one of the protocols
7396 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7397 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7398 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7399 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7400 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7401 // qualifiers.
7402 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007403 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007404 // If there is no protocols associated with RHS, it is not a match.
7405 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007406 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007407
7408 for (const auto *LHSProto : LHS->quals()) {
7409 bool SuperImplementsProtocol = false;
7410 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7411 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7412 SuperImplementsProtocol = true;
7413 break;
7414 }
7415 if (!SuperImplementsProtocol)
7416 return false;
7417 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007418 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007419
7420 // If the LHS is specialized, we may need to check type arguments.
7421 if (LHS->isSpecialized()) {
7422 // Follow the superclass chain until we've matched the LHS class in the
7423 // hierarchy. This substitutes type arguments through.
7424 const ObjCObjectType *RHSSuper = RHS;
7425 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7426 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7427
7428 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007429 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007430 !sameObjCTypeArgs(*this, LHS->getInterface(),
7431 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007432 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007433 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007434 }
7435 }
7436
7437 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007438}
7439
Steve Naroffb7605152009-02-12 17:52:19 +00007440bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7441 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007442 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7443 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007444
Steve Naroff7cae42b2009-07-10 23:34:53 +00007445 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007446 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007447
7448 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7449 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007450}
7451
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007452bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7453 return canAssignObjCInterfaces(
7454 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7455 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7456}
7457
Mike Stump11289f42009-09-09 15:08:12 +00007458/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007459/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007460/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007461/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007462bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7463 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007464 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007465 return hasSameType(LHS, RHS);
7466
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007467 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007468}
7469
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007470bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007471 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007472}
7473
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007474bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7475 return !mergeTypes(LHS, RHS, true).isNull();
7476}
7477
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007478/// mergeTransparentUnionType - if T is a transparent union type and a member
7479/// of T is compatible with SubType, return the merged type, else return
7480/// QualType()
7481QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7482 bool OfBlockPointer,
7483 bool Unqualified) {
7484 if (const RecordType *UT = T->getAsUnionType()) {
7485 RecordDecl *UD = UT->getDecl();
7486 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007487 for (const auto *I : UD->fields()) {
7488 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007489 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7490 if (!MT.isNull())
7491 return MT;
7492 }
7493 }
7494 }
7495
7496 return QualType();
7497}
7498
Alp Toker9cacbab2014-01-20 20:26:09 +00007499/// mergeFunctionParameterTypes - merge two types which appear as function
7500/// parameter types
7501QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7502 bool OfBlockPointer,
7503 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007504 // GNU extension: two types are compatible if they appear as a function
7505 // argument, one of the types is a transparent union type and the other
7506 // type is compatible with a union member
7507 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7508 Unqualified);
7509 if (!lmerge.isNull())
7510 return lmerge;
7511
7512 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7513 Unqualified);
7514 if (!rmerge.isNull())
7515 return rmerge;
7516
7517 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7518}
7519
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007520QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007521 bool OfBlockPointer,
7522 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007523 const FunctionType *lbase = lhs->getAs<FunctionType>();
7524 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007525 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7526 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007527 bool allLTypes = true;
7528 bool allRTypes = true;
7529
7530 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007531 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007532 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007533 QualType RHS = rbase->getReturnType();
7534 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007535 bool UnqualifiedResult = Unqualified;
7536 if (!UnqualifiedResult)
7537 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007538 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007539 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007540 else
Alp Toker314cc812014-01-25 16:55:45 +00007541 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007542 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007543 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007544
7545 if (Unqualified)
7546 retType = retType.getUnqualifiedType();
7547
Alp Toker314cc812014-01-25 16:55:45 +00007548 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7549 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007550 if (Unqualified) {
7551 LRetType = LRetType.getUnqualifiedType();
7552 RRetType = RRetType.getUnqualifiedType();
7553 }
7554
7555 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007556 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007557 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007558 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007559
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007560 // FIXME: double check this
7561 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7562 // rbase->getRegParmAttr() != 0 &&
7563 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007564 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7565 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007566
Douglas Gregor8c940862010-01-18 17:14:39 +00007567 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007568 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007569 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007570
John McCall8c6b56f2010-12-15 01:06:38 +00007571 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007572 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7573 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007574 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7575 return QualType();
7576
John McCall31168b02011-06-15 23:02:42 +00007577 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7578 return QualType();
7579
John McCall8c6b56f2010-12-15 01:06:38 +00007580 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7581 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007582
Rafael Espindola8778c282012-11-29 16:09:03 +00007583 if (lbaseInfo.getNoReturn() != NoReturn)
7584 allLTypes = false;
7585 if (rbaseInfo.getNoReturn() != NoReturn)
7586 allRTypes = false;
7587
John McCall31168b02011-06-15 23:02:42 +00007588 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007589
Eli Friedman47f77112008-08-22 00:56:42 +00007590 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007591 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7592 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007593 // Compatible functions must have the same number of parameters
7594 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007595 return QualType();
7596
7597 // Variadic and non-variadic functions aren't compatible
7598 if (lproto->isVariadic() != rproto->isVariadic())
7599 return QualType();
7600
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007601 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7602 return QualType();
7603
John McCall18afab72016-03-01 00:49:02 +00007604 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007605 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007606
7607 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007608 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007609 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7610 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7611 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7612 QualType paramType = mergeFunctionParameterTypes(
7613 lParamType, rParamType, OfBlockPointer, Unqualified);
7614 if (paramType.isNull())
7615 return QualType();
7616
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007617 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007618 paramType = paramType.getUnqualifiedType();
7619
7620 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007621 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007622 lParamType = lParamType.getUnqualifiedType();
7623 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007624 }
Alp Toker601b22c2014-01-21 23:35:24 +00007625
7626 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007627 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007628 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007629 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007630 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007631
Eli Friedman47f77112008-08-22 00:56:42 +00007632 if (allLTypes) return lhs;
7633 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007634
7635 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7636 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007637 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007638 }
7639
7640 if (lproto) allRTypes = false;
7641 if (rproto) allLTypes = false;
7642
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007643 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007644 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007645 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007646 if (proto->isVariadic()) return QualType();
7647 // Check that the types are compatible with the types that
7648 // would result from default argument promotions (C99 6.7.5.3p15).
7649 // The only types actually affected are promotable integer
7650 // types and floats, which would be passed as a different
7651 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007652 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7653 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007654
Eli Friedman448ce402012-08-30 00:44:15 +00007655 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007656 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007657 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7658 paramTy = Enum->getDecl()->getIntegerType();
7659 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007660 return QualType();
7661 }
Alp Toker601b22c2014-01-21 23:35:24 +00007662
7663 if (paramTy->isPromotableIntegerType() ||
7664 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007665 return QualType();
7666 }
7667
7668 if (allLTypes) return lhs;
7669 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007670
7671 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7672 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007673 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007674 }
7675
7676 if (allLTypes) return lhs;
7677 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007678 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007679}
7680
John McCall433c2e62013-03-21 00:10:07 +00007681/// Given that we have an enum type and a non-enum type, try to merge them.
7682static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7683 QualType other, bool isBlockReturnType) {
7684 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7685 // a signed integer type, or an unsigned integer type.
7686 // Compatibility is based on the underlying type, not the promotion
7687 // type.
7688 QualType underlyingType = ET->getDecl()->getIntegerType();
7689 if (underlyingType.isNull()) return QualType();
7690 if (Context.hasSameType(underlyingType, other))
7691 return other;
7692
7693 // In block return types, we're more permissive and accept any
7694 // integral type of the same size.
7695 if (isBlockReturnType && other->isIntegerType() &&
7696 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7697 return other;
7698
7699 return QualType();
7700}
7701
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007702QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007703 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007704 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007705 // C++ [expr]: If an expression initially has the type "reference to T", the
7706 // type is adjusted to "T" prior to any further analysis, the expression
7707 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007708 // expression is an lvalue unless the reference is an rvalue reference and
7709 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007710 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7711 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007712
7713 if (Unqualified) {
7714 LHS = LHS.getUnqualifiedType();
7715 RHS = RHS.getUnqualifiedType();
7716 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007717
Eli Friedman47f77112008-08-22 00:56:42 +00007718 QualType LHSCan = getCanonicalType(LHS),
7719 RHSCan = getCanonicalType(RHS);
7720
7721 // If two types are identical, they are compatible.
7722 if (LHSCan == RHSCan)
7723 return LHS;
7724
John McCall8ccfcb52009-09-24 19:53:00 +00007725 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007726 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7727 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007728 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007729 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00007730 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007731 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7732 return QualType();
7733 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7734 return LHS;
7735 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7736 return RHS;
7737 }
John McCall8ccfcb52009-09-24 19:53:00 +00007738 // If any of these qualifiers are different, we have a type
7739 // mismatch.
7740 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007741 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7742 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007743 return QualType();
7744
7745 // Exactly one GC qualifier difference is allowed: __strong is
7746 // okay if the other type has no GC qualifier but is an Objective
7747 // C object pointer (i.e. implicitly strong by default). We fix
7748 // this by pretending that the unqualified type was actually
7749 // qualified __strong.
7750 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7751 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7752 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7753
7754 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7755 return QualType();
7756
7757 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7758 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7759 }
7760 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7761 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7762 }
Eli Friedman47f77112008-08-22 00:56:42 +00007763 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007764 }
7765
7766 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007767
Eli Friedmandcca6332009-06-01 01:22:52 +00007768 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7769 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007770
Chris Lattnerfd652912008-01-14 05:45:46 +00007771 // We want to consider the two function types to be the same for these
7772 // comparisons, just force one to the other.
7773 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7774 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007775
7776 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007777 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7778 LHSClass = Type::ConstantArray;
7779 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7780 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007781
John McCall8b07ec22010-05-15 11:32:37 +00007782 // ObjCInterfaces are just specialized ObjCObjects.
7783 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7784 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7785
Nate Begemance4d7fc2008-04-18 23:10:10 +00007786 // Canonicalize ExtVector -> Vector.
7787 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7788 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007789
Chris Lattner95554662008-04-07 05:43:21 +00007790 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007791 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007792 // Note that we only have special rules for turning block enum
7793 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007794 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007795 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007796 }
John McCall9dd450b2009-09-21 23:43:11 +00007797 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007798 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007799 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007800 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007801 if (OfBlockPointer && !BlockReturnType) {
7802 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7803 return LHS;
7804 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7805 return RHS;
7806 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007807
Eli Friedman47f77112008-08-22 00:56:42 +00007808 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007809 }
Eli Friedman47f77112008-08-22 00:56:42 +00007810
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007811 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007812 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007813#define TYPE(Class, Base)
7814#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007815#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007816#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7817#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7818#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007819 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007820
Richard Smith27d807c2013-04-30 13:56:41 +00007821 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007822 case Type::LValueReference:
7823 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007824 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007825 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007826
John McCall8b07ec22010-05-15 11:32:37 +00007827 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007828 case Type::IncompleteArray:
7829 case Type::VariableArray:
7830 case Type::FunctionProto:
7831 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007832 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007833
Chris Lattnerfd652912008-01-14 05:45:46 +00007834 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007835 {
7836 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007837 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7838 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007839 if (Unqualified) {
7840 LHSPointee = LHSPointee.getUnqualifiedType();
7841 RHSPointee = RHSPointee.getUnqualifiedType();
7842 }
7843 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7844 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007845 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007846 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007847 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007848 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007849 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007850 return getPointerType(ResultType);
7851 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007852 case Type::BlockPointer:
7853 {
7854 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007855 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7856 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007857 if (Unqualified) {
7858 LHSPointee = LHSPointee.getUnqualifiedType();
7859 RHSPointee = RHSPointee.getUnqualifiedType();
7860 }
7861 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7862 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007863 if (ResultType.isNull()) return QualType();
7864 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7865 return LHS;
7866 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7867 return RHS;
7868 return getBlockPointerType(ResultType);
7869 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007870 case Type::Atomic:
7871 {
7872 // Merge two pointer types, while trying to preserve typedef info
7873 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7874 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7875 if (Unqualified) {
7876 LHSValue = LHSValue.getUnqualifiedType();
7877 RHSValue = RHSValue.getUnqualifiedType();
7878 }
7879 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7880 Unqualified);
7881 if (ResultType.isNull()) return QualType();
7882 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7883 return LHS;
7884 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7885 return RHS;
7886 return getAtomicType(ResultType);
7887 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007888 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007889 {
7890 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7891 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7892 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7893 return QualType();
7894
7895 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7896 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007897 if (Unqualified) {
7898 LHSElem = LHSElem.getUnqualifiedType();
7899 RHSElem = RHSElem.getUnqualifiedType();
7900 }
7901
7902 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007903 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007904 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7905 return LHS;
7906 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7907 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007908 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7909 ArrayType::ArraySizeModifier(), 0);
7910 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7911 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007912 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7913 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007914 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7915 return LHS;
7916 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7917 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007918 if (LVAT) {
7919 // FIXME: This isn't correct! But tricky to implement because
7920 // the array's size has to be the size of LHS, but the type
7921 // has to be different.
7922 return LHS;
7923 }
7924 if (RVAT) {
7925 // FIXME: This isn't correct! But tricky to implement because
7926 // the array's size has to be the size of RHS, but the type
7927 // has to be different.
7928 return RHS;
7929 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007930 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7931 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007932 return getIncompleteArrayType(ResultType,
7933 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007934 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007935 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007936 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007937 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007938 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007939 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007940 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007941 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007942 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007943 case Type::Complex:
7944 // Distinct complex types are incompatible.
7945 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007946 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007947 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007948 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7949 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007950 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007951 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007952 case Type::ObjCObject: {
7953 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007954 // FIXME: This should be type compatibility, e.g. whether
7955 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007956 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7957 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7958 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007959 return LHS;
7960
Eli Friedman47f77112008-08-22 00:56:42 +00007961 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007962 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007963 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007964 if (OfBlockPointer) {
7965 if (canAssignObjCInterfacesInBlockPointer(
7966 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007967 RHS->getAs<ObjCObjectPointerType>(),
7968 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007969 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007970 return QualType();
7971 }
John McCall9dd450b2009-09-21 23:43:11 +00007972 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7973 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007974 return LHS;
7975
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007976 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007977 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00007978 case Type::Pipe:
7979 {
7980 // Merge two pointer types, while trying to preserve typedef info
7981 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7982 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7983 if (Unqualified) {
7984 LHSValue = LHSValue.getUnqualifiedType();
7985 RHSValue = RHSValue.getUnqualifiedType();
7986 }
7987 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7988 Unqualified);
7989 if (ResultType.isNull()) return QualType();
7990 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7991 return LHS;
7992 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7993 return RHS;
7994 return getPipeType(ResultType);
7995 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007996 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007997
David Blaikie8a40f702012-01-17 06:56:22 +00007998 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007999}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008000
John McCall18afab72016-03-01 00:49:02 +00008001bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8002 const FunctionProtoType *firstFnType,
8003 const FunctionProtoType *secondFnType) {
8004 // Fast path: if the first type doesn't have ext parameter infos,
8005 // we match if and only if they second type also doesn't have them.
8006 if (!firstFnType->hasExtParameterInfos())
8007 return !secondFnType->hasExtParameterInfos();
8008
8009 // Otherwise, we can only match if the second type has them.
8010 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008011 return false;
John McCall18afab72016-03-01 00:49:02 +00008012
8013 auto firstEPI = firstFnType->getExtParameterInfos();
8014 auto secondEPI = secondFnType->getExtParameterInfos();
8015 assert(firstEPI.size() == secondEPI.size());
8016
8017 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8018 if (firstEPI[i] != secondEPI[i])
8019 return false;
8020 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008021 return true;
8022}
8023
Chandler Carruth21c90602015-12-30 03:24:14 +00008024void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8025 ObjCLayouts[CD] = nullptr;
8026}
8027
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008028/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8029/// 'RHS' attributes and returns the merged version; including for function
8030/// return types.
8031QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8032 QualType LHSCan = getCanonicalType(LHS),
8033 RHSCan = getCanonicalType(RHS);
8034 // If two types are identical, they are compatible.
8035 if (LHSCan == RHSCan)
8036 return LHS;
8037 if (RHSCan->isFunctionType()) {
8038 if (!LHSCan->isFunctionType())
8039 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008040 QualType OldReturnType =
8041 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008042 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008043 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008044 QualType ResReturnType =
8045 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8046 if (ResReturnType.isNull())
8047 return QualType();
8048 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8049 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8050 // In either case, use OldReturnType to build the new function type.
8051 const FunctionType *F = LHS->getAs<FunctionType>();
8052 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008053 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8054 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008055 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008056 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008057 return ResultType;
8058 }
8059 }
8060 return QualType();
8061 }
8062
8063 // If the qualifiers are different, the types can still be merged.
8064 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8065 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8066 if (LQuals != RQuals) {
8067 // If any of these qualifiers are different, we have a type mismatch.
8068 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8069 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8070 return QualType();
8071
8072 // Exactly one GC qualifier difference is allowed: __strong is
8073 // okay if the other type has no GC qualifier but is an Objective
8074 // C object pointer (i.e. implicitly strong by default). We fix
8075 // this by pretending that the unqualified type was actually
8076 // qualified __strong.
8077 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8078 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8079 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8080
8081 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8082 return QualType();
8083
8084 if (GC_L == Qualifiers::Strong)
8085 return LHS;
8086 if (GC_R == Qualifiers::Strong)
8087 return RHS;
8088 return QualType();
8089 }
8090
8091 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8092 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8093 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8094 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8095 if (ResQT == LHSBaseQT)
8096 return LHS;
8097 if (ResQT == RHSBaseQT)
8098 return RHS;
8099 }
8100 return QualType();
8101}
8102
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008103//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008104// Integer Predicates
8105//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008106
Jay Foad39c79802011-01-12 09:06:06 +00008107unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008108 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008109 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008110 if (T->isBooleanType())
8111 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008112 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008113 return (unsigned)getTypeSize(T);
8114}
8115
Abramo Bagnara13640492012-09-09 10:21:24 +00008116QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008117 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008118
8119 // Turn <4 x signed int> -> <4 x unsigned int>
8120 if (const VectorType *VTy = T->getAs<VectorType>())
8121 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008122 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008123
8124 // For enums, we return the unsigned version of the base type.
8125 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008126 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008127
8128 const BuiltinType *BTy = T->getAs<BuiltinType>();
8129 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008130 switch (BTy->getKind()) {
8131 case BuiltinType::Char_S:
8132 case BuiltinType::SChar:
8133 return UnsignedCharTy;
8134 case BuiltinType::Short:
8135 return UnsignedShortTy;
8136 case BuiltinType::Int:
8137 return UnsignedIntTy;
8138 case BuiltinType::Long:
8139 return UnsignedLongTy;
8140 case BuiltinType::LongLong:
8141 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008142 case BuiltinType::Int128:
8143 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008144 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008145 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008146 }
8147}
8148
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008149ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008150
Richard Smith1fa5d642013-05-11 05:45:24 +00008151void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8152 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008153
8154//===----------------------------------------------------------------------===//
8155// Builtin Type Computation
8156//===----------------------------------------------------------------------===//
8157
8158/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008159/// pointer over the consumed characters. This returns the resultant type. If
8160/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8161/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8162/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008163///
8164/// RequiresICE is filled in on return to indicate whether the value is required
8165/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008166static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008167 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008168 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008169 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008170 // Modifiers.
8171 int HowLong = 0;
8172 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008173 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008174
Chris Lattnerdc226c22010-10-01 22:42:38 +00008175 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008176 bool Done = false;
8177 while (!Done) {
8178 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008179 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008180 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008181 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008182 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008183 case 'S':
8184 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8185 assert(!Signed && "Can't use 'S' modifier multiple times!");
8186 Signed = true;
8187 break;
8188 case 'U':
8189 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008190 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008191 Unsigned = true;
8192 break;
8193 case 'L':
8194 assert(HowLong <= 2 && "Can't have LLLL modifier");
8195 ++HowLong;
8196 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008197 case 'W':
8198 // This modifier represents int64 type.
8199 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8200 switch (Context.getTargetInfo().getInt64Type()) {
8201 default:
8202 llvm_unreachable("Unexpected integer type");
8203 case TargetInfo::SignedLong:
8204 HowLong = 1;
8205 break;
8206 case TargetInfo::SignedLongLong:
8207 HowLong = 2;
8208 break;
8209 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008210 }
8211 }
8212
8213 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008214
Chris Lattnerecd79c62009-06-14 00:45:47 +00008215 // Read the base type.
8216 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008217 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008218 case 'v':
8219 assert(HowLong == 0 && !Signed && !Unsigned &&
8220 "Bad modifiers used with 'v'!");
8221 Type = Context.VoidTy;
8222 break;
Jack Carter24bef982013-08-15 15:16:57 +00008223 case 'h':
8224 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008225 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008226 Type = Context.HalfTy;
8227 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008228 case 'f':
8229 assert(HowLong == 0 && !Signed && !Unsigned &&
8230 "Bad modifiers used with 'f'!");
8231 Type = Context.FloatTy;
8232 break;
8233 case 'd':
8234 assert(HowLong < 2 && !Signed && !Unsigned &&
8235 "Bad modifiers used with 'd'!");
8236 if (HowLong)
8237 Type = Context.LongDoubleTy;
8238 else
8239 Type = Context.DoubleTy;
8240 break;
8241 case 's':
8242 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8243 if (Unsigned)
8244 Type = Context.UnsignedShortTy;
8245 else
8246 Type = Context.ShortTy;
8247 break;
8248 case 'i':
8249 if (HowLong == 3)
8250 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8251 else if (HowLong == 2)
8252 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8253 else if (HowLong == 1)
8254 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8255 else
8256 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8257 break;
8258 case 'c':
8259 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8260 if (Signed)
8261 Type = Context.SignedCharTy;
8262 else if (Unsigned)
8263 Type = Context.UnsignedCharTy;
8264 else
8265 Type = Context.CharTy;
8266 break;
8267 case 'b': // boolean
8268 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8269 Type = Context.BoolTy;
8270 break;
8271 case 'z': // size_t.
8272 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8273 Type = Context.getSizeType();
8274 break;
8275 case 'F':
8276 Type = Context.getCFConstantStringType();
8277 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008278 case 'G':
8279 Type = Context.getObjCIdType();
8280 break;
8281 case 'H':
8282 Type = Context.getObjCSelType();
8283 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008284 case 'M':
8285 Type = Context.getObjCSuperType();
8286 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008287 case 'a':
8288 Type = Context.getBuiltinVaListType();
8289 assert(!Type.isNull() && "builtin va list type not initialized!");
8290 break;
8291 case 'A':
8292 // This is a "reference" to a va_list; however, what exactly
8293 // this means depends on how va_list is defined. There are two
8294 // different kinds of va_list: ones passed by value, and ones
8295 // passed by reference. An example of a by-value va_list is
8296 // x86, where va_list is a char*. An example of by-ref va_list
8297 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8298 // we want this argument to be a char*&; for x86-64, we want
8299 // it to be a __va_list_tag*.
8300 Type = Context.getBuiltinVaListType();
8301 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008302 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008303 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008304 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008305 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008306 break;
8307 case 'V': {
8308 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008309 unsigned NumElements = strtoul(Str, &End, 10);
8310 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008311 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008312
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008313 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8314 RequiresICE, false);
8315 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008316
8317 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008318 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008319 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008320 break;
8321 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008322 case 'E': {
8323 char *End;
8324
8325 unsigned NumElements = strtoul(Str, &End, 10);
8326 assert(End != Str && "Missing vector size");
8327
8328 Str = End;
8329
8330 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8331 false);
8332 Type = Context.getExtVectorType(ElementType, NumElements);
8333 break;
8334 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008335 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008336 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8337 false);
8338 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008339 Type = Context.getComplexType(ElementType);
8340 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008341 }
8342 case 'Y' : {
8343 Type = Context.getPointerDiffType();
8344 break;
8345 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008346 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008347 Type = Context.getFILEType();
8348 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008349 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008350 return QualType();
8351 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008352 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008353 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008354 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008355 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008356 else
8357 Type = Context.getjmp_bufType();
8358
Mike Stump2adb4da2009-07-28 23:47:15 +00008359 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008360 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008361 return QualType();
8362 }
8363 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008364 case 'K':
8365 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8366 Type = Context.getucontext_tType();
8367
8368 if (Type.isNull()) {
8369 Error = ASTContext::GE_Missing_ucontext;
8370 return QualType();
8371 }
8372 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008373 case 'p':
8374 Type = Context.getProcessIDType();
8375 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008376 }
Mike Stump11289f42009-09-09 15:08:12 +00008377
Chris Lattnerdc226c22010-10-01 22:42:38 +00008378 // If there are modifiers and if we're allowed to parse them, go for it.
8379 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008380 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008381 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008382 default: Done = true; --Str; break;
8383 case '*':
8384 case '&': {
8385 // Both pointers and references can have their pointee types
8386 // qualified with an address space.
8387 char *End;
8388 unsigned AddrSpace = strtoul(Str, &End, 10);
8389 if (End != Str && AddrSpace != 0) {
8390 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8391 Str = End;
8392 }
8393 if (c == '*')
8394 Type = Context.getPointerType(Type);
8395 else
8396 Type = Context.getLValueReferenceType(Type);
8397 break;
8398 }
8399 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8400 case 'C':
8401 Type = Type.withConst();
8402 break;
8403 case 'D':
8404 Type = Context.getVolatileType(Type);
8405 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008406 case 'R':
8407 Type = Type.withRestrict();
8408 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008409 }
8410 }
Chris Lattner84733392010-10-01 07:13:18 +00008411
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008412 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008413 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008414
Chris Lattnerecd79c62009-06-14 00:45:47 +00008415 return Type;
8416}
8417
8418/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008419QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008420 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008421 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008422 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008423
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008424 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008425
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008426 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008427 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008428 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8429 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008430 if (Error != GE_None)
8431 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008432
8433 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8434
Chris Lattnerecd79c62009-06-14 00:45:47 +00008435 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008436 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008437 if (Error != GE_None)
8438 return QualType();
8439
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008440 // If this argument is required to be an IntegerConstantExpression and the
8441 // caller cares, fill in the bitmask we return.
8442 if (RequiresICE && IntegerConstantArgs)
8443 *IntegerConstantArgs |= 1 << ArgTypes.size();
8444
Chris Lattnerecd79c62009-06-14 00:45:47 +00008445 // Do array -> pointer decay. The builtin should use the decayed type.
8446 if (Ty->isArrayType())
8447 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008448
Chris Lattnerecd79c62009-06-14 00:45:47 +00008449 ArgTypes.push_back(Ty);
8450 }
8451
David Majnemerba3e5ec2015-03-13 18:26:17 +00008452 if (Id == Builtin::BI__GetExceptionInfo)
8453 return QualType();
8454
Chris Lattnerecd79c62009-06-14 00:45:47 +00008455 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8456 "'.' should only occur at end of builtin type list!");
8457
Reid Kleckner78af0702013-08-27 23:08:25 +00008458 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008459 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8460
8461 bool Variadic = (TypeStr[0] == '.');
8462
8463 // We really shouldn't be making a no-proto type here, especially in C++.
8464 if (ArgTypes.empty() && Variadic)
8465 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008466
John McCalldb40c7f2010-12-14 08:05:40 +00008467 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008468 EPI.ExtInfo = EI;
8469 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008470
Jordan Rose5c382722013-03-08 21:51:21 +00008471 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008472}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008473
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008474static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8475 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008476 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008477 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008478
Rafael Espindola3ae00052013-05-13 00:12:11 +00008479 GVALinkage External = GVA_StrongExternal;
8480 switch (FD->getTemplateSpecializationKind()) {
8481 case TSK_Undeclared:
8482 case TSK_ExplicitSpecialization:
8483 External = GVA_StrongExternal;
8484 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008485
Rafael Espindola3ae00052013-05-13 00:12:11 +00008486 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008487 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008488
David Majnemerc3d07332014-05-15 06:25:57 +00008489 // C++11 [temp.explicit]p10:
8490 // [ Note: The intent is that an inline function that is the subject of
8491 // an explicit instantiation declaration will still be implicitly
8492 // instantiated when used so that the body can be considered for
8493 // inlining, but that no out-of-line copy of the inline function would be
8494 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008495 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008496 return GVA_AvailableExternally;
8497
Rafael Espindola3ae00052013-05-13 00:12:11 +00008498 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008499 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008500 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008501 }
8502
8503 if (!FD->isInlined())
8504 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008505
David Majnemer3f021502015-10-08 04:53:31 +00008506 if ((!Context.getLangOpts().CPlusPlus &&
8507 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008508 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008509 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008510 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8511
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008512 // GNU or C99 inline semantics. Determine whether this symbol should be
8513 // externally visible.
8514 if (FD->isInlineDefinitionExternallyVisible())
8515 return External;
8516
8517 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008518 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008519 }
8520
David Majnemer54e3ba52014-04-02 23:17:29 +00008521 // Functions specified with extern and inline in -fms-compatibility mode
8522 // forcibly get emitted. While the body of the function cannot be later
8523 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008524 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008525 return GVA_StrongODR;
8526
David Majnemer27d69db2014-04-28 22:17:59 +00008527 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008528}
8529
Artem Belevichca2b9512016-05-02 20:30:03 +00008530static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8531 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008532 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8533 // dllexport/dllimport on inline functions.
8534 if (D->hasAttr<DLLImportAttr>()) {
8535 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8536 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008537 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008538 if (L == GVA_DiscardableODR)
8539 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008540 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8541 D->hasAttr<CUDAGlobalAttr>()) {
8542 // Device-side functions with __global__ attribute must always be
8543 // visible externally so they can be launched from host.
8544 if (L == GVA_DiscardableODR || L == GVA_Internal)
8545 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008546 }
8547 return L;
8548}
8549
8550GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008551 return adjustGVALinkageForAttributes(
8552 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008553}
8554
8555static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8556 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008557 if (!VD->isExternallyVisible())
8558 return GVA_Internal;
8559
David Majnemer27d69db2014-04-28 22:17:59 +00008560 if (VD->isStaticLocal()) {
8561 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8562 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8563 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8564 LexicalContext = LexicalContext->getLexicalParent();
8565
Richard Smith9e2341d2015-03-23 03:25:59 +00008566 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008567 // enclosing function.
8568 if (LexicalContext)
8569 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008570 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008571
8572 // GVA_StrongODR function linkage is stronger than what we need,
8573 // downgrade to GVA_DiscardableODR.
8574 // This allows us to discard the variable if we never end up needing it.
8575 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8576 : StaticLocalLinkage;
8577 }
8578
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008579 // MSVC treats in-class initialized static data members as definitions.
8580 // By giving them non-strong linkage, out-of-line definitions won't
8581 // cause link errors.
8582 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8583 return GVA_DiscardableODR;
8584
Richard Smithd9b90092016-07-02 01:32:16 +00008585 // Most non-template variables have strong linkage; inline variables are
8586 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8587 GVALinkage StrongLinkage;
8588 switch (Context.getInlineVariableDefinitionKind(VD)) {
8589 case ASTContext::InlineVariableDefinitionKind::None:
8590 StrongLinkage = GVA_StrongExternal;
8591 break;
8592 case ASTContext::InlineVariableDefinitionKind::Weak:
8593 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008594 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008595 break;
8596 case ASTContext::InlineVariableDefinitionKind::Strong:
8597 StrongLinkage = GVA_StrongODR;
8598 break;
8599 }
Richard Smith62f19e72016-06-25 00:15:56 +00008600
Richard Smith8809a0c2013-09-27 20:14:12 +00008601 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008602 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008603 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008604
David Majnemer6d1780c2015-07-17 23:36:49 +00008605 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008606 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8607 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008608 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008609 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008610
Rafael Espindola3ae00052013-05-13 00:12:11 +00008611 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008612 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008613
David Majnemer27d69db2014-04-28 22:17:59 +00008614 case TSK_ExplicitInstantiationDeclaration:
8615 return GVA_AvailableExternally;
8616
Rafael Espindola3ae00052013-05-13 00:12:11 +00008617 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008618 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008619 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008620
8621 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008622}
8623
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008624GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008625 return adjustGVALinkageForAttributes(
8626 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008627}
8628
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008629bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008630 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8631 if (!VD->isFileVarDecl())
8632 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008633 // Global named register variables (GNU extension) are never emitted.
8634 if (VD->getStorageClass() == SC_Register)
8635 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008636 if (VD->getDescribedVarTemplate() ||
8637 isa<VarTemplatePartialSpecializationDecl>(VD))
8638 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008639 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8640 // We never need to emit an uninstantiated function template.
8641 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8642 return false;
Nico Weber66220292016-03-02 17:28:48 +00008643 } else if (isa<PragmaCommentDecl>(D))
8644 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008645 else if (isa<OMPThreadPrivateDecl>(D) ||
8646 D->hasAttr<OMPDeclareTargetDeclAttr>())
8647 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008648 else if (isa<PragmaDetectMismatchDecl>(D))
8649 return true;
Nico Weber66220292016-03-02 17:28:48 +00008650 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008651 return !D->getDeclContext()->isDependentContext();
8652 else if (isa<OMPDeclareReductionDecl>(D))
8653 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00008654 else if (isa<ImportDecl>(D))
8655 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00008656 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008657 return false;
8658
8659 // If this is a member of a class template, we do not need to emit it.
8660 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008661 return false;
8662
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008663 // Weak references don't produce any output by themselves.
8664 if (D->hasAttr<WeakRefAttr>())
8665 return false;
8666
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008667 // Aliases and used decls are required.
8668 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8669 return true;
8670
8671 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8672 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008673 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008674 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008675
8676 // Constructors and destructors are required.
8677 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8678 return true;
8679
John McCall6bd2a892013-01-25 22:31:03 +00008680 // The key function for a class is required. This rule only comes
8681 // into play when inline functions can be key functions, though.
8682 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8683 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8684 const CXXRecordDecl *RD = MD->getParent();
8685 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8686 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8687 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8688 return true;
8689 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008690 }
8691 }
8692
8693 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8694
8695 // static, static inline, always_inline, and extern inline functions can
8696 // always be deferred. Normal inline functions can be deferred in C99/C++.
8697 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008698 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8699 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008700 return false;
8701 return true;
8702 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008703
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008704 const VarDecl *VD = cast<VarDecl>(D);
8705 assert(VD->isFileVarDecl() && "Expected file scoped var");
8706
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008707 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8708 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008709 return false;
8710
Richard Smitha0e5e542012-11-12 21:38:00 +00008711 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008712 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008713 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8714 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008715 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008716
Richard Smitha0e5e542012-11-12 21:38:00 +00008717 // Variables that have destruction with side-effects are required.
8718 if (VD->getType().isDestructedType())
8719 return true;
8720
8721 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008722 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8723 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008724 return true;
8725
Richard Smithda383632016-08-15 01:33:41 +00008726 // Likewise, variables with tuple-like bindings are required if their
8727 // bindings have side-effects.
8728 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
8729 for (auto *BD : DD->bindings())
8730 if (auto *BindingVD = BD->getHoldingVar())
8731 if (DeclMustBeEmitted(BindingVD))
8732 return true;
8733
Richard Smitha0e5e542012-11-12 21:38:00 +00008734 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008735}
Charles Davis53c59df2010-08-16 03:33:14 +00008736
Reid Kleckner78af0702013-08-27 23:08:25 +00008737CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8738 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008739 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008740 if (IsCXXMethod)
8741 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008742
Alexey Bataeva7547182016-05-18 09:06:38 +00008743 switch (LangOpts.getDefaultCallingConv()) {
8744 case LangOptions::DCC_None:
8745 break;
8746 case LangOptions::DCC_CDecl:
8747 return CC_C;
8748 case LangOptions::DCC_FastCall:
8749 if (getTargetInfo().hasFeature("sse2"))
8750 return CC_X86FastCall;
8751 break;
8752 case LangOptions::DCC_StdCall:
8753 if (!IsVariadic)
8754 return CC_X86StdCall;
8755 break;
8756 case LangOptions::DCC_VectorCall:
8757 // __vectorcall cannot be applied to variadic functions.
8758 if (!IsVariadic)
8759 return CC_X86VectorCall;
8760 break;
8761 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008762 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008763}
8764
Jay Foad39c79802011-01-12 09:06:06 +00008765bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008766 // Pass through to the C++ ABI object
8767 return ABI->isNearlyEmpty(RD);
8768}
8769
Reid Kleckner96f8f932014-02-05 17:27:08 +00008770VTableContextBase *ASTContext::getVTableContext() {
8771 if (!VTContext.get()) {
8772 if (Target->getCXXABI().isMicrosoft())
8773 VTContext.reset(new MicrosoftVTableContext(*this));
8774 else
8775 VTContext.reset(new ItaniumVTableContext(*this));
8776 }
8777 return VTContext.get();
8778}
8779
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008780MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008781 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008782 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008783 case TargetCXXABI::GenericItanium:
8784 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008785 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008786 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008787 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008788 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008789 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008790 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008791 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008792 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008793 }
David Blaikie83d382b2011-09-23 05:06:16 +00008794 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008795}
8796
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008797CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008798
8799size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008800 return ASTRecordLayouts.getMemorySize() +
8801 llvm::capacity_in_bytes(ObjCLayouts) +
8802 llvm::capacity_in_bytes(KeyFunctions) +
8803 llvm::capacity_in_bytes(ObjCImpls) +
8804 llvm::capacity_in_bytes(BlockVarCopyInits) +
8805 llvm::capacity_in_bytes(DeclAttrs) +
8806 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8807 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8808 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8809 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8810 llvm::capacity_in_bytes(OverriddenMethods) +
8811 llvm::capacity_in_bytes(Types) +
8812 llvm::capacity_in_bytes(VariableArrayTypes) +
8813 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008814}
Ted Kremenek540017e2011-10-06 05:00:56 +00008815
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008816/// getIntTypeForBitwidth -
8817/// sets integer QualTy according to specified details:
8818/// bitwidth, signed/unsigned.
8819/// Returns empty type if there is no appropriate target types.
8820QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8821 unsigned Signed) const {
8822 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8823 CanQualType QualTy = getFromTargetType(Ty);
8824 if (!QualTy && DestWidth == 128)
8825 return Signed ? Int128Ty : UnsignedInt128Ty;
8826 return QualTy;
8827}
8828
8829/// getRealTypeForBitwidth -
8830/// sets floating point QualTy according to specified bitwidth.
8831/// Returns empty type if there is no appropriate target types.
8832QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8833 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8834 switch (Ty) {
8835 case TargetInfo::Float:
8836 return FloatTy;
8837 case TargetInfo::Double:
8838 return DoubleTy;
8839 case TargetInfo::LongDouble:
8840 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00008841 case TargetInfo::Float128:
8842 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008843 case TargetInfo::NoFloat:
8844 return QualType();
8845 }
8846
8847 llvm_unreachable("Unhandled TargetInfo::RealType value");
8848}
8849
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008850void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8851 if (Number > 1)
8852 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008853}
8854
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008855unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008856 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008857 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008858}
8859
David Majnemer2206bf52014-03-05 08:57:59 +00008860void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8861 if (Number > 1)
8862 StaticLocalNumbers[VD] = Number;
8863}
8864
8865unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008866 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00008867 return I != StaticLocalNumbers.end() ? I->second : 1;
8868}
8869
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008870MangleNumberingContext &
8871ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008872 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8873 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8874 if (!MCtx)
8875 MCtx = createMangleNumberingContext();
8876 return *MCtx;
8877}
8878
8879MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8880 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008881}
8882
David Majnemere7a818f2015-03-06 18:53:55 +00008883const CXXConstructorDecl *
8884ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8885 return ABI->getCopyConstructorForExceptionObject(
8886 cast<CXXRecordDecl>(RD->getFirstDecl()));
8887}
8888
8889void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8890 CXXConstructorDecl *CD) {
8891 return ABI->addCopyConstructorForExceptionObject(
8892 cast<CXXRecordDecl>(RD->getFirstDecl()),
8893 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8894}
8895
David Majnemerdfa6d202015-03-11 18:36:39 +00008896void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8897 unsigned ParmIdx, Expr *DAE) {
8898 ABI->addDefaultArgExprForConstructor(
8899 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8900}
8901
8902Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8903 unsigned ParmIdx) {
8904 return ABI->getDefaultArgExprForConstructor(
8905 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8906}
8907
David Majnemer00350522015-08-31 18:48:39 +00008908void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8909 TypedefNameDecl *DD) {
8910 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8911}
8912
8913TypedefNameDecl *
8914ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8915 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8916}
8917
8918void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8919 DeclaratorDecl *DD) {
8920 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8921}
8922
8923DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8924 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8925}
8926
Ted Kremenek540017e2011-10-06 05:00:56 +00008927void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8928 ParamIndices[D] = index;
8929}
8930
8931unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8932 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8933 assert(I != ParamIndices.end() &&
8934 "ParmIndices lacks entry set by ParmVarDecl");
8935 return I->second;
8936}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008937
Richard Smithe6c01442013-06-05 00:46:14 +00008938APValue *
8939ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8940 bool MayCreate) {
8941 assert(E && E->getStorageDuration() == SD_Static &&
8942 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008943 if (MayCreate) {
8944 APValue *&MTVI = MaterializedTemporaryValues[E];
8945 if (!MTVI)
8946 MTVI = new (*this) APValue;
8947 return MTVI;
8948 }
Richard Smithe6c01442013-06-05 00:46:14 +00008949
David Majnemer2dcef9e2015-08-13 23:50:15 +00008950 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008951}
8952
Fariborz Jahanian615de762013-05-28 17:37:39 +00008953bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8954 const llvm::Triple &T = getTargetInfo().getTriple();
8955 if (!T.isOSDarwin())
8956 return false;
8957
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008958 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8959 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8960 return false;
8961
Fariborz Jahanian615de762013-05-28 17:37:39 +00008962 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8963 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8964 uint64_t Size = sizeChars.getQuantity();
8965 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8966 unsigned Align = alignChars.getQuantity();
8967 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8968 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8969}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008970
8971namespace {
8972
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008973ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8974 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008975 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008976 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008977 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008978 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008979 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008980}
8981
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008982/// Template specializations to abstract away from pointers and TypeLocs.
8983/// @{
8984template <typename T>
8985ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8986 return ast_type_traits::DynTypedNode::create(*Node);
8987}
8988template <>
8989ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8990 return ast_type_traits::DynTypedNode::create(Node);
8991}
8992template <>
8993ast_type_traits::DynTypedNode
8994createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8995 return ast_type_traits::DynTypedNode::create(Node);
8996}
8997/// @}
8998
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008999 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9000 /// parents as defined by the \c RecursiveASTVisitor.
9001 ///
9002 /// Note that the relationship described here is purely in terms of AST
9003 /// traversal - there are other relationships (for example declaration context)
9004 /// in the AST that are better modeled by special matchers.
9005 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009006 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009007 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009008 public:
9009 /// \brief Builds and returns the translation unit's parent map.
9010 ///
9011 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009012 static std::pair<ASTContext::ParentMapPointers *,
9013 ASTContext::ParentMapOtherNodes *>
9014 buildMap(TranslationUnitDecl &TU) {
9015 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9016 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009017 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009018 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009019 }
9020
9021 private:
9022 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9023
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009024 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9025 ASTContext::ParentMapOtherNodes *OtherParents)
9026 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009027
9028 bool shouldVisitTemplateInstantiations() const {
9029 return true;
9030 }
9031 bool shouldVisitImplicitCode() const {
9032 return true;
9033 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009034
Richard Smith85838722015-11-24 03:09:01 +00009035 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9036 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009037 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009038 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009039 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009040 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009041 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009042 // FIXME: Currently we add the same parent multiple times, but only
9043 // when no memoization data is available for the type.
9044 // For example when we visit all subexpressions of template
9045 // instantiations; this is suboptimal, but benign: the only way to
9046 // visit those is with hasAncestor / hasParent, and those do not create
9047 // new matches.
9048 // The plan is to enable DynTypedNode to be storable in a map or hash
9049 // map. The main problem there is to implement hash functions /
9050 // comparison operators for all types that DynTypedNode supports that
9051 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009052 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009053 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009054 if (const auto *D = ParentStack.back().get<Decl>())
9055 NodeOrVector = D;
9056 else if (const auto *S = ParentStack.back().get<Stmt>())
9057 NodeOrVector = S;
9058 else
9059 NodeOrVector =
9060 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009061 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009062 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9063 auto *Vector = new ASTContext::ParentVector(
9064 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009065 if (auto *Node =
9066 NodeOrVector
9067 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9068 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009069 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009070 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009071
9072 auto *Vector =
9073 NodeOrVector.template get<ASTContext::ParentVector *>();
9074 // Skip duplicates for types that have memoization data.
9075 // We must check that the type has memoization data before calling
9076 // std::find() because DynTypedNode::operator== can't compare all
9077 // types.
9078 bool Found = ParentStack.back().getMemoizationData() &&
9079 std::find(Vector->begin(), Vector->end(),
9080 ParentStack.back()) != Vector->end();
9081 if (!Found)
9082 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009083 }
9084 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009085 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009086 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009087 ParentStack.pop_back();
9088 return Result;
9089 }
9090
9091 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009092 return TraverseNode(DeclNode, DeclNode,
9093 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009094 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009095 }
9096
9097 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009098 return TraverseNode(StmtNode, StmtNode,
9099 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009100 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009101 }
9102
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009103 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009104 return TraverseNode(
9105 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9106 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9107 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009108 }
9109
9110 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9111 return TraverseNode(
9112 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009113 [&] {
9114 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9115 },
9116 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009117 }
9118
9119 ASTContext::ParentMapPointers *Parents;
9120 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009121 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9122
9123 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9124 };
9125
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009126} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009127
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009128template <typename NodeTy, typename MapTy>
9129static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9130 const MapTy &Map) {
9131 auto I = Map.find(Node);
9132 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009133 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009134 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009135 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009136 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009137 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009138 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009139}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009140
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009141ASTContext::DynTypedNodeList
9142ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9143 if (!PointerParents) {
9144 // We always need to run over the whole translation unit, as
9145 // hasAncestor can escape any subtree.
9146 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9147 PointerParents.reset(Maps.first);
9148 OtherParents.reset(Maps.second);
9149 }
9150 if (Node.getNodeKind().hasPointerIdentity())
9151 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9152 return getDynNodeFromMap(Node, *OtherParents);
9153}
9154
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009155bool
9156ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9157 const ObjCMethodDecl *MethodImpl) {
9158 // No point trying to match an unavailable/deprecated mothod.
9159 if (MethodDecl->hasAttr<UnavailableAttr>()
9160 || MethodDecl->hasAttr<DeprecatedAttr>())
9161 return false;
9162 if (MethodDecl->getObjCDeclQualifier() !=
9163 MethodImpl->getObjCDeclQualifier())
9164 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009165 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009166 return false;
9167
9168 if (MethodDecl->param_size() != MethodImpl->param_size())
9169 return false;
9170
9171 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9172 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9173 EF = MethodDecl->param_end();
9174 IM != EM && IF != EF; ++IM, ++IF) {
9175 const ParmVarDecl *DeclVar = (*IF);
9176 const ParmVarDecl *ImplVar = (*IM);
9177 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9178 return false;
9179 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9180 return false;
9181 }
9182 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9183
9184}
Richard Smith053f6c62014-05-16 23:01:30 +00009185
9186// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9187// doesn't include ASTContext.h
9188template
9189clang::LazyGenerationalUpdatePtr<
9190 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9191clang::LazyGenerationalUpdatePtr<
9192 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9193 const clang::ASTContext &Ctx, Decl *Value);