blob: cf7f5947a2f222ed6cec9c0a384cdcc987999220 [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
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000662 CanonParams,
Hubert Tong286547a2016-07-20 01:05:31 +0000663 SourceLocation()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664
665 // Get the new insert position for the node we care about.
666 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000667 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000668 (void)Canonical;
669
670 // Create the canonical template template parameter entry.
671 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
672 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
673 return CanonTTP;
674}
675
Charles Davis53c59df2010-08-16 03:33:14 +0000676CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000677 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000678
John McCall359b8852013-01-25 22:30:49 +0000679 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000680 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000681 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000682 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000683 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000687 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000688 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000690 return CreateMicrosoftCXXABI(*this);
691 }
David Blaikie8a40f702012-01-17 06:56:22 +0000692 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000693}
694
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 const LangOptions &LOpts) {
697 if (LOpts.FakeAddressSpaceMap) {
698 // The fake address space map must have a distinct entry for each
699 // language-specific address space.
700 static const unsigned FakeAddrSpaceMap[] = {
701 1, // opencl_global
702 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000703 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000704 4, // opencl_generic
705 5, // cuda_device
706 6, // cuda_constant
707 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 }
713}
714
David Tweed31d09b02013-09-13 12:04:22 +0000715static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
716 const LangOptions &LangOpts) {
717 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000718 case LangOptions::ASMM_Target:
719 return TI.useAddressSpaceMapMangling();
720 case LangOptions::ASMM_On:
721 return true;
722 case LangOptions::ASMM_Off:
723 return false;
724 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000725 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000726}
727
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000728ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000729 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000730 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
732 DependentTemplateSpecializationTypes(this_()),
733 SubstTemplateTemplateParmPacks(this_()),
734 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000735 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
736 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
737 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000738 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
739 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
740 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
741 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
742 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000743 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
744 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000745 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000746 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
747 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
748 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
749 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000750 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751 TUDecl = TranslationUnitDecl::Create(*this);
752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000755 ReleaseParentMapEntries();
756
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000757 // Release the DenseMaps associated with DeclContext objects.
758 // FIXME: Is this the ideal solution?
759 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000760
Manuel Klimeka7328992013-06-03 13:51:33 +0000761 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000762 for (auto &Pair : Deallocations)
763 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
David Majnemere694f3e2015-08-14 14:43:50 +0000786 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
787 MaterializedTemporaryValues)
788 MTVPair.second->~APValue();
789
Richard Smith423f46f2016-07-20 21:38:26 +0000790 for (const auto &Value : ModuleInitializers)
791 Value.second->~PerModuleInitializers();
792
Reid Kleckner588c9372014-02-19 23:44:52 +0000793 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000794}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000795
Manuel Klimek95403e62014-05-21 13:28:59 +0000796void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000797 if (!PointerParents) return;
798 for (const auto &Entry : *PointerParents) {
799 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
800 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
801 } else if (Entry.second.is<ParentVector *>()) {
802 delete Entry.second.get<ParentVector *>();
803 }
804 }
805 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000806 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
807 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000808 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000809 delete Entry.second.get<ParentVector *>();
810 }
811 }
812}
813
Douglas Gregor1a809332010-05-23 18:26:36 +0000814void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000815 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000816}
817
Mike Stump11289f42009-09-09 15:08:12 +0000818void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000819ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000820 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000821}
822
Chris Lattner4eb445d2007-01-26 01:27:23 +0000823void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000824 llvm::errs() << "\n*** AST Context Stats:\n";
825 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000826
Douglas Gregora30d0462009-05-26 14:40:08 +0000827 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000828#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000829#define ABSTRACT_TYPE(Name, Parent)
830#include "clang/AST/TypeNodes.def"
831 0 // Extra
832 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000833
Chris Lattner4eb445d2007-01-26 01:27:23 +0000834 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
835 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000836 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000837 }
838
Douglas Gregora30d0462009-05-26 14:40:08 +0000839 unsigned Idx = 0;
840 unsigned TotalBytes = 0;
841#define TYPE(Name, Parent) \
842 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000843 llvm::errs() << " " << counts[Idx] << " " << #Name \
844 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000845 TotalBytes += counts[Idx] * sizeof(Name##Type); \
846 ++Idx;
847#define ABSTRACT_TYPE(Name, Parent)
848#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000849
Chandler Carruth3c147a72011-07-04 05:32:14 +0000850 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
851
Douglas Gregor7454c562010-07-02 20:37:36 +0000852 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
854 << NumImplicitDefaultConstructors
855 << " implicit default constructors created\n";
856 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
857 << NumImplicitCopyConstructors
858 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
861 << NumImplicitMoveConstructors
862 << " implicit move constructors created\n";
863 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
864 << NumImplicitCopyAssignmentOperators
865 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000866 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
868 << NumImplicitMoveAssignmentOperators
869 << " implicit move assignment operators created\n";
870 llvm::errs() << NumImplicitDestructorsDeclared << "/"
871 << NumImplicitDestructors
872 << " implicit destructors created\n";
873
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000874 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000875 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000876 ExternalSource->PrintStats();
877 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000878
Douglas Gregor5b11d492010-07-25 17:53:33 +0000879 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000880}
881
Richard Smith42413142015-05-15 20:05:43 +0000882void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
883 bool NotifyListeners) {
884 if (NotifyListeners)
885 if (auto *Listener = getASTMutationListener())
886 Listener->RedefinedHiddenDefinition(ND, M);
887
888 if (getLangOpts().ModulesLocalVisibility)
889 MergedDefModules[ND].push_back(M);
890 else
891 ND->setHidden(false);
892}
893
894void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
895 auto It = MergedDefModules.find(ND);
896 if (It == MergedDefModules.end())
897 return;
898
899 auto &Merged = It->second;
900 llvm::DenseSet<Module*> Found;
901 for (Module *&M : Merged)
902 if (!Found.insert(M).second)
903 M = nullptr;
904 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
905}
906
Richard Smithdc1f0422016-07-20 19:10:16 +0000907void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
908 if (LazyInitializers.empty())
909 return;
910
911 auto *Source = Ctx.getExternalSource();
912 assert(Source && "lazy initializers but no external source");
913
914 auto LazyInits = std::move(LazyInitializers);
915 LazyInitializers.clear();
916
917 for (auto ID : LazyInits)
918 Initializers.push_back(Source->GetExternalDecl(ID));
919
920 assert(LazyInitializers.empty() &&
921 "GetExternalDecl for lazy module initializer added more inits");
922}
923
924void ASTContext::addModuleInitializer(Module *M, Decl *D) {
925 // One special case: if we add a module initializer that imports another
926 // module, and that module's only initializer is an ImportDecl, simplify.
927 if (auto *ID = dyn_cast<ImportDecl>(D)) {
928 auto It = ModuleInitializers.find(ID->getImportedModule());
929
930 // Maybe the ImportDecl does nothing at all. (Common case.)
931 if (It == ModuleInitializers.end())
932 return;
933
934 // Maybe the ImportDecl only imports another ImportDecl.
935 auto &Imported = *It->second;
936 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
937 Imported.resolve(*this);
938 auto *OnlyDecl = Imported.Initializers.front();
939 if (isa<ImportDecl>(OnlyDecl))
940 D = OnlyDecl;
941 }
942 }
943
944 auto *&Inits = ModuleInitializers[M];
945 if (!Inits)
946 Inits = new (*this) PerModuleInitializers;
947 Inits->Initializers.push_back(D);
948}
949
950void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
951 auto *&Inits = ModuleInitializers[M];
952 if (!Inits)
953 Inits = new (*this) PerModuleInitializers;
954 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
955 IDs.begin(), IDs.end());
956}
957
958ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
959 auto It = ModuleInitializers.find(M);
960 if (It == ModuleInitializers.end())
961 return None;
962
963 auto *Inits = It->second;
964 Inits->resolve(*this);
965 return Inits->Initializers;
966}
967
Richard Smithf19e1272015-03-07 00:04:49 +0000968ExternCContextDecl *ASTContext::getExternCContextDecl() const {
969 if (!ExternCContext)
970 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
971
972 return ExternCContext;
973}
974
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000975BuiltinTemplateDecl *
976ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
977 const IdentifierInfo *II) const {
978 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
979 BuiltinTemplate->setImplicit();
980 TUDecl->addDecl(BuiltinTemplate);
981
982 return BuiltinTemplate;
983}
984
985BuiltinTemplateDecl *
986ASTContext::getMakeIntegerSeqDecl() const {
987 if (!MakeIntegerSeqDecl)
988 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
989 getMakeIntegerSeqName());
990 return MakeIntegerSeqDecl;
991}
992
Eric Fiselier6ad68552016-07-01 01:24:09 +0000993BuiltinTemplateDecl *
994ASTContext::getTypePackElementDecl() const {
995 if (!TypePackElementDecl)
996 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
997 getTypePackElementName());
998 return TypePackElementDecl;
999}
1000
Alp Toker2dea15b2013-12-17 01:22:38 +00001001RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1002 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001003 SourceLocation Loc;
1004 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001005 if (getLangOpts().CPlusPlus)
1006 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1007 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001008 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001009 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1010 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001011 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001012 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1013 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 return NewDecl;
1015}
1016
1017TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1018 StringRef Name) const {
1019 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1020 TypedefDecl *NewDecl = TypedefDecl::Create(
1021 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1022 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1023 NewDecl->setImplicit();
1024 return NewDecl;
1025}
1026
Douglas Gregor801c99d2011-08-12 06:49:56 +00001027TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001028 if (!Int128Decl)
1029 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001030 return Int128Decl;
1031}
1032
1033TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001034 if (!UInt128Decl)
1035 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001036 return UInt128Decl;
1037}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001038
John McCall48f2d582009-10-23 23:03:21 +00001039void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001040 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001041 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001042 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001043}
1044
Artem Belevichb5bc9232015-09-22 17:23:22 +00001045void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1046 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001047 assert((!this->Target || this->Target == &Target) &&
1048 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001049 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001050
Douglas Gregore8bbc122011-09-02 00:18:52 +00001051 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001052 this->AuxTarget = AuxTarget;
1053
Douglas Gregore8bbc122011-09-02 00:18:52 +00001054 ABI.reset(createCXXABI(Target));
1055 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001056 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057
Chris Lattner970e54e2006-11-12 00:37:36 +00001058 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001059 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattner970e54e2006-11-12 00:37:36 +00001061 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001062 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001063 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001064 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001065 InitBuiltinType(CharTy, BuiltinType::Char_S);
1066 else
1067 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001068 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001069 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1070 InitBuiltinType(ShortTy, BuiltinType::Short);
1071 InitBuiltinType(IntTy, BuiltinType::Int);
1072 InitBuiltinType(LongTy, BuiltinType::Long);
1073 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattner970e54e2006-11-12 00:37:36 +00001075 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001076 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1077 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1078 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1079 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1080 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001081
Chris Lattner970e54e2006-11-12 00:37:36 +00001082 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001083 InitBuiltinType(FloatTy, BuiltinType::Float);
1084 InitBuiltinType(DoubleTy, BuiltinType::Double);
1085 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001086
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001087 // GNU extension, __float128 for IEEE quadruple precision
1088 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1089
Chris Lattnerf122cef2009-04-30 02:43:43 +00001090 // GNU extension, 128-bit integers.
1091 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1092 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1093
Hans Wennborg0d81e012013-05-10 10:08:40 +00001094 // C++ 3.9.1p5
1095 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1096 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1097 else // -fshort-wchar makes wchar_t be unsigned.
1098 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1099 if (LangOpts.CPlusPlus && LangOpts.WChar)
1100 WideCharTy = WCharTy;
1101 else {
1102 // C99 (or C++ using -fno-wchar).
1103 WideCharTy = getFromTargetType(Target.getWCharType());
1104 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001105
James Molloy36365542012-05-04 10:55:22 +00001106 WIntTy = getFromTargetType(Target.getWIntType());
1107
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001108 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1109 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1110 else // C99
1111 Char16Ty = getFromTargetType(Target.getChar16Type());
1112
1113 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1114 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1115 else // C99
1116 Char32Ty = getFromTargetType(Target.getChar32Type());
1117
Douglas Gregor4619e432008-12-05 23:32:09 +00001118 // Placeholder type for type-dependent expressions whose type is
1119 // completely unknown. No code should ever check a type against
1120 // DependentTy and users should never see it; however, it is here to
1121 // help diagnose failures to properly check for type-dependent
1122 // expressions.
1123 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124
John McCall36e7fe32010-10-12 00:20:44 +00001125 // Placeholder type for functions.
1126 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1127
John McCall0009fcc2011-04-26 20:42:42 +00001128 // Placeholder type for bound members.
1129 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1130
John McCall526ab472011-10-25 17:37:35 +00001131 // Placeholder type for pseudo-objects.
1132 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1133
John McCall31996342011-04-07 08:22:57 +00001134 // "any" type; useful for debugger-like clients.
1135 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1136
John McCall8a6b59a2011-10-17 18:09:15 +00001137 // Placeholder type for unbridged ARC casts.
1138 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1139
Eli Friedman34866c72012-08-31 00:14:07 +00001140 // Placeholder type for builtin functions.
1141 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1142
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001143 // Placeholder type for OMP array sections.
1144 if (LangOpts.OpenMP)
1145 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1146
Chris Lattner970e54e2006-11-12 00:37:36 +00001147 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001148 FloatComplexTy = getComplexType(FloatTy);
1149 DoubleComplexTy = getComplexType(DoubleTy);
1150 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001151 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001153 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001154 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1155 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001156 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001157
Alexey Bader954ba212016-04-08 13:40:33 +00001158 if (LangOpts.OpenCL) {
1159#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1160 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001161#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001162
Guy Benyei61054192013-02-07 10:55:47 +00001163 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001164 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001165 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1166 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1167 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1168 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001169 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001170
1171 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001172 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1173 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001174
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001175 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001176
1177 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001178
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001179 // void * type
1180 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001181
1182 // nullptr type (C++0x 2.14.7)
1183 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001184
1185 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1186 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001187
1188 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001189 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001190}
1191
David Blaikie9c902b52011-09-25 23:23:43 +00001192DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001193 return SourceMgr.getDiagnostics();
1194}
1195
Douglas Gregor561eceb2010-08-30 16:49:28 +00001196AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1197 AttrVec *&Result = DeclAttrs[D];
1198 if (!Result) {
1199 void *Mem = Allocate(sizeof(AttrVec));
1200 Result = new (Mem) AttrVec;
1201 }
1202
1203 return *Result;
1204}
1205
1206/// \brief Erase the attributes corresponding to the given declaration.
1207void ASTContext::eraseDeclAttrs(const Decl *D) {
1208 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1209 if (Pos != DeclAttrs.end()) {
1210 Pos->second->~AttrVec();
1211 DeclAttrs.erase(Pos);
1212 }
1213}
1214
Larisse Voufo39a1e502013-08-06 01:03:05 +00001215// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001216MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001217ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001218 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001219 return getTemplateOrSpecializationInfo(Var)
1220 .dyn_cast<MemberSpecializationInfo *>();
1221}
1222
1223ASTContext::TemplateOrSpecializationInfo
1224ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1225 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1226 TemplateOrInstantiation.find(Var);
1227 if (Pos == TemplateOrInstantiation.end())
1228 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001229
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001230 return Pos->second;
1231}
1232
Mike Stump11289f42009-09-09 15:08:12 +00001233void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001234ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001235 TemplateSpecializationKind TSK,
1236 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001237 assert(Inst->isStaticDataMember() && "Not a static data member");
1238 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001239 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1240 Tmpl, TSK, PointOfInstantiation));
1241}
1242
1243void
1244ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1245 TemplateOrSpecializationInfo TSI) {
1246 assert(!TemplateOrInstantiation[Inst] &&
1247 "Already noted what the variable was instantiated from");
1248 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001249}
1250
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001251FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1252 const FunctionDecl *FD){
1253 assert(FD && "Specialization is 0");
1254 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001255 = ClassScopeSpecializationPattern.find(FD);
1256 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001257 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001258
1259 return Pos->second;
1260}
1261
1262void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1263 FunctionDecl *Pattern) {
1264 assert(FD && "Specialization is 0");
1265 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001266 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001267}
1268
John McCalle61f2ba2009-11-18 02:36:19 +00001269NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001270ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001271 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001272 = InstantiatedFromUsingDecl.find(UUD);
1273 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001274 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001275
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001276 return Pos->second;
1277}
1278
1279void
John McCallb96ec562009-12-04 22:46:56 +00001280ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1281 assert((isa<UsingDecl>(Pattern) ||
1282 isa<UnresolvedUsingValueDecl>(Pattern) ||
1283 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1284 "pattern decl is not a using decl");
1285 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1286 InstantiatedFromUsingDecl[Inst] = Pattern;
1287}
1288
1289UsingShadowDecl *
1290ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1291 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1292 = InstantiatedFromUsingShadowDecl.find(Inst);
1293 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001294 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001295
1296 return Pos->second;
1297}
1298
1299void
1300ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1301 UsingShadowDecl *Pattern) {
1302 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1303 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001304}
1305
Anders Carlsson5da84842009-09-01 04:26:58 +00001306FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1307 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1308 = InstantiatedFromUnnamedFieldDecl.find(Field);
1309 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001310 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Anders Carlsson5da84842009-09-01 04:26:58 +00001312 return Pos->second;
1313}
1314
1315void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1316 FieldDecl *Tmpl) {
1317 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1318 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1319 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1320 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001321
Anders Carlsson5da84842009-09-01 04:26:58 +00001322 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1323}
1324
Douglas Gregor832940b2010-03-02 23:58:15 +00001325ASTContext::overridden_cxx_method_iterator
1326ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001327 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1328 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001329 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001330 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001331 return Pos->second.begin();
1332}
1333
1334ASTContext::overridden_cxx_method_iterator
1335ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001336 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1337 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001338 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001339 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001340 return Pos->second.end();
1341}
1342
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001343unsigned
1344ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001345 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1346 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001347 if (Pos == OverriddenMethods.end())
1348 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001349 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001350}
1351
Clement Courbet6ecaec82016-07-05 07:49:31 +00001352ASTContext::overridden_method_range
1353ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1354 return overridden_method_range(overridden_methods_begin(Method),
1355 overridden_methods_end(Method));
1356}
1357
Douglas Gregor832940b2010-03-02 23:58:15 +00001358void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1359 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001360 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001361 OverriddenMethods[Method].push_back(Overridden);
1362}
1363
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001364void ASTContext::getOverriddenMethods(
1365 const NamedDecl *D,
1366 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001367 assert(D);
1368
1369 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001370 Overridden.append(overridden_methods_begin(CXXMethod),
1371 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001372 return;
1373 }
1374
1375 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1376 if (!Method)
1377 return;
1378
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001379 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1380 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001381 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001382}
1383
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001384void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1385 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1386 assert(!Import->isFromASTFile() && "Non-local import declaration");
1387 if (!FirstLocalImport) {
1388 FirstLocalImport = Import;
1389 LastLocalImport = Import;
1390 return;
1391 }
1392
1393 LastLocalImport->NextLocalImport = Import;
1394 LastLocalImport = Import;
1395}
1396
Chris Lattner53cfe802007-07-18 17:52:12 +00001397//===----------------------------------------------------------------------===//
1398// Type Sizing and Analysis
1399//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001400
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001401/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1402/// scalar floating point type.
1403const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001404 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001405 assert(BT && "Not a floating point type!");
1406 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001407 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001408 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001409 case BuiltinType::Float: return Target->getFloatFormat();
1410 case BuiltinType::Double: return Target->getDoubleFormat();
1411 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001412 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001413 }
1414}
1415
Rafael Espindola71eccb32013-08-08 19:53:46 +00001416CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001417 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001418
John McCall94268702010-10-08 18:24:19 +00001419 bool UseAlignAttrOnly = false;
1420 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1421 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001422
John McCall94268702010-10-08 18:24:19 +00001423 // __attribute__((aligned)) can increase or decrease alignment
1424 // *except* on a struct or struct member, where it only increases
1425 // alignment unless 'packed' is also specified.
1426 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001427 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001428 // ignore that possibility; Sema should diagnose it.
1429 if (isa<FieldDecl>(D)) {
1430 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1431 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1432 } else {
1433 UseAlignAttrOnly = true;
1434 }
1435 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001436 else if (isa<FieldDecl>(D))
1437 UseAlignAttrOnly =
1438 D->hasAttr<PackedAttr>() ||
1439 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001440
John McCall4e819612011-01-20 07:57:12 +00001441 // If we're using the align attribute only, just ignore everything
1442 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001443 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001444 // do nothing
1445
John McCall94268702010-10-08 18:24:19 +00001446 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001447 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001448 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001449 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001450 T = RT->getPointeeType();
1451 else
1452 T = getPointerType(RT->getPointeeType());
1453 }
Richard Smithf6d70302014-06-10 23:34:28 +00001454 QualType BaseT = getBaseElementType(T);
1455 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001456 // Adjust alignments of declarations with array type by the
1457 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001458 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001459 unsigned MinWidth = Target->getLargeArrayMinWidth();
1460 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001461 if (isa<VariableArrayType>(arrayType))
1462 Align = std::max(Align, Target->getLargeArrayAlign());
1463 else if (isa<ConstantArrayType>(arrayType) &&
1464 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1465 Align = std::max(Align, Target->getLargeArrayAlign());
1466 }
John McCall33ddac02011-01-19 10:06:00 +00001467 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001468 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001469 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001470 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001471 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1472 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001473 }
John McCall4e819612011-01-20 07:57:12 +00001474
1475 // Fields can be subject to extra alignment constraints, like if
1476 // the field is packed, the struct is packed, or the struct has a
1477 // a max-field-alignment constraint (#pragma pack). So calculate
1478 // the actual alignment of the field within the struct, and then
1479 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001480 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1481 const RecordDecl *Parent = Field->getParent();
1482 // We can only produce a sensible answer if the record is valid.
1483 if (!Parent->isInvalidDecl()) {
1484 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001485
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001486 // Start with the record's overall alignment.
1487 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001488
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001489 // Use the GCD of that and the offset within the record.
1490 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1491 if (Offset > 0) {
1492 // Alignment is always a power of 2, so the GCD will be a power of 2,
1493 // which means we get to do this crazy thing instead of Euclid's.
1494 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1495 if (LowBitOfOffset < FieldAlign)
1496 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1497 }
1498
1499 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001500 }
Charles Davis3fc51072010-02-23 04:52:00 +00001501 }
Chris Lattner68061312009-01-24 21:53:27 +00001502 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001503
Ken Dyckcc56c542011-01-15 18:38:59 +00001504 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001505}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001506
John McCallf1249922012-08-21 04:10:00 +00001507// getTypeInfoDataSizeInChars - Return the size of a type, in
1508// chars. If the type is a record, its data size is returned. This is
1509// the size of the memcpy that's performed when assigning this type
1510// using a trivial copy/move assignment operator.
1511std::pair<CharUnits, CharUnits>
1512ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1513 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1514
1515 // In C++, objects can sometimes be allocated into the tail padding
1516 // of a base-class subobject. We decide whether that's possible
1517 // during class layout, so here we can just trust the layout results.
1518 if (getLangOpts().CPlusPlus) {
1519 if (const RecordType *RT = T->getAs<RecordType>()) {
1520 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1521 sizeAndAlign.first = layout.getDataSize();
1522 }
1523 }
1524
1525 return sizeAndAlign;
1526}
1527
Richard Trieu04d2d942013-05-14 21:59:17 +00001528/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1529/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1530std::pair<CharUnits, CharUnits>
1531static getConstantArrayInfoInChars(const ASTContext &Context,
1532 const ConstantArrayType *CAT) {
1533 std::pair<CharUnits, CharUnits> EltInfo =
1534 Context.getTypeInfoInChars(CAT->getElementType());
1535 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001536 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1537 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001538 "Overflow in array type char size evaluation");
1539 uint64_t Width = EltInfo.first.getQuantity() * Size;
1540 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001541 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1542 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001543 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001544 return std::make_pair(CharUnits::fromQuantity(Width),
1545 CharUnits::fromQuantity(Align));
1546}
1547
John McCall87fe5d52010-05-20 01:18:31 +00001548std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001549ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001550 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1551 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001552 TypeInfo Info = getTypeInfo(T);
1553 return std::make_pair(toCharUnitsFromBits(Info.Width),
1554 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001555}
1556
1557std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001558ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001559 return getTypeInfoInChars(T.getTypePtr());
1560}
1561
David Majnemer34b57492014-07-30 01:30:47 +00001562bool ASTContext::isAlignmentRequired(const Type *T) const {
1563 return getTypeInfo(T).AlignIsRequired;
1564}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001565
David Majnemer34b57492014-07-30 01:30:47 +00001566bool ASTContext::isAlignmentRequired(QualType T) const {
1567 return isAlignmentRequired(T.getTypePtr());
1568}
1569
1570TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001571 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1572 if (I != MemoizedTypeInfo.end())
1573 return I->second;
1574
1575 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1576 TypeInfo TI = getTypeInfoImpl(T);
1577 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001578 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001579}
1580
1581/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1582/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001583///
1584/// FIXME: Pointers into different addr spaces could have different sizes and
1585/// alignment requirements: getPointerInfo should take an AddrSpace, this
1586/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001587TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1588 uint64_t Width = 0;
1589 unsigned Align = 8;
1590 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001591 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001592#define TYPE(Class, Base)
1593#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001594#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001595#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001596#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1597 case Type::Class: \
1598 assert(!T->isDependentType() && "should not see dependent types here"); \
1599 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001600#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001601 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001602
Chris Lattner355332d2007-07-13 22:27:08 +00001603 case Type::FunctionNoProto:
1604 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001605 // GCC extension: alignof(function) = 32 bits
1606 Width = 0;
1607 Align = 32;
1608 break;
1609
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001610 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001611 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001612 Width = 0;
1613 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1614 break;
1615
Steve Naroff5c131802007-08-30 01:06:46 +00001616 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001617 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001618
David Majnemer34b57492014-07-30 01:30:47 +00001619 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001620 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001621 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001622 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001623 Width = EltInfo.Width * Size;
1624 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001625 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1626 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001627 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001628 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001629 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001630 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001631 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001632 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001633 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1634 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001635 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001636 // If the alignment is not a power of 2, round up to the next power of 2.
1637 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001638 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001639 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001640 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001641 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001642 // Adjust the alignment based on the target max.
1643 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1644 if (TargetVectorAlign && TargetVectorAlign < Align)
1645 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001646 break;
1647 }
Chris Lattner647fb222007-07-18 18:26:58 +00001648
Chris Lattner7570e9c2008-03-08 08:52:55 +00001649 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001650 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001651 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001652 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001653 // GCC extension: alignof(void) = 8 bits.
1654 Width = 0;
1655 Align = 8;
1656 break;
1657
Chris Lattner6a4f7452007-12-19 19:23:28 +00001658 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001659 Width = Target->getBoolWidth();
1660 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001661 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001662 case BuiltinType::Char_S:
1663 case BuiltinType::Char_U:
1664 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001665 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001666 Width = Target->getCharWidth();
1667 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001668 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001669 case BuiltinType::WChar_S:
1670 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001671 Width = Target->getWCharWidth();
1672 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001673 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001674 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001675 Width = Target->getChar16Width();
1676 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001677 break;
1678 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001679 Width = Target->getChar32Width();
1680 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001681 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001682 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001683 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001684 Width = Target->getShortWidth();
1685 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001686 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001687 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001688 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001689 Width = Target->getIntWidth();
1690 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001691 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001692 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001693 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001694 Width = Target->getLongWidth();
1695 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001696 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001697 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001698 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001699 Width = Target->getLongLongWidth();
1700 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001701 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001702 case BuiltinType::Int128:
1703 case BuiltinType::UInt128:
1704 Width = 128;
1705 Align = 128; // int128_t is 128-bit aligned on all targets.
1706 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001707 case BuiltinType::Half:
1708 Width = Target->getHalfWidth();
1709 Align = Target->getHalfAlign();
1710 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001711 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001712 Width = Target->getFloatWidth();
1713 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001714 break;
1715 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001716 Width = Target->getDoubleWidth();
1717 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001718 break;
1719 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001720 Width = Target->getLongDoubleWidth();
1721 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001722 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001723 case BuiltinType::Float128:
1724 Width = Target->getFloat128Width();
1725 Align = Target->getFloat128Align();
1726 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001727 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001728 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1729 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001730 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001731 case BuiltinType::ObjCId:
1732 case BuiltinType::ObjCClass:
1733 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001734 Width = Target->getPointerWidth(0);
1735 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001736 break;
Guy Benyei61054192013-02-07 10:55:47 +00001737 case BuiltinType::OCLSampler:
1738 // Samplers are modeled as integers.
1739 Width = Target->getIntWidth();
1740 Align = Target->getIntAlign();
1741 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001742 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001743 case BuiltinType::OCLClkEvent:
1744 case BuiltinType::OCLQueue:
1745 case BuiltinType::OCLNDRange:
1746 case BuiltinType::OCLReserveID:
Alexey Bader954ba212016-04-08 13:40:33 +00001747#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1748 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001749#include "clang/Basic/OpenCLImageTypes.def"
Alexey Bader954ba212016-04-08 13:40:33 +00001750
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001751 // Currently these types are pointers to opaque types.
1752 Width = Target->getPointerWidth(0);
1753 Align = Target->getPointerAlign(0);
1754 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001755 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001756 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001757 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001758 Width = Target->getPointerWidth(0);
1759 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001760 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001761 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001762 unsigned AS = getTargetAddressSpace(
1763 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001764 Width = Target->getPointerWidth(AS);
1765 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001766 break;
1767 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001768 case Type::LValueReference:
1769 case Type::RValueReference: {
1770 // alignof and sizeof should never enter this code path here, so we go
1771 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001772 unsigned AS = getTargetAddressSpace(
1773 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001774 Width = Target->getPointerWidth(AS);
1775 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001776 break;
1777 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001778 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001779 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001780 Width = Target->getPointerWidth(AS);
1781 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001782 break;
1783 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001784 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001785 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001786 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001787 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001788 }
Chris Lattner647fb222007-07-18 18:26:58 +00001789 case Type::Complex: {
1790 // Complex types have the same alignment as their elements, but twice the
1791 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001792 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1793 Width = EltInfo.Width * 2;
1794 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001795 break;
1796 }
John McCall8b07ec22010-05-15 11:32:37 +00001797 case Type::ObjCObject:
1798 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001799 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001800 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001801 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001802 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001803 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001804 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001805 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001806 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001807 break;
1808 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001809 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001810 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001811 const TagType *TT = cast<TagType>(T);
1812
1813 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001814 Width = 8;
1815 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001816 break;
1817 }
Mike Stump11289f42009-09-09 15:08:12 +00001818
David Majnemer475b25e2015-01-21 10:54:38 +00001819 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1820 const EnumDecl *ED = ET->getDecl();
1821 TypeInfo Info =
1822 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1823 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1824 Info.Align = AttrAlign;
1825 Info.AlignIsRequired = true;
1826 }
1827 return Info;
1828 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001829
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001830 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001831 const RecordDecl *RD = RT->getDecl();
1832 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001833 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001834 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001835 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001836 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001837 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001838
Chris Lattner63d2b362009-10-22 05:17:15 +00001839 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001840 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1841 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001842
Richard Smith30482bc2011-02-20 03:19:35 +00001843 case Type::Auto: {
1844 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001845 assert(!A->getDeducedType().isNull() &&
1846 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001847 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001848 }
1849
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001850 case Type::Paren:
1851 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1852
Douglas Gregoref462e62009-04-30 17:32:17 +00001853 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001854 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001855 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001856 // If the typedef has an aligned attribute on it, it overrides any computed
1857 // alignment we have. This violates the GCC documentation (which says that
1858 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001859 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001860 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001861 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001862 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001863 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001864 AlignIsRequired = Info.AlignIsRequired;
1865 }
David Majnemer34b57492014-07-30 01:30:47 +00001866 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001867 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001868 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001869
Abramo Bagnara6150c882010-05-11 21:36:43 +00001870 case Type::Elaborated:
1871 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001872
John McCall81904512011-01-06 01:58:22 +00001873 case Type::Attributed:
1874 return getTypeInfo(
1875 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1876
Eli Friedman0dfb8892011-10-06 23:00:33 +00001877 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001878 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001879 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1880 Width = Info.Width;
1881 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001882
1883 // If the size of the type doesn't exceed the platform's max
1884 // atomic promotion width, make the size and alignment more
1885 // favorable to atomic operations:
1886 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1887 // Round the size up to a power of 2.
1888 if (!llvm::isPowerOf2_64(Width))
1889 Width = llvm::NextPowerOf2(Width);
1890
1891 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001892 Align = static_cast<unsigned>(Width);
1893 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001894 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001895 break;
1896
1897 case Type::Pipe: {
1898 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1899 Width = Info.Width;
1900 Align = Info.Align;
1901 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001902
Douglas Gregoref462e62009-04-30 17:32:17 +00001903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001905 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001906 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001907}
1908
Alexey Bataev00396512015-07-02 03:40:19 +00001909unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1910 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1911 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1912 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1913 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1914 getTargetInfo().getABI() == "elfv1-qpx" &&
1915 T->isSpecificBuiltinType(BuiltinType::Double))
1916 SimdAlign = 256;
1917 return SimdAlign;
1918}
1919
Ken Dyckcc56c542011-01-15 18:38:59 +00001920/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1921CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1922 return CharUnits::fromQuantity(BitSize / getCharWidth());
1923}
1924
Ken Dyckb0fcc592011-02-11 01:54:29 +00001925/// toBits - Convert a size in characters to a size in characters.
1926int64_t ASTContext::toBits(CharUnits CharSize) const {
1927 return CharSize.getQuantity() * getCharWidth();
1928}
1929
Ken Dyck8c89d592009-12-22 14:23:30 +00001930/// getTypeSizeInChars - Return the size of the specified type, in characters.
1931/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001932CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001933 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001934}
Jay Foad39c79802011-01-12 09:06:06 +00001935CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001936 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001937}
1938
Ken Dycka6046ab2010-01-26 17:25:18 +00001939/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001940/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001941CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001942 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001943}
Jay Foad39c79802011-01-12 09:06:06 +00001944CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001945 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001946}
1947
Chris Lattnera3402cd2009-01-27 18:08:34 +00001948/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1949/// type for the current target in bits. This can be different than the ABI
1950/// alignment in cases where it is beneficial for performance to overalign
1951/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001952unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001953 TypeInfo TI = getTypeInfo(T);
1954 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001955
David Majnemere1544562015-04-24 01:25:05 +00001956 T = T->getBaseElementTypeUnsafe();
1957
1958 // The preferred alignment of member pointers is that of a pointer.
1959 if (T->isMemberPointerType())
1960 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1961
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001962 if (!Target->allowsLargerPreferedTypeAlignment())
1963 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001964
Eli Friedman7ab09572009-05-25 21:27:19 +00001965 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001966 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001967 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001968 if (const EnumType *ET = T->getAs<EnumType>())
1969 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001970 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001971 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1972 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001973 // Don't increase the alignment if an alignment attribute was specified on a
1974 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001975 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001976 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001977
Chris Lattnera3402cd2009-01-27 18:08:34 +00001978 return ABIAlign;
1979}
1980
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001981/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1982/// for __attribute__((aligned)) on this target, to be used if no alignment
1983/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001984unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001985 return getTargetInfo().getDefaultAlignForAttributeAligned();
1986}
1987
Ulrich Weigandfa806422013-05-06 16:23:57 +00001988/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1989/// to a global variable of the specified type.
1990unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1991 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1992}
1993
1994/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1995/// should be given to a global variable of the specified type.
1996CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1997 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1998}
1999
David Majnemer08ef2ba2015-06-23 20:34:18 +00002000CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2001 CharUnits Offset = CharUnits::Zero();
2002 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2003 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2004 Offset += Layout->getBaseClassOffset(Base);
2005 Layout = &getASTRecordLayout(Base);
2006 }
2007 return Offset;
2008}
2009
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002010/// DeepCollectObjCIvars -
2011/// This routine first collects all declared, but not synthesized, ivars in
2012/// super class and then collects all ivars, including those synthesized for
2013/// current class. This routine is used for implementation of current class
2014/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002015///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002016void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2017 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002018 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002019 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2020 DeepCollectObjCIvars(SuperClass, false, Ivars);
2021 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002022 for (const auto *I : OI->ivars())
2023 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002024 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002025 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002026 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002027 Iv= Iv->getNextIvar())
2028 Ivars.push_back(Iv);
2029 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002030}
2031
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002032/// CollectInheritedProtocols - Collect all protocols in current class and
2033/// those inherited by it.
2034void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002035 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002036 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002037 // We can use protocol_iterator here instead of
2038 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002039 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002040 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002041 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002042
2043 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002044 for (const auto *Cat : OI->visible_categories())
2045 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002046
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002047 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2048 while (SD) {
2049 CollectInheritedProtocols(SD, Protocols);
2050 SD = SD->getSuperClass();
2051 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002052 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002053 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002054 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002055 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002056 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002057 // Insert the protocol.
2058 if (!Protocols.insert(
2059 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2060 return;
2061
2062 for (auto *Proto : OP->protocols())
2063 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002064 }
2065}
2066
Jay Foad39c79802011-01-12 09:06:06 +00002067unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002068 unsigned count = 0;
2069 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002070 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002071 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002072
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002073 // Count ivar defined in this class's implementation. This
2074 // includes synthesized ivars.
2075 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002076 count += ImplDecl->ivar_size();
2077
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002078 return count;
2079}
2080
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002081bool ASTContext::isSentinelNullExpr(const Expr *E) {
2082 if (!E)
2083 return false;
2084
2085 // nullptr_t is always treated as null.
2086 if (E->getType()->isNullPtrType()) return true;
2087
2088 if (E->getType()->isAnyPointerType() &&
2089 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2090 Expr::NPC_ValueDependentIsNull))
2091 return true;
2092
2093 // Unfortunately, __null has type 'int'.
2094 if (isa<GNUNullExpr>(E)) return true;
2095
2096 return false;
2097}
2098
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002099/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2100ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2101 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2102 I = ObjCImpls.find(D);
2103 if (I != ObjCImpls.end())
2104 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002105 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002106}
2107/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2108ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2109 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2110 I = ObjCImpls.find(D);
2111 if (I != ObjCImpls.end())
2112 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002113 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002114}
2115
2116/// \brief Set the implementation of ObjCInterfaceDecl.
2117void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2118 ObjCImplementationDecl *ImplD) {
2119 assert(IFaceD && ImplD && "Passed null params");
2120 ObjCImpls[IFaceD] = ImplD;
2121}
2122/// \brief Set the implementation of ObjCCategoryDecl.
2123void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2124 ObjCCategoryImplDecl *ImplD) {
2125 assert(CatD && ImplD && "Passed null params");
2126 ObjCImpls[CatD] = ImplD;
2127}
2128
Chandler Carruth21c90602015-12-30 03:24:14 +00002129const ObjCMethodDecl *
2130ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2131 return ObjCMethodRedecls.lookup(MD);
2132}
2133
2134void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2135 const ObjCMethodDecl *Redecl) {
2136 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2137 ObjCMethodRedecls[MD] = Redecl;
2138}
2139
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002140const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2141 const NamedDecl *ND) const {
2142 if (const ObjCInterfaceDecl *ID =
2143 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002144 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002145 if (const ObjCCategoryDecl *CD =
2146 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002147 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002148 if (const ObjCImplDecl *IMD =
2149 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002150 return IMD->getClassInterface();
2151
Craig Topper36250ad2014-05-12 05:36:57 +00002152 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002153}
2154
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002155/// \brief Get the copy initialization expression of VarDecl,or NULL if
2156/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002157Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002158 assert(VD && "Passed null params");
2159 assert(VD->hasAttr<BlocksAttr>() &&
2160 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002161 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002162 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002163 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002164}
2165
2166/// \brief Set the copy inialization expression of a block var decl.
2167void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2168 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002169 assert(VD->hasAttr<BlocksAttr>() &&
2170 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002171 BlockVarCopyInits[VD] = Init;
2172}
2173
John McCallbcd03502009-12-07 02:54:59 +00002174TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002175 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002176 if (!DataSize)
2177 DataSize = TypeLoc::getFullDataSizeForType(T);
2178 else
2179 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002180 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002181
John McCallbcd03502009-12-07 02:54:59 +00002182 TypeSourceInfo *TInfo =
2183 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2184 new (TInfo) TypeSourceInfo(T);
2185 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002186}
2187
John McCallbcd03502009-12-07 02:54:59 +00002188TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002189 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002190 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002191 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002192 return DI;
2193}
2194
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002195const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002196ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002197 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002198}
2199
2200const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002201ASTContext::getASTObjCImplementationLayout(
2202 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002203 return getObjCLayout(D->getClassInterface(), D);
2204}
2205
Chris Lattner983a8bb2007-07-13 22:13:22 +00002206//===----------------------------------------------------------------------===//
2207// Type creation/memoization methods
2208//===----------------------------------------------------------------------===//
2209
Jay Foad39c79802011-01-12 09:06:06 +00002210QualType
John McCall33ddac02011-01-19 10:06:00 +00002211ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2212 unsigned fastQuals = quals.getFastQualifiers();
2213 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002214
2215 // Check if we've already instantiated this type.
2216 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002217 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002218 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002219 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2220 assert(eq->getQualifiers() == quals);
2221 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002222 }
2223
John McCall33ddac02011-01-19 10:06:00 +00002224 // If the base type is not canonical, make the appropriate canonical type.
2225 QualType canon;
2226 if (!baseType->isCanonicalUnqualified()) {
2227 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002228 canonSplit.Quals.addConsistentQualifiers(quals);
2229 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002230
2231 // Re-find the insert position.
2232 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2233 }
2234
2235 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2236 ExtQualNodes.InsertNode(eq, insertPos);
2237 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002238}
2239
Jay Foad39c79802011-01-12 09:06:06 +00002240QualType
2241ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002242 QualType CanT = getCanonicalType(T);
2243 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002244 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002245
John McCall8ccfcb52009-09-24 19:53:00 +00002246 // If we are composing extended qualifiers together, merge together
2247 // into one ExtQuals node.
2248 QualifierCollector Quals;
2249 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002250
John McCall8ccfcb52009-09-24 19:53:00 +00002251 // If this type already has an address space specified, it cannot get
2252 // another one.
2253 assert(!Quals.hasAddressSpace() &&
2254 "Type cannot be in multiple addr spaces!");
2255 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002256
John McCall8ccfcb52009-09-24 19:53:00 +00002257 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002258}
2259
Chris Lattnerd60183d2009-02-18 22:53:11 +00002260QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002261 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002262 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002263 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002264 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002265
John McCall53fa7142010-12-24 02:08:15 +00002266 if (const PointerType *ptr = T->getAs<PointerType>()) {
2267 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002268 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002269 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2270 return getPointerType(ResultType);
2271 }
2272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273
John McCall8ccfcb52009-09-24 19:53:00 +00002274 // If we are composing extended qualifiers together, merge together
2275 // into one ExtQuals node.
2276 QualifierCollector Quals;
2277 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002278
John McCall8ccfcb52009-09-24 19:53:00 +00002279 // If this type already has an ObjCGC specified, it cannot get
2280 // another one.
2281 assert(!Quals.hasObjCGCAttr() &&
2282 "Type cannot have multiple ObjCGCs!");
2283 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002284
John McCall8ccfcb52009-09-24 19:53:00 +00002285 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002286}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002287
John McCall4f5019e2010-12-19 02:44:49 +00002288const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2289 FunctionType::ExtInfo Info) {
2290 if (T->getExtInfo() == Info)
2291 return T;
2292
2293 QualType Result;
2294 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002295 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002296 } else {
2297 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2298 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2299 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002300 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002301 }
2302
2303 return cast<FunctionType>(Result.getTypePtr());
2304}
2305
Richard Smith2a7d4812013-05-04 07:00:32 +00002306void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2307 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002308 FD = FD->getMostRecentDecl();
2309 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002310 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2311 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002312 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002313 if (FunctionDecl *Next = FD->getPreviousDecl())
2314 FD = Next;
2315 else
2316 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002317 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002318 if (ASTMutationListener *L = getASTMutationListener())
2319 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002320}
2321
Richard Smith0b3a4622014-11-13 20:01:57 +00002322/// Get a function type and produce the equivalent function type with the
2323/// specified exception specification. Type sugar that can be present on a
2324/// declaration of a function with an exception specification is permitted
2325/// and preserved. Other type sugar (for instance, typedefs) is not.
2326static QualType getFunctionTypeWithExceptionSpec(
2327 ASTContext &Context, QualType Orig,
2328 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2329 // Might have some parens.
2330 if (auto *PT = dyn_cast<ParenType>(Orig))
2331 return Context.getParenType(
2332 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2333
2334 // Might have a calling-convention attribute.
2335 if (auto *AT = dyn_cast<AttributedType>(Orig))
2336 return Context.getAttributedType(
2337 AT->getAttrKind(),
2338 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2339 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2340 ESI));
2341
2342 // Anything else must be a function type. Rebuild it with the new exception
2343 // specification.
2344 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2345 return Context.getFunctionType(
2346 Proto->getReturnType(), Proto->getParamTypes(),
2347 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2348}
2349
2350void ASTContext::adjustExceptionSpec(
2351 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2352 bool AsWritten) {
2353 // Update the type.
2354 QualType Updated =
2355 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2356 FD->setType(Updated);
2357
2358 if (!AsWritten)
2359 return;
2360
2361 // Update the type in the type source information too.
2362 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2363 // If the type and the type-as-written differ, we may need to update
2364 // the type-as-written too.
2365 if (TSInfo->getType() != FD->getType())
2366 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2367
2368 // FIXME: When we get proper type location information for exceptions,
2369 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2370 // up the TypeSourceInfo;
2371 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2372 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2373 "TypeLoc size mismatch from updating exception specification");
2374 TSInfo->overrideType(Updated);
2375 }
2376}
2377
Chris Lattnerc6395932007-06-22 20:56:16 +00002378/// getComplexType - Return the uniqued reference to the type for a complex
2379/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002380QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002381 // Unique pointers, to guarantee there is only one pointer of a particular
2382 // structure.
2383 llvm::FoldingSetNodeID ID;
2384 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002385
Craig Topper36250ad2014-05-12 05:36:57 +00002386 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002387 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2388 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002389
Chris Lattnerc6395932007-06-22 20:56:16 +00002390 // If the pointee type isn't canonical, this won't be a canonical type either,
2391 // so fill in the canonical type field.
2392 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002393 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002394 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002395
Chris Lattnerc6395932007-06-22 20:56:16 +00002396 // Get the new insert position for the node we care about.
2397 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002398 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002399 }
John McCall90d1c2d2009-09-24 23:30:46 +00002400 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002401 Types.push_back(New);
2402 ComplexTypes.InsertNode(New, InsertPos);
2403 return QualType(New, 0);
2404}
2405
Chris Lattner970e54e2006-11-12 00:37:36 +00002406/// getPointerType - Return the uniqued reference to the type for a pointer to
2407/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002408QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002409 // Unique pointers, to guarantee there is only one pointer of a particular
2410 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002411 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002412 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002413
Craig Topper36250ad2014-05-12 05:36:57 +00002414 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002415 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002416 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002417
Chris Lattner7ccecb92006-11-12 08:50:50 +00002418 // If the pointee type isn't canonical, this won't be a canonical type either,
2419 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002420 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002421 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002422 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002423
Bob Wilsonc8541f22013-03-15 17:12:43 +00002424 // Get the new insert position for the node we care about.
2425 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002426 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002427 }
John McCall90d1c2d2009-09-24 23:30:46 +00002428 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002429 Types.push_back(New);
2430 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002431 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002432}
2433
Reid Kleckner0503a872013-12-05 01:23:43 +00002434QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2435 llvm::FoldingSetNodeID ID;
2436 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002437 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002438 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2439 if (AT)
2440 return QualType(AT, 0);
2441
2442 QualType Canonical = getCanonicalType(New);
2443
2444 // Get the new insert position for the node we care about.
2445 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002446 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002447
2448 AT = new (*this, TypeAlignment)
2449 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2450 Types.push_back(AT);
2451 AdjustedTypes.InsertNode(AT, InsertPos);
2452 return QualType(AT, 0);
2453}
2454
Reid Kleckner8a365022013-06-24 17:51:48 +00002455QualType ASTContext::getDecayedType(QualType T) const {
2456 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2457
Reid Kleckner8a365022013-06-24 17:51:48 +00002458 QualType Decayed;
2459
2460 // C99 6.7.5.3p7:
2461 // A declaration of a parameter as "array of type" shall be
2462 // adjusted to "qualified pointer to type", where the type
2463 // qualifiers (if any) are those specified within the [ and ] of
2464 // the array type derivation.
2465 if (T->isArrayType())
2466 Decayed = getArrayDecayedType(T);
2467
2468 // C99 6.7.5.3p8:
2469 // A declaration of a parameter as "function returning type"
2470 // shall be adjusted to "pointer to function returning type", as
2471 // in 6.3.2.1.
2472 if (T->isFunctionType())
2473 Decayed = getPointerType(T);
2474
Reid Kleckner0503a872013-12-05 01:23:43 +00002475 llvm::FoldingSetNodeID ID;
2476 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002477 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002478 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2479 if (AT)
2480 return QualType(AT, 0);
2481
Reid Kleckner8a365022013-06-24 17:51:48 +00002482 QualType Canonical = getCanonicalType(Decayed);
2483
2484 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002485 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002486 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002487
Reid Kleckner0503a872013-12-05 01:23:43 +00002488 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2489 Types.push_back(AT);
2490 AdjustedTypes.InsertNode(AT, InsertPos);
2491 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002492}
2493
Mike Stump11289f42009-09-09 15:08:12 +00002494/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002495/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002496QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002497 assert(T->isFunctionType() && "block of function types only");
2498 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002499 // structure.
2500 llvm::FoldingSetNodeID ID;
2501 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002502
Craig Topper36250ad2014-05-12 05:36:57 +00002503 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002504 if (BlockPointerType *PT =
2505 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2506 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002507
2508 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002509 // type either so fill in the canonical type field.
2510 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002511 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002512 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002513
Steve Naroffec33ed92008-08-27 16:04:49 +00002514 // Get the new insert position for the node we care about.
2515 BlockPointerType *NewIP =
2516 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002517 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002518 }
John McCall90d1c2d2009-09-24 23:30:46 +00002519 BlockPointerType *New
2520 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002521 Types.push_back(New);
2522 BlockPointerTypes.InsertNode(New, InsertPos);
2523 return QualType(New, 0);
2524}
2525
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002526/// getLValueReferenceType - Return the uniqued reference to the type for an
2527/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002528QualType
2529ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002530 assert(getCanonicalType(T) != OverloadTy &&
2531 "Unresolved overloaded function type");
2532
Bill Wendling3708c182007-05-27 10:15:43 +00002533 // Unique pointers, to guarantee there is only one pointer of a particular
2534 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002535 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002536 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002537
Craig Topper36250ad2014-05-12 05:36:57 +00002538 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002539 if (LValueReferenceType *RT =
2540 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002541 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002542
John McCallfc93cf92009-10-22 22:37:11 +00002543 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2544
Bill Wendling3708c182007-05-27 10:15:43 +00002545 // If the referencee type isn't canonical, this won't be a canonical type
2546 // either, so fill in the canonical type field.
2547 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002548 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2549 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2550 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002551
Bill Wendling3708c182007-05-27 10:15:43 +00002552 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002553 LValueReferenceType *NewIP =
2554 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002555 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002556 }
2557
John McCall90d1c2d2009-09-24 23:30:46 +00002558 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002559 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2560 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002561 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002562 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002563
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002564 return QualType(New, 0);
2565}
2566
2567/// getRValueReferenceType - Return the uniqued reference to the type for an
2568/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002569QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002570 // Unique pointers, to guarantee there is only one pointer of a particular
2571 // structure.
2572 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002573 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002574
Craig Topper36250ad2014-05-12 05:36:57 +00002575 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002576 if (RValueReferenceType *RT =
2577 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2578 return QualType(RT, 0);
2579
John McCallfc93cf92009-10-22 22:37:11 +00002580 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2581
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002582 // If the referencee type isn't canonical, this won't be a canonical type
2583 // either, so fill in the canonical type field.
2584 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002585 if (InnerRef || !T.isCanonical()) {
2586 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2587 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002588
2589 // Get the new insert position for the node we care about.
2590 RValueReferenceType *NewIP =
2591 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002592 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002593 }
2594
John McCall90d1c2d2009-09-24 23:30:46 +00002595 RValueReferenceType *New
2596 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002597 Types.push_back(New);
2598 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002599 return QualType(New, 0);
2600}
2601
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002602/// getMemberPointerType - Return the uniqued reference to the type for a
2603/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002604QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002605 // Unique pointers, to guarantee there is only one pointer of a particular
2606 // structure.
2607 llvm::FoldingSetNodeID ID;
2608 MemberPointerType::Profile(ID, T, Cls);
2609
Craig Topper36250ad2014-05-12 05:36:57 +00002610 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002611 if (MemberPointerType *PT =
2612 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2613 return QualType(PT, 0);
2614
2615 // If the pointee or class type isn't canonical, this won't be a canonical
2616 // type either, so fill in the canonical type field.
2617 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002618 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002619 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2620
2621 // Get the new insert position for the node we care about.
2622 MemberPointerType *NewIP =
2623 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002624 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002625 }
John McCall90d1c2d2009-09-24 23:30:46 +00002626 MemberPointerType *New
2627 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002628 Types.push_back(New);
2629 MemberPointerTypes.InsertNode(New, InsertPos);
2630 return QualType(New, 0);
2631}
2632
Mike Stump11289f42009-09-09 15:08:12 +00002633/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002634/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002635QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002636 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002637 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002638 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002639 assert((EltTy->isDependentType() ||
2640 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002641 "Constant array of VLAs is illegal!");
2642
Chris Lattnere2df3f92009-05-13 04:12:56 +00002643 // Convert the array size into a canonical width matching the pointer size for
2644 // the target.
2645 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002646 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002647 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002648
Chris Lattner23b7eb62007-06-15 23:05:46 +00002649 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002650 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002651
Craig Topper36250ad2014-05-12 05:36:57 +00002652 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002653 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002654 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002655 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002656
John McCall33ddac02011-01-19 10:06:00 +00002657 // If the element type isn't canonical or has qualifiers, this won't
2658 // be a canonical type either, so fill in the canonical type field.
2659 QualType Canon;
2660 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2661 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002662 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002663 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002664 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002665
Chris Lattner36f8e652007-01-27 08:31:04 +00002666 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002667 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002668 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002669 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002670 }
Mike Stump11289f42009-09-09 15:08:12 +00002671
John McCall90d1c2d2009-09-24 23:30:46 +00002672 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002673 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002674 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002675 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002676 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002677}
2678
John McCall06549462011-01-18 08:40:38 +00002679/// getVariableArrayDecayedType - Turns the given type, which may be
2680/// variably-modified, into the corresponding type with all the known
2681/// sizes replaced with [*].
2682QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2683 // Vastly most common case.
2684 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002685
John McCall06549462011-01-18 08:40:38 +00002686 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002687
John McCall06549462011-01-18 08:40:38 +00002688 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002689 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002690 switch (ty->getTypeClass()) {
2691#define TYPE(Class, Base)
2692#define ABSTRACT_TYPE(Class, Base)
2693#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2694#include "clang/AST/TypeNodes.def"
2695 llvm_unreachable("didn't desugar past all non-canonical types?");
2696
2697 // These types should never be variably-modified.
2698 case Type::Builtin:
2699 case Type::Complex:
2700 case Type::Vector:
2701 case Type::ExtVector:
2702 case Type::DependentSizedExtVector:
2703 case Type::ObjCObject:
2704 case Type::ObjCInterface:
2705 case Type::ObjCObjectPointer:
2706 case Type::Record:
2707 case Type::Enum:
2708 case Type::UnresolvedUsing:
2709 case Type::TypeOfExpr:
2710 case Type::TypeOf:
2711 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002712 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002713 case Type::DependentName:
2714 case Type::InjectedClassName:
2715 case Type::TemplateSpecialization:
2716 case Type::DependentTemplateSpecialization:
2717 case Type::TemplateTypeParm:
2718 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002719 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002720 case Type::PackExpansion:
2721 llvm_unreachable("type should never be variably-modified");
2722
2723 // These types can be variably-modified but should never need to
2724 // further decay.
2725 case Type::FunctionNoProto:
2726 case Type::FunctionProto:
2727 case Type::BlockPointer:
2728 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002729 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002730 return type;
2731
2732 // These types can be variably-modified. All these modifications
2733 // preserve structure except as noted by comments.
2734 // TODO: if we ever care about optimizing VLAs, there are no-op
2735 // optimizations available here.
2736 case Type::Pointer:
2737 result = getPointerType(getVariableArrayDecayedType(
2738 cast<PointerType>(ty)->getPointeeType()));
2739 break;
2740
2741 case Type::LValueReference: {
2742 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2743 result = getLValueReferenceType(
2744 getVariableArrayDecayedType(lv->getPointeeType()),
2745 lv->isSpelledAsLValue());
2746 break;
2747 }
2748
2749 case Type::RValueReference: {
2750 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2751 result = getRValueReferenceType(
2752 getVariableArrayDecayedType(lv->getPointeeType()));
2753 break;
2754 }
2755
Eli Friedman0dfb8892011-10-06 23:00:33 +00002756 case Type::Atomic: {
2757 const AtomicType *at = cast<AtomicType>(ty);
2758 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2759 break;
2760 }
2761
John McCall06549462011-01-18 08:40:38 +00002762 case Type::ConstantArray: {
2763 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2764 result = getConstantArrayType(
2765 getVariableArrayDecayedType(cat->getElementType()),
2766 cat->getSize(),
2767 cat->getSizeModifier(),
2768 cat->getIndexTypeCVRQualifiers());
2769 break;
2770 }
2771
2772 case Type::DependentSizedArray: {
2773 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2774 result = getDependentSizedArrayType(
2775 getVariableArrayDecayedType(dat->getElementType()),
2776 dat->getSizeExpr(),
2777 dat->getSizeModifier(),
2778 dat->getIndexTypeCVRQualifiers(),
2779 dat->getBracketsRange());
2780 break;
2781 }
2782
2783 // Turn incomplete types into [*] types.
2784 case Type::IncompleteArray: {
2785 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2786 result = getVariableArrayType(
2787 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002788 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002789 ArrayType::Normal,
2790 iat->getIndexTypeCVRQualifiers(),
2791 SourceRange());
2792 break;
2793 }
2794
2795 // Turn VLA types into [*] types.
2796 case Type::VariableArray: {
2797 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2798 result = getVariableArrayType(
2799 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002800 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002801 ArrayType::Star,
2802 vat->getIndexTypeCVRQualifiers(),
2803 vat->getBracketsRange());
2804 break;
2805 }
2806 }
2807
2808 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002809 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002810}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002811
Steve Naroffcadebd02007-08-30 18:14:25 +00002812/// getVariableArrayType - Returns a non-unique reference to the type for a
2813/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002814QualType ASTContext::getVariableArrayType(QualType EltTy,
2815 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002816 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002817 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002818 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002819 // Since we don't unique expressions, it isn't possible to unique VLA's
2820 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002821 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002822
John McCall33ddac02011-01-19 10:06:00 +00002823 // Be sure to pull qualifiers off the element type.
2824 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2825 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002826 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002827 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002828 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002829 }
2830
John McCall90d1c2d2009-09-24 23:30:46 +00002831 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002832 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002833
2834 VariableArrayTypes.push_back(New);
2835 Types.push_back(New);
2836 return QualType(New, 0);
2837}
2838
Douglas Gregor4619e432008-12-05 23:32:09 +00002839/// getDependentSizedArrayType - Returns a non-unique reference to
2840/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002841/// type.
John McCall33ddac02011-01-19 10:06:00 +00002842QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2843 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002844 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002845 unsigned elementTypeQuals,
2846 SourceRange brackets) const {
2847 assert((!numElements || numElements->isTypeDependent() ||
2848 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002849 "Size must be type- or value-dependent!");
2850
John McCall33ddac02011-01-19 10:06:00 +00002851 // Dependently-sized array types that do not have a specified number
2852 // of elements will have their sizes deduced from a dependent
2853 // initializer. We do no canonicalization here at all, which is okay
2854 // because they can't be used in most locations.
2855 if (!numElements) {
2856 DependentSizedArrayType *newType
2857 = new (*this, TypeAlignment)
2858 DependentSizedArrayType(*this, elementType, QualType(),
2859 numElements, ASM, elementTypeQuals,
2860 brackets);
2861 Types.push_back(newType);
2862 return QualType(newType, 0);
2863 }
2864
2865 // Otherwise, we actually build a new type every time, but we
2866 // also build a canonical type.
2867
2868 SplitQualType canonElementType = getCanonicalType(elementType).split();
2869
Craig Topper36250ad2014-05-12 05:36:57 +00002870 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002871 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002872 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002873 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002874 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002875
John McCall33ddac02011-01-19 10:06:00 +00002876 // Look for an existing type with these properties.
2877 DependentSizedArrayType *canonTy =
2878 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002879
John McCall33ddac02011-01-19 10:06:00 +00002880 // If we don't have one, build one.
2881 if (!canonTy) {
2882 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002883 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002884 QualType(), numElements, ASM, elementTypeQuals,
2885 brackets);
2886 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2887 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002888 }
2889
John McCall33ddac02011-01-19 10:06:00 +00002890 // Apply qualifiers from the element type to the array.
2891 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002892 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002893
David Majnemer16a74702015-07-24 05:54:19 +00002894 // If we didn't need extra canonicalization for the element type or the size
2895 // expression, then just use that as our result.
2896 if (QualType(canonElementType.Ty, 0) == elementType &&
2897 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002898 return canon;
2899
2900 // Otherwise, we need to build a type which follows the spelling
2901 // of the element type.
2902 DependentSizedArrayType *sugaredType
2903 = new (*this, TypeAlignment)
2904 DependentSizedArrayType(*this, elementType, canon, numElements,
2905 ASM, elementTypeQuals, brackets);
2906 Types.push_back(sugaredType);
2907 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002908}
2909
John McCall33ddac02011-01-19 10:06:00 +00002910QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002911 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002912 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002913 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002914 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002915
Craig Topper36250ad2014-05-12 05:36:57 +00002916 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002917 if (IncompleteArrayType *iat =
2918 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2919 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002920
2921 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002922 // either, so fill in the canonical type field. We also have to pull
2923 // qualifiers off the element type.
2924 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002925
John McCall33ddac02011-01-19 10:06:00 +00002926 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2927 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002928 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002929 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002930 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002931
2932 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002933 IncompleteArrayType *existing =
2934 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2935 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002936 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002937
John McCall33ddac02011-01-19 10:06:00 +00002938 IncompleteArrayType *newType = new (*this, TypeAlignment)
2939 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002940
John McCall33ddac02011-01-19 10:06:00 +00002941 IncompleteArrayTypes.InsertNode(newType, insertPos);
2942 Types.push_back(newType);
2943 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002944}
2945
Steve Naroff91fcddb2007-07-18 18:00:27 +00002946/// getVectorType - Return the unique reference to a vector type of
2947/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002948QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002949 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002950 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002951
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002952 // Check if we've already instantiated a vector of this type.
2953 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002954 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002955
Craig Topper36250ad2014-05-12 05:36:57 +00002956 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002957 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2958 return QualType(VTP, 0);
2959
2960 // If the element type isn't canonical, this won't be a canonical type either,
2961 // so fill in the canonical type field.
2962 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002963 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002964 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002965
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002966 // Get the new insert position for the node we care about.
2967 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002968 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002969 }
John McCall90d1c2d2009-09-24 23:30:46 +00002970 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002971 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002972 VectorTypes.InsertNode(New, InsertPos);
2973 Types.push_back(New);
2974 return QualType(New, 0);
2975}
2976
Nate Begemance4d7fc2008-04-18 23:10:10 +00002977/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002978/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002979QualType
2980ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002981 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002982
Steve Naroff91fcddb2007-07-18 18:00:27 +00002983 // Check if we've already instantiated a vector of this type.
2984 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002985 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002986 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002987 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002988 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2989 return QualType(VTP, 0);
2990
2991 // If the element type isn't canonical, this won't be a canonical type either,
2992 // so fill in the canonical type field.
2993 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002994 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002995 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002996
Steve Naroff91fcddb2007-07-18 18:00:27 +00002997 // Get the new insert position for the node we care about.
2998 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002999 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003000 }
John McCall90d1c2d2009-09-24 23:30:46 +00003001 ExtVectorType *New = new (*this, TypeAlignment)
3002 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003003 VectorTypes.InsertNode(New, InsertPos);
3004 Types.push_back(New);
3005 return QualType(New, 0);
3006}
3007
Jay Foad39c79802011-01-12 09:06:06 +00003008QualType
3009ASTContext::getDependentSizedExtVectorType(QualType vecType,
3010 Expr *SizeExpr,
3011 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003012 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003013 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003014 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003015
Craig Topper36250ad2014-05-12 05:36:57 +00003016 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003017 DependentSizedExtVectorType *Canon
3018 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3019 DependentSizedExtVectorType *New;
3020 if (Canon) {
3021 // We already have a canonical version of this array type; use it as
3022 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003023 New = new (*this, TypeAlignment)
3024 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3025 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003026 } else {
3027 QualType CanonVecTy = getCanonicalType(vecType);
3028 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003029 New = new (*this, TypeAlignment)
3030 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3031 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003032
3033 DependentSizedExtVectorType *CanonCheck
3034 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3035 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3036 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003037 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3038 } else {
3039 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3040 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003041 New = new (*this, TypeAlignment)
3042 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003043 }
3044 }
Mike Stump11289f42009-09-09 15:08:12 +00003045
Douglas Gregor758a8692009-06-17 21:51:59 +00003046 Types.push_back(New);
3047 return QualType(New, 0);
3048}
3049
John McCall18afab72016-03-01 00:49:02 +00003050/// \brief Determine whether \p T is canonical as the result type of a function.
3051static bool isCanonicalResultType(QualType T) {
3052 return T.isCanonical() &&
3053 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3054 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3055}
3056
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003057/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003058///
Jay Foad39c79802011-01-12 09:06:06 +00003059QualType
3060ASTContext::getFunctionNoProtoType(QualType ResultTy,
3061 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003062 // Unique functions, to guarantee there is only one function of a particular
3063 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003064 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003065 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003066
Craig Topper36250ad2014-05-12 05:36:57 +00003067 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003068 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003069 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003070 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003071
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003072 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003073 if (!isCanonicalResultType(ResultTy)) {
3074 Canonical =
3075 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003076
Chris Lattner47955de2007-01-27 08:37:20 +00003077 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003078 FunctionNoProtoType *NewIP =
3079 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003080 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003081 }
Mike Stump11289f42009-09-09 15:08:12 +00003082
John McCall90d1c2d2009-09-24 23:30:46 +00003083 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003084 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003085 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003086 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003087 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003088}
3089
Douglas Gregora602a152015-10-01 20:20:47 +00003090CanQualType
3091ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3092 CanQualType CanResultType = getCanonicalType(ResultType);
3093
3094 // Canonical result types do not have ARC lifetime qualifiers.
3095 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3096 Qualifiers Qs = CanResultType.getQualifiers();
3097 Qs.removeObjCLifetime();
3098 return CanQualType::CreateUnsafe(
3099 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3100 }
3101
3102 return CanResultType;
3103}
3104
Jay Foad39c79802011-01-12 09:06:06 +00003105QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003106ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003107 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003108 size_t NumArgs = ArgArray.size();
3109
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003110 // Unique functions, to guarantee there is only one function of a particular
3111 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003112 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003113 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3114 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003115
Craig Topper36250ad2014-05-12 05:36:57 +00003116 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003117 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003118 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003119 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003120
3121 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003122 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003123 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003124 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003125 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003126 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003127 isCanonical = false;
3128
3129 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003130 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003131 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003132 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003133 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003134 CanonicalArgs.reserve(NumArgs);
3135 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003136 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003137
John McCalldb40c7f2010-12-14 08:05:40 +00003138 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003139 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003140 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003141
Douglas Gregora602a152015-10-01 20:20:47 +00003142 // Adjust the canonical function result type.
3143 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003144 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003145
Chris Lattnerfd4de792007-01-27 01:15:32 +00003146 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003147 FunctionProtoType *NewIP =
3148 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003149 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003150 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003151
John McCall31168b02011-06-15 23:02:42 +00003152 // FunctionProtoType objects are allocated with extra bytes after
3153 // them for three variable size arrays at the end:
3154 // - parameter types
3155 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003156 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003157 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003158 // expression, or information used to resolve the exception
3159 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003160 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003161 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003162
Richard Smith8acb4282014-07-31 21:57:55 +00003163 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3164 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3165 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003166 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003167 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003168 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003169 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003170 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003171 }
John McCall18afab72016-03-01 00:49:02 +00003172
3173 // Put the ExtParameterInfos last. If all were equal, it would make
3174 // more sense to put these before the exception specification, because
3175 // it's much easier to skip past them compared to the elaborate switch
3176 // required to skip the exception specification. However, all is not
3177 // equal; ExtParameterInfos are used to model very uncommon features,
3178 // and it's better not to burden the more common paths.
3179 if (EPI.ExtParameterInfos) {
3180 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3181 }
John McCall31168b02011-06-15 23:02:42 +00003182
John McCalldb40c7f2010-12-14 08:05:40 +00003183 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003184 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003185 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003186 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003187 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003188 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003189}
Chris Lattneref51c202006-11-10 07:17:23 +00003190
Xiuli Pan9c14e282016-01-09 12:53:17 +00003191/// Return pipe type for the specified type.
3192QualType ASTContext::getPipeType(QualType T) const {
3193 llvm::FoldingSetNodeID ID;
3194 PipeType::Profile(ID, T);
3195
3196 void *InsertPos = 0;
3197 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3198 return QualType(PT, 0);
3199
3200 // If the pipe element type isn't canonical, this won't be a canonical type
3201 // either, so fill in the canonical type field.
3202 QualType Canonical;
3203 if (!T.isCanonical()) {
3204 Canonical = getPipeType(getCanonicalType(T));
3205
3206 // Get the new insert position for the node we care about.
3207 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3208 assert(!NewIP && "Shouldn't be in the map!");
3209 (void)NewIP;
3210 }
3211 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3212 Types.push_back(New);
3213 PipeTypes.InsertNode(New, InsertPos);
3214 return QualType(New, 0);
3215}
3216
John McCalle78aac42010-03-10 03:28:59 +00003217#ifndef NDEBUG
3218static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3219 if (!isa<CXXRecordDecl>(D)) return false;
3220 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3221 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3222 return true;
3223 if (RD->getDescribedClassTemplate() &&
3224 !isa<ClassTemplateSpecializationDecl>(RD))
3225 return true;
3226 return false;
3227}
3228#endif
3229
3230/// getInjectedClassNameType - Return the unique reference to the
3231/// injected class name type for the specified templated declaration.
3232QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003233 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003234 assert(NeedsInjectedClassNameType(Decl));
3235 if (Decl->TypeForDecl) {
3236 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003237 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003238 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3239 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3240 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3241 } else {
John McCall424cec92011-01-19 06:33:43 +00003242 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003243 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003244 Decl->TypeForDecl = newType;
3245 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003246 }
3247 return QualType(Decl->TypeForDecl, 0);
3248}
3249
Douglas Gregor83a586e2008-04-13 21:07:44 +00003250/// getTypeDeclType - Return the unique reference to the type for the
3251/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003252QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003253 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003254 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003255
Richard Smithdda56e42011-04-15 14:24:37 +00003256 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003257 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003258
John McCall96f0b5f2010-03-10 06:48:02 +00003259 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3260 "Template type parameter types are always available.");
3261
John McCall81e38502010-02-16 03:57:14 +00003262 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003263 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003264 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003265 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003266 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003267 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003268 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003269 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003270 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003271 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3272 Decl->TypeForDecl = newType;
3273 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003274 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003275 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003276
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003277 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003278}
3279
Chris Lattner32d920b2007-01-26 02:01:53 +00003280/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003281/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003282QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003283ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3284 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003285 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003286
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003287 if (Canonical.isNull())
3288 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003289 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003290 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003291 Decl->TypeForDecl = newType;
3292 Types.push_back(newType);
3293 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003294}
3295
Jay Foad39c79802011-01-12 09:06:06 +00003296QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003297 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3298
Douglas Gregorec9fd132012-01-14 16:38:05 +00003299 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003300 if (PrevDecl->TypeForDecl)
3301 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3302
John McCall424cec92011-01-19 06:33:43 +00003303 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3304 Decl->TypeForDecl = newType;
3305 Types.push_back(newType);
3306 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003307}
3308
Jay Foad39c79802011-01-12 09:06:06 +00003309QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003310 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3311
Douglas Gregorec9fd132012-01-14 16:38:05 +00003312 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003313 if (PrevDecl->TypeForDecl)
3314 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3315
John McCall424cec92011-01-19 06:33:43 +00003316 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3317 Decl->TypeForDecl = newType;
3318 Types.push_back(newType);
3319 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003320}
3321
John McCall81904512011-01-06 01:58:22 +00003322QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3323 QualType modifiedType,
3324 QualType equivalentType) {
3325 llvm::FoldingSetNodeID id;
3326 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3327
Craig Topper36250ad2014-05-12 05:36:57 +00003328 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003329 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3330 if (type) return QualType(type, 0);
3331
3332 QualType canon = getCanonicalType(equivalentType);
3333 type = new (*this, TypeAlignment)
3334 AttributedType(canon, attrKind, modifiedType, equivalentType);
3335
3336 Types.push_back(type);
3337 AttributedTypes.InsertNode(type, insertPos);
3338
3339 return QualType(type, 0);
3340}
3341
John McCallcebee162009-10-18 09:09:24 +00003342/// \brief Retrieve a substitution-result type.
3343QualType
3344ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003345 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003346 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003347 && "replacement types must always be canonical");
3348
3349 llvm::FoldingSetNodeID ID;
3350 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003351 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003352 SubstTemplateTypeParmType *SubstParm
3353 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3354
3355 if (!SubstParm) {
3356 SubstParm = new (*this, TypeAlignment)
3357 SubstTemplateTypeParmType(Parm, Replacement);
3358 Types.push_back(SubstParm);
3359 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3360 }
3361
3362 return QualType(SubstParm, 0);
3363}
3364
Douglas Gregorada4b792011-01-14 02:55:32 +00003365/// \brief Retrieve a
3366QualType ASTContext::getSubstTemplateTypeParmPackType(
3367 const TemplateTypeParmType *Parm,
3368 const TemplateArgument &ArgPack) {
3369#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003370 for (const auto &P : ArgPack.pack_elements()) {
3371 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3372 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003373 }
3374#endif
3375
3376 llvm::FoldingSetNodeID ID;
3377 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003378 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003379 if (SubstTemplateTypeParmPackType *SubstParm
3380 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3381 return QualType(SubstParm, 0);
3382
3383 QualType Canon;
3384 if (!Parm->isCanonicalUnqualified()) {
3385 Canon = getCanonicalType(QualType(Parm, 0));
3386 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3387 ArgPack);
3388 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3389 }
3390
3391 SubstTemplateTypeParmPackType *SubstParm
3392 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3393 ArgPack);
3394 Types.push_back(SubstParm);
3395 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3396 return QualType(SubstParm, 0);
3397}
3398
Douglas Gregoreff93e02009-02-05 23:33:38 +00003399/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003400/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003401/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003402QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003403 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003404 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003405 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003406 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003407 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003408 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003409 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3410
3411 if (TypeParm)
3412 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003413
Chandler Carruth08836322011-05-01 00:51:33 +00003414 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003415 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003416 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003417
3418 TemplateTypeParmType *TypeCheck
3419 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3420 assert(!TypeCheck && "Template type parameter canonical type broken");
3421 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003422 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003423 TypeParm = new (*this, TypeAlignment)
3424 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003425
3426 Types.push_back(TypeParm);
3427 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3428
3429 return QualType(TypeParm, 0);
3430}
3431
John McCalle78aac42010-03-10 03:28:59 +00003432TypeSourceInfo *
3433ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3434 SourceLocation NameLoc,
3435 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003436 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003437 assert(!Name.getAsDependentTemplateName() &&
3438 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003439 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003440
3441 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003442 TemplateSpecializationTypeLoc TL =
3443 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003444 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003445 TL.setTemplateNameLoc(NameLoc);
3446 TL.setLAngleLoc(Args.getLAngleLoc());
3447 TL.setRAngleLoc(Args.getRAngleLoc());
3448 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3449 TL.setArgLocInfo(i, Args[i].getLocInfo());
3450 return DI;
3451}
3452
Mike Stump11289f42009-09-09 15:08:12 +00003453QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003454ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003455 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003456 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003457 assert(!Template.getAsDependentTemplateName() &&
3458 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003459
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003460 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003461 ArgVec.reserve(Args.size());
3462 for (const TemplateArgumentLoc &Arg : Args.arguments())
3463 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003464
David Majnemer6fbeee32016-07-07 04:43:07 +00003465 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003466}
3467
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003468#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003469static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3470 for (const TemplateArgument &Arg : Args)
3471 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003472 return true;
3473
3474 return true;
3475}
3476#endif
3477
John McCall0ad16662009-10-29 08:12:44 +00003478QualType
3479ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003480 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003481 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003482 assert(!Template.getAsDependentTemplateName() &&
3483 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003484 // Look through qualified template names.
3485 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3486 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003487
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003488 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003489 Template.getAsTemplateDecl() &&
3490 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003491 QualType CanonType;
3492 if (!Underlying.isNull())
3493 CanonType = getCanonicalType(Underlying);
3494 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003495 // We can get here with an alias template when the specialization contains
3496 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003497 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003498 "Caller must compute aliased type");
3499 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003500 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003501 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003502
Douglas Gregora8e02e72009-07-28 23:00:59 +00003503 // Allocate the (non-canonical) template specialization type, but don't
3504 // try to unique it: these types typically have location information that
3505 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003506 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003507 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003508 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003509 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003510 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003511 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003512 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003513
Douglas Gregor8bf42052009-02-09 18:46:07 +00003514 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003515 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003516}
3517
David Majnemer6fbeee32016-07-07 04:43:07 +00003518QualType ASTContext::getCanonicalTemplateSpecializationType(
3519 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003520 assert(!Template.getAsDependentTemplateName() &&
3521 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003522
Douglas Gregore29139c2011-03-03 17:04:51 +00003523 // Look through qualified template names.
3524 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3525 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003526
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003527 // Build the canonical template specialization type.
3528 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003529 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003530 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003531 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003532 for (const TemplateArgument &Arg : Args)
3533 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003534
3535 // Determine whether this canonical template specialization type already
3536 // exists.
3537 llvm::FoldingSetNodeID ID;
3538 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003539 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003540
Craig Topper36250ad2014-05-12 05:36:57 +00003541 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003542 TemplateSpecializationType *Spec
3543 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3544
3545 if (!Spec) {
3546 // Allocate a new canonical template specialization type.
3547 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3548 sizeof(TemplateArgument) * NumArgs),
3549 TypeAlignment);
3550 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003551 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003552 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003553 Types.push_back(Spec);
3554 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3555 }
3556
3557 assert(Spec->isDependentType() &&
3558 "Non-dependent template-id type must have a canonical type");
3559 return QualType(Spec, 0);
3560}
3561
3562QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003563ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3564 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003565 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003566 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003567 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003568
Craig Topper36250ad2014-05-12 05:36:57 +00003569 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003570 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003571 if (T)
3572 return QualType(T, 0);
3573
Douglas Gregorc42075a2010-02-04 18:10:26 +00003574 QualType Canon = NamedType;
3575 if (!Canon.isCanonical()) {
3576 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003577 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3578 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003579 (void)CheckT;
3580 }
3581
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003582 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003583 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003584 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003585 return QualType(T, 0);
3586}
3587
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003588QualType
Jay Foad39c79802011-01-12 09:06:06 +00003589ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003590 llvm::FoldingSetNodeID ID;
3591 ParenType::Profile(ID, InnerType);
3592
Craig Topper36250ad2014-05-12 05:36:57 +00003593 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003594 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 if (T)
3596 return QualType(T, 0);
3597
3598 QualType Canon = InnerType;
3599 if (!Canon.isCanonical()) {
3600 Canon = getCanonicalType(InnerType);
3601 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3602 assert(!CheckT && "Paren canonical type broken");
3603 (void)CheckT;
3604 }
3605
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003606 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003607 Types.push_back(T);
3608 ParenTypes.InsertNode(T, InsertPos);
3609 return QualType(T, 0);
3610}
3611
Douglas Gregor02085352010-03-31 20:19:30 +00003612QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3613 NestedNameSpecifier *NNS,
3614 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003615 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003616 if (Canon.isNull()) {
3617 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003618 ElaboratedTypeKeyword CanonKeyword = Keyword;
3619 if (Keyword == ETK_None)
3620 CanonKeyword = ETK_Typename;
3621
3622 if (CanonNNS != NNS || CanonKeyword != Keyword)
3623 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003624 }
3625
3626 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003627 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003628
Craig Topper36250ad2014-05-12 05:36:57 +00003629 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003630 DependentNameType *T
3631 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003632 if (T)
3633 return QualType(T, 0);
3634
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003635 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003636 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003637 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003638 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003639}
3640
Mike Stump11289f42009-09-09 15:08:12 +00003641QualType
John McCallc392f372010-06-11 00:33:02 +00003642ASTContext::getDependentTemplateSpecializationType(
3643 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003644 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003645 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003646 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003647 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003648 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003649 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3650 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003651 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003652}
3653
3654QualType
3655ASTContext::getDependentTemplateSpecializationType(
3656 ElaboratedTypeKeyword Keyword,
3657 NestedNameSpecifier *NNS,
3658 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003659 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003660 assert((!NNS || NNS->isDependent()) &&
3661 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003662
Douglas Gregorc42075a2010-02-04 18:10:26 +00003663 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003664 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003665 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003666
Craig Topper36250ad2014-05-12 05:36:57 +00003667 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003668 DependentTemplateSpecializationType *T
3669 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003670 if (T)
3671 return QualType(T, 0);
3672
John McCallc392f372010-06-11 00:33:02 +00003673 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003674
John McCallc392f372010-06-11 00:33:02 +00003675 ElaboratedTypeKeyword CanonKeyword = Keyword;
3676 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3677
3678 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003679 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003680 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003681 for (unsigned I = 0; I != NumArgs; ++I) {
3682 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3683 if (!CanonArgs[I].structurallyEquals(Args[I]))
3684 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003685 }
3686
John McCallc392f372010-06-11 00:33:02 +00003687 QualType Canon;
3688 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3689 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003690 Name,
3691 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003692
3693 // Find the insert position again.
3694 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3695 }
3696
3697 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3698 sizeof(TemplateArgument) * NumArgs),
3699 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003700 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003701 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003702 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003703 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003704 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003705}
3706
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003707QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003708 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003709 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003710 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003711
3712 assert(Pattern->containsUnexpandedParameterPack() &&
3713 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003714 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003715 PackExpansionType *T
3716 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3717 if (T)
3718 return QualType(T, 0);
3719
3720 QualType Canon;
3721 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003722 Canon = getCanonicalType(Pattern);
3723 // The canonical type might not contain an unexpanded parameter pack, if it
3724 // contains an alias template specialization which ignores one of its
3725 // parameters.
3726 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003727 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003728
Richard Smith68eea502012-07-16 00:20:35 +00003729 // Find the insert position again, in case we inserted an element into
3730 // PackExpansionTypes and invalidated our insert position.
3731 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3732 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003733 }
3734
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003735 T = new (*this, TypeAlignment)
3736 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003737 Types.push_back(T);
3738 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003739 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003740}
3741
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003742/// CmpProtocolNames - Comparison predicate for sorting protocols
3743/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003744static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3745 ObjCProtocolDecl *const *RHS) {
3746 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003747}
3748
Craig Topper1f26d5b2016-01-03 19:43:23 +00003749static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3750 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003751
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003752 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3753 return false;
3754
Craig Topper1f26d5b2016-01-03 19:43:23 +00003755 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003756 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003757 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003758 return false;
3759 return true;
3760}
3761
Craig Topper6a8c1512015-10-22 01:56:18 +00003762static void
3763SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003764 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003765 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003766
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003767 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003768 for (ObjCProtocolDecl *&P : Protocols)
3769 P = P->getCanonicalDecl();
3770
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003771 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003772 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3773 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003774}
3775
John McCall8b07ec22010-05-15 11:32:37 +00003776QualType ASTContext::getObjCObjectType(QualType BaseType,
3777 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003778 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003779 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003780 llvm::makeArrayRef(Protocols, NumProtocols),
3781 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003782}
3783
3784QualType ASTContext::getObjCObjectType(
3785 QualType baseType,
3786 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003787 ArrayRef<ObjCProtocolDecl *> protocols,
3788 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003789 // If the base type is an interface and there aren't any protocols or
3790 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003791 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3792 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003793 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003794
3795 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003796 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003797 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003798 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003799 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3800 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003801
Douglas Gregore9d95f12015-07-07 03:57:35 +00003802 // Determine the type arguments to be used for canonicalization,
3803 // which may be explicitly specified here or written on the base
3804 // type.
3805 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3806 if (effectiveTypeArgs.empty()) {
3807 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3808 effectiveTypeArgs = baseObject->getTypeArgs();
3809 }
John McCallfc93cf92009-10-22 22:37:11 +00003810
Douglas Gregore9d95f12015-07-07 03:57:35 +00003811 // Build the canonical type, which has the canonical base type and a
3812 // sorted-and-uniqued list of protocols and the type arguments
3813 // canonicalized.
3814 QualType canonical;
3815 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3816 effectiveTypeArgs.end(),
3817 [&](QualType type) {
3818 return type.isCanonical();
3819 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003820 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003821 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3822 // Determine the canonical type arguments.
3823 ArrayRef<QualType> canonTypeArgs;
3824 SmallVector<QualType, 4> canonTypeArgsVec;
3825 if (!typeArgsAreCanonical) {
3826 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3827 for (auto typeArg : effectiveTypeArgs)
3828 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3829 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003830 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003831 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003832 }
3833
Douglas Gregore9d95f12015-07-07 03:57:35 +00003834 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3835 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3836 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003837 canonProtocolsVec.append(protocols.begin(), protocols.end());
3838 SortAndUniqueProtocols(canonProtocolsVec);
3839 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003840 } else {
3841 canonProtocols = protocols;
3842 }
3843
3844 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003845 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003846
John McCallfc93cf92009-10-22 22:37:11 +00003847 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003848 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3849 }
3850
Douglas Gregore9d95f12015-07-07 03:57:35 +00003851 unsigned size = sizeof(ObjCObjectTypeImpl);
3852 size += typeArgs.size() * sizeof(QualType);
3853 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3854 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003855 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003856 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3857 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003858
3859 Types.push_back(T);
3860 ObjCObjectTypes.InsertNode(T, InsertPos);
3861 return QualType(T, 0);
3862}
3863
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003864/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3865/// protocol list adopt all protocols in QT's qualified-id protocol
3866/// list.
3867bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3868 ObjCInterfaceDecl *IC) {
3869 if (!QT->isObjCQualifiedIdType())
3870 return false;
3871
3872 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3873 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003874 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003875 if (!IC->ClassImplementsProtocol(Proto, false))
3876 return false;
3877 }
3878 return true;
3879 }
3880 return false;
3881}
3882
3883/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3884/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3885/// of protocols.
3886bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3887 ObjCInterfaceDecl *IDecl) {
3888 if (!QT->isObjCQualifiedIdType())
3889 return false;
3890 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3891 if (!OPT)
3892 return false;
3893 if (!IDecl->hasDefinition())
3894 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003895 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3896 CollectInheritedProtocols(IDecl, InheritedProtocols);
3897 if (InheritedProtocols.empty())
3898 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003899 // Check that if every protocol in list of id<plist> conforms to a protcol
3900 // of IDecl's, then bridge casting is ok.
3901 bool Conforms = false;
3902 for (auto *Proto : OPT->quals()) {
3903 Conforms = false;
3904 for (auto *PI : InheritedProtocols) {
3905 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3906 Conforms = true;
3907 break;
3908 }
3909 }
3910 if (!Conforms)
3911 break;
3912 }
3913 if (Conforms)
3914 return true;
3915
Aaron Ballman83731462014-03-17 16:14:00 +00003916 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003917 // If both the right and left sides have qualifiers.
3918 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003919 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003920 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003921 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003922 break;
3923 }
3924 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003925 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003926 }
3927 return true;
3928}
3929
John McCall8b07ec22010-05-15 11:32:37 +00003930/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3931/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003932QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003933 llvm::FoldingSetNodeID ID;
3934 ObjCObjectPointerType::Profile(ID, ObjectT);
3935
Craig Topper36250ad2014-05-12 05:36:57 +00003936 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003937 if (ObjCObjectPointerType *QT =
3938 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3939 return QualType(QT, 0);
3940
3941 // Find the canonical object type.
3942 QualType Canonical;
3943 if (!ObjectT.isCanonical()) {
3944 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3945
3946 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003947 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3948 }
3949
Douglas Gregorf85bee62010-02-08 22:59:26 +00003950 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003951 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3952 ObjCObjectPointerType *QType =
3953 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003954
Steve Narofffb4330f2009-06-17 22:40:22 +00003955 Types.push_back(QType);
3956 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003957 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003958}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003959
Douglas Gregor1c283312010-08-11 12:19:30 +00003960/// getObjCInterfaceType - Return the unique reference to the type for the
3961/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003962QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3963 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003964 if (Decl->TypeForDecl)
3965 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003966
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003967 if (PrevDecl) {
3968 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3969 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3970 return QualType(PrevDecl->TypeForDecl, 0);
3971 }
3972
Douglas Gregor7671e532011-12-16 16:34:57 +00003973 // Prefer the definition, if there is one.
3974 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3975 Decl = Def;
3976
Douglas Gregor1c283312010-08-11 12:19:30 +00003977 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3978 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3979 Decl->TypeForDecl = T;
3980 Types.push_back(T);
3981 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003982}
3983
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003984/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3985/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003986/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003987/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003988/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003989QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003990 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003991 if (tofExpr->isTypeDependent()) {
3992 llvm::FoldingSetNodeID ID;
3993 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003994
Craig Topper36250ad2014-05-12 05:36:57 +00003995 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003996 DependentTypeOfExprType *Canon
3997 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3998 if (Canon) {
3999 // We already have a "canonical" version of an identical, dependent
4000 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004001 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004002 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004003 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004004 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004005 Canon
4006 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004007 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4008 toe = Canon;
4009 }
4010 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004011 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004012 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004013 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004014 Types.push_back(toe);
4015 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004016}
4017
Steve Naroffa773cd52007-08-01 18:02:17 +00004018/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004019/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004020/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004021/// an issue. This doesn't affect the type checker, since it operates
4022/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004023QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004024 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004025 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004026 Types.push_back(tot);
4027 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004028}
4029
Richard Smith8eb1d322014-06-05 20:13:13 +00004030/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4031/// nodes. This would never be helpful, since each such type has its own
4032/// expression, and would not give a significant memory saving, since there
4033/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004034QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004035 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004036
4037 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004038 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004039 // unique dependent type. Two such decltype-specifiers refer to the same
4040 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004041 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004042 llvm::FoldingSetNodeID ID;
4043 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004044
Craig Topper36250ad2014-05-12 05:36:57 +00004045 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004046 DependentDecltypeType *Canon
4047 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004048 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004049 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004050 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004051 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004052 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004053 dt = new (*this, TypeAlignment)
4054 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004055 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004056 dt = new (*this, TypeAlignment)
4057 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004058 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004059 Types.push_back(dt);
4060 return QualType(dt, 0);
4061}
4062
Alexis Hunte852b102011-05-24 22:41:36 +00004063/// getUnaryTransformationType - We don't unique these, since the memory
4064/// savings are minimal and these are rare.
4065QualType ASTContext::getUnaryTransformType(QualType BaseType,
4066 QualType UnderlyingType,
4067 UnaryTransformType::UTTKind Kind)
4068 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004069 UnaryTransformType *ut = nullptr;
4070
4071 if (BaseType->isDependentType()) {
4072 // Look in the folding set for an existing type.
4073 llvm::FoldingSetNodeID ID;
4074 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4075
4076 void *InsertPos = nullptr;
4077 DependentUnaryTransformType *Canon
4078 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4079
4080 if (!Canon) {
4081 // Build a new, canonical __underlying_type(type) type.
4082 Canon = new (*this, TypeAlignment)
4083 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4084 Kind);
4085 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4086 }
4087 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4088 QualType(), Kind,
4089 QualType(Canon, 0));
4090 } else {
4091 QualType CanonType = getCanonicalType(UnderlyingType);
4092 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4093 UnderlyingType, Kind,
4094 CanonType);
4095 }
4096 Types.push_back(ut);
4097 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004098}
4099
Richard Smith2a7d4812013-05-04 07:00:32 +00004100/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4101/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4102/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004103QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004104 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004105 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004106 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004107
Richard Smith2a7d4812013-05-04 07:00:32 +00004108 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004109 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004110 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004111 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004112 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4113 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004114
Richard Smith74aeef52013-04-26 16:15:35 +00004115 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004116 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004117 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004118 Types.push_back(AT);
4119 if (InsertPos)
4120 AutoTypes.InsertNode(AT, InsertPos);
4121 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004122}
4123
Eli Friedman0dfb8892011-10-06 23:00:33 +00004124/// getAtomicType - Return the uniqued reference to the atomic type for
4125/// the given value type.
4126QualType ASTContext::getAtomicType(QualType T) const {
4127 // Unique pointers, to guarantee there is only one pointer of a particular
4128 // structure.
4129 llvm::FoldingSetNodeID ID;
4130 AtomicType::Profile(ID, T);
4131
Craig Topper36250ad2014-05-12 05:36:57 +00004132 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004133 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4134 return QualType(AT, 0);
4135
4136 // If the atomic value type isn't canonical, this won't be a canonical type
4137 // either, so fill in the canonical type field.
4138 QualType Canonical;
4139 if (!T.isCanonical()) {
4140 Canonical = getAtomicType(getCanonicalType(T));
4141
4142 // Get the new insert position for the node we care about.
4143 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004144 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004145 }
4146 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4147 Types.push_back(New);
4148 AtomicTypes.InsertNode(New, InsertPos);
4149 return QualType(New, 0);
4150}
4151
Richard Smith02e85f32011-04-14 22:09:26 +00004152/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4153QualType ASTContext::getAutoDeductType() const {
4154 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004155 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004156 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004157 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004158 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004159 return AutoDeductTy;
4160}
4161
4162/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4163QualType ASTContext::getAutoRRefDeductType() const {
4164 if (AutoRRefDeductTy.isNull())
4165 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4166 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4167 return AutoRRefDeductTy;
4168}
4169
Chris Lattnerfb072462007-01-23 05:45:31 +00004170/// getTagDeclType - Return the unique reference to the type for the
4171/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004172QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004173 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004174 // FIXME: What is the design on getTagDeclType when it requires casting
4175 // away const? mutable?
4176 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004177}
4178
Mike Stump11289f42009-09-09 15:08:12 +00004179/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4180/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4181/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004182CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004183 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004184}
Chris Lattnerfb072462007-01-23 05:45:31 +00004185
Hans Wennborg27541db2011-10-27 08:29:09 +00004186/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4187CanQualType ASTContext::getIntMaxType() const {
4188 return getFromTargetType(Target->getIntMaxType());
4189}
4190
4191/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4192CanQualType ASTContext::getUIntMaxType() const {
4193 return getFromTargetType(Target->getUIntMaxType());
4194}
4195
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004196/// getSignedWCharType - Return the type of "signed wchar_t".
4197/// Used when in C++, as a GCC extension.
4198QualType ASTContext::getSignedWCharType() const {
4199 // FIXME: derive from "Target" ?
4200 return WCharTy;
4201}
4202
4203/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4204/// Used when in C++, as a GCC extension.
4205QualType ASTContext::getUnsignedWCharType() const {
4206 // FIXME: derive from "Target" ?
4207 return UnsignedIntTy;
4208}
4209
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004210QualType ASTContext::getIntPtrType() const {
4211 return getFromTargetType(Target->getIntPtrType());
4212}
4213
4214QualType ASTContext::getUIntPtrType() const {
4215 return getCorrespondingUnsignedType(getIntPtrType());
4216}
4217
Hans Wennborg27541db2011-10-27 08:29:09 +00004218/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004219/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4220QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004221 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004222}
4223
Eli Friedman4e91899e2012-11-27 02:58:24 +00004224/// \brief Return the unique type for "pid_t" defined in
4225/// <sys/types.h>. We need this to compute the correct type for vfork().
4226QualType ASTContext::getProcessIDType() const {
4227 return getFromTargetType(Target->getProcessIDType());
4228}
4229
Chris Lattnera21ad802008-04-02 05:18:44 +00004230//===----------------------------------------------------------------------===//
4231// Type Operators
4232//===----------------------------------------------------------------------===//
4233
Jay Foad39c79802011-01-12 09:06:06 +00004234CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004235 // Push qualifiers into arrays, and then discard any remaining
4236 // qualifiers.
4237 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004238 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004239 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004240 QualType Result;
4241 if (isa<ArrayType>(Ty)) {
4242 Result = getArrayDecayedType(QualType(Ty,0));
4243 } else if (isa<FunctionType>(Ty)) {
4244 Result = getPointerType(QualType(Ty, 0));
4245 } else {
4246 Result = QualType(Ty, 0);
4247 }
4248
4249 return CanQualType::CreateUnsafe(Result);
4250}
4251
John McCall6c9dd522011-01-18 07:41:22 +00004252QualType ASTContext::getUnqualifiedArrayType(QualType type,
4253 Qualifiers &quals) {
4254 SplitQualType splitType = type.getSplitUnqualifiedType();
4255
4256 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4257 // the unqualified desugared type and then drops it on the floor.
4258 // We then have to strip that sugar back off with
4259 // getUnqualifiedDesugaredType(), which is silly.
4260 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004261 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004262
4263 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004264 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004265 quals = splitType.Quals;
4266 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004267 }
4268
John McCall6c9dd522011-01-18 07:41:22 +00004269 // Otherwise, recurse on the array's element type.
4270 QualType elementType = AT->getElementType();
4271 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4272
4273 // If that didn't change the element type, AT has no qualifiers, so we
4274 // can just use the results in splitType.
4275 if (elementType == unqualElementType) {
4276 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004277 quals = splitType.Quals;
4278 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004279 }
4280
4281 // Otherwise, add in the qualifiers from the outermost type, then
4282 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004283 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004284
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004285 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004286 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004287 CAT->getSizeModifier(), 0);
4288 }
4289
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004290 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004291 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004292 }
4293
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004294 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004295 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004296 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004297 VAT->getSizeModifier(),
4298 VAT->getIndexTypeCVRQualifiers(),
4299 VAT->getBracketsRange());
4300 }
4301
4302 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004303 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004304 DSAT->getSizeModifier(), 0,
4305 SourceRange());
4306}
4307
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004308/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4309/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4310/// they point to and return true. If T1 and T2 aren't pointer types
4311/// or pointer-to-member types, or if they are not similar at this
4312/// level, returns false and leaves T1 and T2 unchanged. Top-level
4313/// qualifiers on T1 and T2 are ignored. This function will typically
4314/// be called in a loop that successively "unwraps" pointer and
4315/// pointer-to-member types to compare them at each level.
4316bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4317 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4318 *T2PtrType = T2->getAs<PointerType>();
4319 if (T1PtrType && T2PtrType) {
4320 T1 = T1PtrType->getPointeeType();
4321 T2 = T2PtrType->getPointeeType();
4322 return true;
4323 }
4324
4325 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4326 *T2MPType = T2->getAs<MemberPointerType>();
4327 if (T1MPType && T2MPType &&
4328 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4329 QualType(T2MPType->getClass(), 0))) {
4330 T1 = T1MPType->getPointeeType();
4331 T2 = T2MPType->getPointeeType();
4332 return true;
4333 }
4334
David Blaikiebbafb8a2012-03-11 07:00:24 +00004335 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004336 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4337 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4338 if (T1OPType && T2OPType) {
4339 T1 = T1OPType->getPointeeType();
4340 T2 = T2OPType->getPointeeType();
4341 return true;
4342 }
4343 }
4344
4345 // FIXME: Block pointers, too?
4346
4347 return false;
4348}
4349
Jay Foad39c79802011-01-12 09:06:06 +00004350DeclarationNameInfo
4351ASTContext::getNameForTemplate(TemplateName Name,
4352 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004353 switch (Name.getKind()) {
4354 case TemplateName::QualifiedTemplate:
4355 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004356 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004357 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4358 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004359
John McCalld9dfe3a2011-06-30 08:33:18 +00004360 case TemplateName::OverloadedTemplate: {
4361 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4362 // DNInfo work in progress: CHECKME: what about DNLoc?
4363 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4364 }
4365
4366 case TemplateName::DependentTemplate: {
4367 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004368 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004369 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004370 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4371 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004372 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004373 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4374 // DNInfo work in progress: FIXME: source locations?
4375 DeclarationNameLoc DNLoc;
4376 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4377 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4378 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004379 }
4380 }
4381
John McCalld9dfe3a2011-06-30 08:33:18 +00004382 case TemplateName::SubstTemplateTemplateParm: {
4383 SubstTemplateTemplateParmStorage *subst
4384 = Name.getAsSubstTemplateTemplateParm();
4385 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4386 NameLoc);
4387 }
4388
4389 case TemplateName::SubstTemplateTemplateParmPack: {
4390 SubstTemplateTemplateParmPackStorage *subst
4391 = Name.getAsSubstTemplateTemplateParmPack();
4392 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4393 NameLoc);
4394 }
4395 }
4396
4397 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004398}
4399
Jay Foad39c79802011-01-12 09:06:06 +00004400TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004401 switch (Name.getKind()) {
4402 case TemplateName::QualifiedTemplate:
4403 case TemplateName::Template: {
4404 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004405 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004406 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004407 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4408
4409 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004410 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004411 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004412
John McCalld9dfe3a2011-06-30 08:33:18 +00004413 case TemplateName::OverloadedTemplate:
4414 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004415
John McCalld9dfe3a2011-06-30 08:33:18 +00004416 case TemplateName::DependentTemplate: {
4417 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4418 assert(DTN && "Non-dependent template names must refer to template decls.");
4419 return DTN->CanonicalTemplateName;
4420 }
4421
4422 case TemplateName::SubstTemplateTemplateParm: {
4423 SubstTemplateTemplateParmStorage *subst
4424 = Name.getAsSubstTemplateTemplateParm();
4425 return getCanonicalTemplateName(subst->getReplacement());
4426 }
4427
4428 case TemplateName::SubstTemplateTemplateParmPack: {
4429 SubstTemplateTemplateParmPackStorage *subst
4430 = Name.getAsSubstTemplateTemplateParmPack();
4431 TemplateTemplateParmDecl *canonParameter
4432 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4433 TemplateArgument canonArgPack
4434 = getCanonicalTemplateArgument(subst->getArgumentPack());
4435 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4436 }
4437 }
4438
4439 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004440}
4441
Douglas Gregoradee3e32009-11-11 23:06:43 +00004442bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4443 X = getCanonicalTemplateName(X);
4444 Y = getCanonicalTemplateName(Y);
4445 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4446}
4447
Mike Stump11289f42009-09-09 15:08:12 +00004448TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004449ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004450 switch (Arg.getKind()) {
4451 case TemplateArgument::Null:
4452 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004453
Douglas Gregora8e02e72009-07-28 23:00:59 +00004454 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004455 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004456
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004457 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004458 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004459 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004460 }
Mike Stump11289f42009-09-09 15:08:12 +00004461
Eli Friedmanb826a002012-09-26 02:36:12 +00004462 case TemplateArgument::NullPtr:
4463 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4464 /*isNullPtr*/true);
4465
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004466 case TemplateArgument::Template:
4467 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004468
4469 case TemplateArgument::TemplateExpansion:
4470 return TemplateArgument(getCanonicalTemplateName(
4471 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004472 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004473
Douglas Gregora8e02e72009-07-28 23:00:59 +00004474 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004475 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004476
Douglas Gregora8e02e72009-07-28 23:00:59 +00004477 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004478 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004479
Douglas Gregora8e02e72009-07-28 23:00:59 +00004480 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004481 if (Arg.pack_size() == 0)
4482 return Arg;
4483
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004484 TemplateArgument *CanonArgs
4485 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004486 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004487 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004488 AEnd = Arg.pack_end();
4489 A != AEnd; (void)++A, ++Idx)
4490 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004491
Benjamin Kramercce63472015-08-05 09:40:22 +00004492 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004493 }
4494 }
4495
4496 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004497 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004498}
4499
Douglas Gregor333489b2009-03-27 23:10:48 +00004500NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004501ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004502 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004503 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004504
4505 switch (NNS->getKind()) {
4506 case NestedNameSpecifier::Identifier:
4507 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004508 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004509 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4510 NNS->getAsIdentifier());
4511
4512 case NestedNameSpecifier::Namespace:
4513 // A namespace is canonical; build a nested-name-specifier with
4514 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004515 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004516 NNS->getAsNamespace()->getOriginalNamespace());
4517
4518 case NestedNameSpecifier::NamespaceAlias:
4519 // A namespace is canonical; build a nested-name-specifier with
4520 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004521 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004522 NNS->getAsNamespaceAlias()->getNamespace()
4523 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004524
4525 case NestedNameSpecifier::TypeSpec:
4526 case NestedNameSpecifier::TypeSpecWithTemplate: {
4527 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004528
4529 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4530 // break it apart into its prefix and identifier, then reconsititute those
4531 // as the canonical nested-name-specifier. This is required to canonicalize
4532 // a dependent nested-name-specifier involving typedefs of dependent-name
4533 // types, e.g.,
4534 // typedef typename T::type T1;
4535 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004536 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4537 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004538 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004539
Eli Friedman5358a0a2012-03-03 04:09:56 +00004540 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4541 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4542 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004543 return NestedNameSpecifier::Create(*this, nullptr, false,
4544 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004545 }
4546
4547 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004548 case NestedNameSpecifier::Super:
4549 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004550 return NNS;
4551 }
4552
David Blaikie8a40f702012-01-17 06:56:22 +00004553 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004554}
4555
Jay Foad39c79802011-01-12 09:06:06 +00004556const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004557 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004558 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004559 // Handle the common positive case fast.
4560 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4561 return AT;
4562 }
Mike Stump11289f42009-09-09 15:08:12 +00004563
John McCall8ccfcb52009-09-24 19:53:00 +00004564 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004565 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004566 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004567
John McCall8ccfcb52009-09-24 19:53:00 +00004568 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004569 // implements C99 6.7.3p8: "If the specification of an array type includes
4570 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004571
Chris Lattner7adf0762008-08-04 07:31:14 +00004572 // If we get here, we either have type qualifiers on the type, or we have
4573 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004574 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004575
John McCall33ddac02011-01-19 10:06:00 +00004576 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004577 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004578
Chris Lattner7adf0762008-08-04 07:31:14 +00004579 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004580 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004581 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004582 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004583
Chris Lattner7adf0762008-08-04 07:31:14 +00004584 // Otherwise, we have an array and we have qualifiers on it. Push the
4585 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004586 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004587
Chris Lattner7adf0762008-08-04 07:31:14 +00004588 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4589 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4590 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004591 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004592 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4593 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4594 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004595 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004596
Mike Stump11289f42009-09-09 15:08:12 +00004597 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004598 = dyn_cast<DependentSizedArrayType>(ATy))
4599 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004600 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004601 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004602 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004603 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004604 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004605
Chris Lattner7adf0762008-08-04 07:31:14 +00004606 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004607 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004608 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004609 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004610 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004611 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004612}
4613
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004614QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004615 if (T->isArrayType() || T->isFunctionType())
4616 return getDecayedType(T);
4617 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004618}
4619
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004620QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004621 T = getVariableArrayDecayedType(T);
4622 T = getAdjustedParameterType(T);
4623 return T.getUnqualifiedType();
4624}
4625
David Majnemerd09a51c2015-03-03 01:50:05 +00004626QualType ASTContext::getExceptionObjectType(QualType T) const {
4627 // C++ [except.throw]p3:
4628 // A throw-expression initializes a temporary object, called the exception
4629 // object, the type of which is determined by removing any top-level
4630 // cv-qualifiers from the static type of the operand of throw and adjusting
4631 // the type from "array of T" or "function returning T" to "pointer to T"
4632 // or "pointer to function returning T", [...]
4633 T = getVariableArrayDecayedType(T);
4634 if (T->isArrayType() || T->isFunctionType())
4635 T = getDecayedType(T);
4636 return T.getUnqualifiedType();
4637}
4638
Chris Lattnera21ad802008-04-02 05:18:44 +00004639/// getArrayDecayedType - Return the properly qualified result of decaying the
4640/// specified array type to a pointer. This operation is non-trivial when
4641/// handling typedefs etc. The canonical type of "T" must be an array type,
4642/// this returns a pointer to a properly qualified element of the array.
4643///
4644/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004645QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004646 // Get the element type with 'getAsArrayType' so that we don't lose any
4647 // typedefs in the element type of the array. This also handles propagation
4648 // of type qualifiers from the array type into the element type if present
4649 // (C99 6.7.3p8).
4650 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4651 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004652
Chris Lattner7adf0762008-08-04 07:31:14 +00004653 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004654
4655 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004656 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004657}
4658
John McCall33ddac02011-01-19 10:06:00 +00004659QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4660 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004661}
4662
John McCall33ddac02011-01-19 10:06:00 +00004663QualType ASTContext::getBaseElementType(QualType type) const {
4664 Qualifiers qs;
4665 while (true) {
4666 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004667 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004668 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004669
John McCall33ddac02011-01-19 10:06:00 +00004670 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004671 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004672 }
Mike Stump11289f42009-09-09 15:08:12 +00004673
John McCall33ddac02011-01-19 10:06:00 +00004674 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004675}
4676
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004677/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004678uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004679ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4680 uint64_t ElementCount = 1;
4681 do {
4682 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004683 CA = dyn_cast_or_null<ConstantArrayType>(
4684 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004685 } while (CA);
4686 return ElementCount;
4687}
4688
Steve Naroff0af91202007-04-27 21:51:21 +00004689/// getFloatingRank - Return a relative rank for floating point types.
4690/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004691static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004692 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004693 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004694
John McCall9dd450b2009-09-21 23:43:11 +00004695 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4696 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004697 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004698 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004699 case BuiltinType::Float: return FloatRank;
4700 case BuiltinType::Double: return DoubleRank;
4701 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004702 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00004703 }
4704}
4705
Mike Stump11289f42009-09-09 15:08:12 +00004706/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4707/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004708/// 'typeDomain' is a real floating point or complex type.
4709/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004710QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4711 QualType Domain) const {
4712 FloatingRank EltRank = getFloatingRank(Size);
4713 if (Domain->isComplexType()) {
4714 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004715 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004716 case FloatRank: return FloatComplexTy;
4717 case DoubleRank: return DoubleComplexTy;
4718 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004719 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004720 }
Steve Naroff0af91202007-04-27 21:51:21 +00004721 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004722
4723 assert(Domain->isRealFloatingType() && "Unknown domain!");
4724 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004725 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004726 case FloatRank: return FloatTy;
4727 case DoubleRank: return DoubleTy;
4728 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004729 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00004730 }
David Blaikief47fa302012-01-17 02:30:50 +00004731 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004732}
4733
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004734/// getFloatingTypeOrder - Compare the rank of the two specified floating
4735/// point types, ignoring the domain of the type (i.e. 'double' ==
4736/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004737/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004738int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004739 FloatingRank LHSR = getFloatingRank(LHS);
4740 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004741
Chris Lattnerb90739d2008-04-06 23:38:49 +00004742 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004743 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004744 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004745 return 1;
4746 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004747}
4748
Chris Lattner76a00cf2008-04-06 22:59:24 +00004749/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4750/// routine will assert if passed a built-in type that isn't an integer or enum,
4751/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004752unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004753 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004754
Chris Lattner76a00cf2008-04-06 22:59:24 +00004755 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004756 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004757 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004758 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004759 case BuiltinType::Char_S:
4760 case BuiltinType::Char_U:
4761 case BuiltinType::SChar:
4762 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004763 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004764 case BuiltinType::Short:
4765 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004766 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004767 case BuiltinType::Int:
4768 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004769 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004770 case BuiltinType::Long:
4771 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004772 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004773 case BuiltinType::LongLong:
4774 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004775 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004776 case BuiltinType::Int128:
4777 case BuiltinType::UInt128:
4778 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004779 }
4780}
4781
Eli Friedman629ffb92009-08-20 04:21:42 +00004782/// \brief Whether this is a promotable bitfield reference according
4783/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4784///
4785/// \returns the type this bit-field will promote to, or NULL if no
4786/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004787QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004788 if (E->isTypeDependent() || E->isValueDependent())
4789 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004790
4791 // FIXME: We should not do this unless E->refersToBitField() is true. This
4792 // matters in C where getSourceBitField() will find bit-fields for various
4793 // cases where the source expression is not a bit-field designator.
4794
John McCalld25db7e2013-05-06 21:39:12 +00004795 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004796 if (!Field)
4797 return QualType();
4798
4799 QualType FT = Field->getType();
4800
Richard Smithcaf33902011-10-10 18:28:20 +00004801 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004802 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004803 // C++ [conv.prom]p5:
4804 // A prvalue for an integral bit-field can be converted to a prvalue of type
4805 // int if int can represent all the values of the bit-field; otherwise, it
4806 // can be converted to unsigned int if unsigned int can represent all the
4807 // values of the bit-field. If the bit-field is larger yet, no integral
4808 // promotion applies to it.
4809 // C11 6.3.1.1/2:
4810 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4811 // If an int can represent all values of the original type (as restricted by
4812 // the width, for a bit-field), the value is converted to an int; otherwise,
4813 // it is converted to an unsigned int.
4814 //
4815 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4816 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004817 if (BitWidth < IntSize)
4818 return IntTy;
4819
4820 if (BitWidth == IntSize)
4821 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4822
4823 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004824 // like the base type. GCC has some weird bugs in this area that we
4825 // deliberately do not follow (GCC follows a pre-standard resolution to
4826 // C's DR315 which treats bit-width as being part of the type, and this leaks
4827 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004828 return QualType();
4829}
4830
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004831/// getPromotedIntegerType - Returns the type that Promotable will
4832/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4833/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004834QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004835 assert(!Promotable.isNull());
4836 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004837 if (const EnumType *ET = Promotable->getAs<EnumType>())
4838 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004839
4840 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4841 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4842 // (3.9.1) can be converted to a prvalue of the first of the following
4843 // types that can represent all the values of its underlying type:
4844 // int, unsigned int, long int, unsigned long int, long long int, or
4845 // unsigned long long int [...]
4846 // FIXME: Is there some better way to compute this?
4847 if (BT->getKind() == BuiltinType::WChar_S ||
4848 BT->getKind() == BuiltinType::WChar_U ||
4849 BT->getKind() == BuiltinType::Char16 ||
4850 BT->getKind() == BuiltinType::Char32) {
4851 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4852 uint64_t FromSize = getTypeSize(BT);
4853 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4854 LongLongTy, UnsignedLongLongTy };
4855 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4856 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4857 if (FromSize < ToSize ||
4858 (FromSize == ToSize &&
4859 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4860 return PromoteTypes[Idx];
4861 }
4862 llvm_unreachable("char type should fit into long long");
4863 }
4864 }
4865
4866 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004867 if (Promotable->isSignedIntegerType())
4868 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004869 uint64_t PromotableSize = getIntWidth(Promotable);
4870 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004871 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4872 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4873}
4874
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004875/// \brief Recurses in pointer/array types until it finds an objc retainable
4876/// type and returns its ownership.
4877Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4878 while (!T.isNull()) {
4879 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4880 return T.getObjCLifetime();
4881 if (T->isArrayType())
4882 T = getBaseElementType(T);
4883 else if (const PointerType *PT = T->getAs<PointerType>())
4884 T = PT->getPointeeType();
4885 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004886 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004887 else
4888 break;
4889 }
4890
4891 return Qualifiers::OCL_None;
4892}
4893
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004894static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4895 // Incomplete enum types are not treated as integer types.
4896 // FIXME: In C++, enum types are never integer types.
4897 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4898 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004899 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004900}
4901
Mike Stump11289f42009-09-09 15:08:12 +00004902/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004903/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004904/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004905int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004906 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4907 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004908
4909 // Unwrap enums to their underlying type.
4910 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4911 LHSC = getIntegerTypeForEnum(ET);
4912 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4913 RHSC = getIntegerTypeForEnum(ET);
4914
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004915 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004916
Chris Lattner76a00cf2008-04-06 22:59:24 +00004917 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4918 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004919
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004920 unsigned LHSRank = getIntegerRank(LHSC);
4921 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004922
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004923 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4924 if (LHSRank == RHSRank) return 0;
4925 return LHSRank > RHSRank ? 1 : -1;
4926 }
Mike Stump11289f42009-09-09 15:08:12 +00004927
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004928 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4929 if (LHSUnsigned) {
4930 // If the unsigned [LHS] type is larger, return it.
4931 if (LHSRank >= RHSRank)
4932 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004933
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004934 // If the signed type can represent all values of the unsigned type, it
4935 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004936 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004937 return -1;
4938 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004939
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004940 // If the unsigned [RHS] type is larger, return it.
4941 if (RHSRank >= LHSRank)
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;
Steve Naroffe4718892007-04-27 18:30:00 +00004948}
Anders Carlsson98f07902007-08-17 05:31:46 +00004949
Ben Langmuirf5416742016-02-04 00:55:24 +00004950TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004951 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004952 assert(!CFConstantStringTagDecl &&
4953 "tag and typedef should be initialized together");
4954 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4955 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004956
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004957 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00004958 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00004959
Anders Carlsson98f07902007-08-17 05:31:46 +00004960 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004961 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004962 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004963 // int flags;
4964 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004965 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00004966 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004967 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004968 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00004969 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004970 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004971 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00004972
Anders Carlsson98f07902007-08-17 05:31:46 +00004973 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004974 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004975 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004976 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00004977 SourceLocation(),
4978 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00004979 FieldTypes[i], /*TInfo=*/nullptr,
4980 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004981 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004982 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004983 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00004984 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004985 }
4986
Ben Langmuirf5416742016-02-04 00:55:24 +00004987 CFConstantStringTagDecl->completeDefinition();
4988 // This type is designed to be compatible with NSConstantString, but cannot
4989 // use the same name, since NSConstantString is an interface.
4990 auto tagType = getTagDeclType(CFConstantStringTagDecl);
4991 CFConstantStringTypeDecl =
4992 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00004993 }
Mike Stump11289f42009-09-09 15:08:12 +00004994
Quentin Colombet043406b2016-02-03 22:41:00 +00004995 return CFConstantStringTypeDecl;
4996}
4997
Ben Langmuirf5416742016-02-04 00:55:24 +00004998RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4999 if (!CFConstantStringTagDecl)
5000 getCFConstantStringDecl(); // Build the tag and the typedef.
5001 return CFConstantStringTagDecl;
5002}
5003
Quentin Colombet043406b2016-02-03 22:41:00 +00005004// getCFConstantStringType - Return the type used for constant CFStrings.
5005QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005006 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005007}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005008
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005009QualType ASTContext::getObjCSuperType() const {
5010 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005011 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005012 TUDecl->addDecl(ObjCSuperTypeDecl);
5013 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5014 }
5015 return ObjCSuperType;
5016}
5017
Douglas Gregor512b0772009-04-23 22:29:11 +00005018void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005019 const TypedefType *TD = T->getAs<TypedefType>();
5020 assert(TD && "Invalid CFConstantStringType");
5021 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5022 auto TagType =
5023 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5024 assert(TagType && "Invalid CFConstantStringType");
5025 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005026}
5027
Jay Foad39c79802011-01-12 09:06:06 +00005028QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005029 if (BlockDescriptorType)
5030 return getTagDeclType(BlockDescriptorType);
5031
Alp Toker2dea15b2013-12-17 01:22:38 +00005032 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005033 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005034 RD = buildImplicitRecord("__block_descriptor");
5035 RD->startDefinition();
5036
Mike Stumpd0153282009-10-20 02:12:22 +00005037 QualType FieldTypes[] = {
5038 UnsignedLongTy,
5039 UnsignedLongTy,
5040 };
5041
Craig Topperd6d31ac2013-07-15 08:24:27 +00005042 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005043 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005044 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005045 };
5046
5047 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005048 FieldDecl *Field = FieldDecl::Create(
5049 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005050 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5051 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005052 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005053 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005054 }
5055
Alp Toker2dea15b2013-12-17 01:22:38 +00005056 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005057
Alp Toker2dea15b2013-12-17 01:22:38 +00005058 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005059
5060 return getTagDeclType(BlockDescriptorType);
5061}
5062
Jay Foad39c79802011-01-12 09:06:06 +00005063QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005064 if (BlockDescriptorExtendedType)
5065 return getTagDeclType(BlockDescriptorExtendedType);
5066
Alp Toker2dea15b2013-12-17 01:22:38 +00005067 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005068 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005069 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5070 RD->startDefinition();
5071
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005072 QualType FieldTypes[] = {
5073 UnsignedLongTy,
5074 UnsignedLongTy,
5075 getPointerType(VoidPtrTy),
5076 getPointerType(VoidPtrTy)
5077 };
5078
Craig Topperd6d31ac2013-07-15 08:24:27 +00005079 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005080 "reserved",
5081 "Size",
5082 "CopyFuncPtr",
5083 "DestroyFuncPtr"
5084 };
5085
5086 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005087 FieldDecl *Field = FieldDecl::Create(
5088 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005089 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5090 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005091 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005092 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005093 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005094 }
5095
Alp Toker2dea15b2013-12-17 01:22:38 +00005096 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005097
Alp Toker2dea15b2013-12-17 01:22:38 +00005098 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005099 return getTagDeclType(BlockDescriptorExtendedType);
5100}
5101
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005102/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5103/// requires copy/dispose. Note that this must match the logic
5104/// in buildByrefHelpers.
5105bool ASTContext::BlockRequiresCopying(QualType Ty,
5106 const VarDecl *D) {
5107 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5108 const Expr *copyExpr = getBlockVarCopyInits(D);
5109 if (!copyExpr && record->hasTrivialDestructor()) return false;
5110
Mike Stump94967902009-10-21 18:16:27 +00005111 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005112 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005113
5114 if (!Ty->isObjCRetainableType()) return false;
5115
5116 Qualifiers qs = Ty.getQualifiers();
5117
5118 // If we have lifetime, that dominates.
5119 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005120 switch (lifetime) {
5121 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5122
5123 // These are just bits as far as the runtime is concerned.
5124 case Qualifiers::OCL_ExplicitNone:
5125 case Qualifiers::OCL_Autoreleasing:
5126 return false;
5127
5128 // Tell the runtime that this is ARC __weak, called by the
5129 // byref routines.
5130 case Qualifiers::OCL_Weak:
5131 // ARC __strong __block variables need to be retained.
5132 case Qualifiers::OCL_Strong:
5133 return true;
5134 }
5135 llvm_unreachable("fell out of lifetime switch!");
5136 }
5137 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5138 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005139}
5140
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005141bool ASTContext::getByrefLifetime(QualType Ty,
5142 Qualifiers::ObjCLifetime &LifeTime,
5143 bool &HasByrefExtendedLayout) const {
5144
5145 if (!getLangOpts().ObjC1 ||
5146 getLangOpts().getGC() != LangOptions::NonGC)
5147 return false;
5148
5149 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005150 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005151 HasByrefExtendedLayout = true;
5152 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005153 } else if ((LifeTime = Ty.getObjCLifetime())) {
5154 // Honor the ARC qualifiers.
5155 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5156 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005157 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005158 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005159 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005160 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005161 return true;
5162}
5163
Douglas Gregorbab8a962011-09-08 01:46:34 +00005164TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5165 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005166 ObjCInstanceTypeDecl =
5167 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005168 return ObjCInstanceTypeDecl;
5169}
5170
Anders Carlsson18acd442007-10-29 06:33:42 +00005171// This returns true if a type has been typedefed to BOOL:
5172// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005173static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005174 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005175 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5176 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005177
Anders Carlssond8499822007-10-29 05:01:08 +00005178 return false;
5179}
5180
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005181/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005182/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005183CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005184 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5185 return CharUnits::Zero();
5186
Ken Dyck40775002010-01-11 17:06:35 +00005187 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005188
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005189 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005190 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005191 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005192 // Treat arrays as pointers, since that's how they're passed in.
5193 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005194 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005195 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005196}
5197
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005198bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005199 return getTargetInfo().getCXXABI().isMicrosoft() &&
5200 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005201 VD->getType()->isIntegralOrEnumerationType() &&
5202 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005203}
5204
Richard Smithd9b90092016-07-02 01:32:16 +00005205ASTContext::InlineVariableDefinitionKind
5206ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5207 if (!VD->isInline())
5208 return InlineVariableDefinitionKind::None;
5209
5210 // In almost all cases, it's a weak definition.
5211 auto *First = VD->getFirstDecl();
5212 if (!First->isConstexpr() || First->isInlineSpecified() ||
5213 !VD->isStaticDataMember())
5214 return InlineVariableDefinitionKind::Weak;
5215
5216 // If there's a file-context declaration in this translation unit, it's a
5217 // non-discardable definition.
5218 for (auto *D : VD->redecls())
5219 if (D->getLexicalDeclContext()->isFileContext())
5220 return InlineVariableDefinitionKind::Strong;
5221
5222 // If we've not seen one yet, we don't know.
5223 return InlineVariableDefinitionKind::WeakUnknown;
5224}
5225
Ken Dyck40775002010-01-11 17:06:35 +00005226static inline
5227std::string charUnitsToString(const CharUnits &CU) {
5228 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005229}
5230
John McCall351762c2011-02-07 10:33:21 +00005231/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005232/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005233std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5234 std::string S;
5235
David Chisnall950a9512009-11-17 19:33:30 +00005236 const BlockDecl *Decl = Expr->getBlockDecl();
5237 QualType BlockTy =
5238 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5239 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005240 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005241 getObjCEncodingForMethodParameter(
5242 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5243 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005244 else
Alp Toker314cc812014-01-25 16:55:45 +00005245 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005246 // Compute size of all parameters.
5247 // Start with computing size of a pointer in number of bytes.
5248 // FIXME: There might(should) be a better way of doing this computation!
5249 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005250 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5251 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005252 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005253 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005254 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005255 if (sz.isZero())
5256 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005257 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005258 ParmOffset += sz;
5259 }
5260 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005261 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005262 // Block pointer and offset.
5263 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005264
5265 // Argument types.
5266 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005267 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005268 QualType PType = PVDecl->getOriginalType();
5269 if (const ArrayType *AT =
5270 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5271 // Use array's original type only if it has known number of
5272 // elements.
5273 if (!isa<ConstantArrayType>(AT))
5274 PType = PVDecl->getType();
5275 } else if (PType->isFunctionType())
5276 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005277 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005278 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5279 S, true /*Extended*/);
5280 else
5281 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005282 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005283 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005284 }
John McCall351762c2011-02-07 10:33:21 +00005285
5286 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005287}
5288
Douglas Gregora9d84932011-05-27 01:19:52 +00005289bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005290 std::string& S) {
5291 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005292 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005293 CharUnits ParmOffset;
5294 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005295 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005296 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005297 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005298 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005299 continue;
5300
David Chisnall50e4eba2010-12-30 14:05:53 +00005301 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005302 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005303 ParmOffset += sz;
5304 }
5305 S += charUnitsToString(ParmOffset);
5306 ParmOffset = CharUnits::Zero();
5307
5308 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005309 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005310 QualType PType = PVDecl->getOriginalType();
5311 if (const ArrayType *AT =
5312 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5313 // Use array's original type only if it has known number of
5314 // elements.
5315 if (!isa<ConstantArrayType>(AT))
5316 PType = PVDecl->getType();
5317 } else if (PType->isFunctionType())
5318 PType = PVDecl->getType();
5319 getObjCEncodingForType(PType, S);
5320 S += charUnitsToString(ParmOffset);
5321 ParmOffset += getObjCEncodingTypeSize(PType);
5322 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005323
5324 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005325}
5326
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005327/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5328/// method parameter or return type. If Extended, include class names and
5329/// block object types.
5330void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5331 QualType T, std::string& S,
5332 bool Extended) const {
5333 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5334 getObjCEncodingForTypeQualifier(QT, S);
5335 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005336 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005337 true /*OutermostType*/,
5338 false /*EncodingProperty*/,
5339 false /*StructField*/,
5340 Extended /*EncodeBlockParameters*/,
5341 Extended /*EncodeClassNames*/);
5342}
5343
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005344/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005345/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005346bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005347 std::string& S,
5348 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005349 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005350 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005351 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5352 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005353 // Compute size of all parameters.
5354 // Start with computing size of a pointer in number of bytes.
5355 // FIXME: There might(should) be a better way of doing this computation!
5356 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005357 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005358 // The first two arguments (self and _cmd) are pointers; account for
5359 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005360 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005361 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005362 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005363 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005364 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005365 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005366 continue;
5367
Ken Dyck40775002010-01-11 17:06:35 +00005368 assert (sz.isPositive() &&
5369 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005370 ParmOffset += sz;
5371 }
Ken Dyck40775002010-01-11 17:06:35 +00005372 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005373 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005374 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005375
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005376 // Argument types.
5377 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005378 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005379 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005380 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005381 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005382 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005383 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5384 // Use array's original type only if it has known number of
5385 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005386 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005387 PType = PVDecl->getType();
5388 } else if (PType->isFunctionType())
5389 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005390 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5391 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005392 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005393 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005394 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005395
5396 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005397}
5398
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005399ObjCPropertyImplDecl *
5400ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5401 const ObjCPropertyDecl *PD,
5402 const Decl *Container) const {
5403 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005404 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005405 if (const ObjCCategoryImplDecl *CID =
5406 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005407 for (auto *PID : CID->property_impls())
5408 if (PID->getPropertyDecl() == PD)
5409 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005410 } else {
5411 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5412 for (auto *PID : OID->property_impls())
5413 if (PID->getPropertyDecl() == PD)
5414 return PID;
5415 }
5416 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005417}
5418
Daniel Dunbar4932b362008-08-28 04:38:10 +00005419/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005420/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005421/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5422/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005423/// Property attributes are stored as a comma-delimited C string. The simple
5424/// attributes readonly and bycopy are encoded as single characters. The
5425/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5426/// encoded as single characters, followed by an identifier. Property types
5427/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005428/// these attributes are defined by the following enumeration:
5429/// @code
5430/// enum PropertyAttributes {
5431/// kPropertyReadOnly = 'R', // property is read-only.
5432/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5433/// kPropertyByref = '&', // property is a reference to the value last assigned
5434/// kPropertyDynamic = 'D', // property is dynamic
5435/// kPropertyGetter = 'G', // followed by getter selector name
5436/// kPropertySetter = 'S', // followed by setter selector name
5437/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005438/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005439/// kPropertyWeak = 'W' // 'weak' property
5440/// kPropertyStrong = 'P' // property GC'able
5441/// kPropertyNonAtomic = 'N' // property non-atomic
5442/// };
5443/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005444void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005445 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005446 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005447 // Collect information from the property implementation decl(s).
5448 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005449 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005450
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005451 if (ObjCPropertyImplDecl *PropertyImpDecl =
5452 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5453 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5454 Dynamic = true;
5455 else
5456 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005457 }
5458
5459 // FIXME: This is not very efficient.
5460 S = "T";
5461
5462 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005463 // GCC has some special rules regarding encoding of properties which
5464 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005465 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005466
5467 if (PD->isReadOnly()) {
5468 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005469 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5470 S += ",C";
5471 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5472 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005473 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5474 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005475 } else {
5476 switch (PD->getSetterKind()) {
5477 case ObjCPropertyDecl::Assign: break;
5478 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005479 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005480 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005481 }
5482 }
5483
5484 // It really isn't clear at all what this means, since properties
5485 // are "dynamic by default".
5486 if (Dynamic)
5487 S += ",D";
5488
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005489 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5490 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005491
Daniel Dunbar4932b362008-08-28 04:38:10 +00005492 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5493 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005494 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005495 }
5496
5497 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5498 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005499 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005500 }
5501
5502 if (SynthesizePID) {
5503 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5504 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005505 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005506 }
5507
5508 // FIXME: OBJCGC: weak & strong
5509}
5510
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005511/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005512/// Another legacy compatibility encoding: 32-bit longs are encoded as
5513/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005514/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5515///
5516void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005517 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005518 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005519 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005520 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005521 else
Jay Foad39c79802011-01-12 09:06:06 +00005522 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005523 PointeeTy = IntTy;
5524 }
5525 }
5526}
5527
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005528void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005529 const FieldDecl *Field,
5530 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005531 // We follow the behavior of gcc, expanding structures which are
5532 // directly pointed to, and expanding embedded structures. Note that
5533 // these rules are sufficient to prevent recursive encoding of the
5534 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005535 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005536 true /* outermost type */, false, false,
5537 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005538}
5539
Joe Groff98ac7d22014-07-07 22:25:15 +00005540void ASTContext::getObjCEncodingForPropertyType(QualType T,
5541 std::string& S) const {
5542 // Encode result type.
5543 // GCC has some special rules regarding encoding of properties which
5544 // closely resembles encoding of ivars.
5545 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5546 true /* outermost type */,
5547 true /* encoding property */);
5548}
5549
John McCall393a78d2012-12-20 02:45:14 +00005550static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5551 BuiltinType::Kind kind) {
5552 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005553 case BuiltinType::Void: return 'v';
5554 case BuiltinType::Bool: return 'B';
5555 case BuiltinType::Char_U:
5556 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005557 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005558 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005559 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005560 case BuiltinType::UInt: return 'I';
5561 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005562 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005563 case BuiltinType::UInt128: return 'T';
5564 case BuiltinType::ULongLong: return 'Q';
5565 case BuiltinType::Char_S:
5566 case BuiltinType::SChar: return 'c';
5567 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005568 case BuiltinType::WChar_S:
5569 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005570 case BuiltinType::Int: return 'i';
5571 case BuiltinType::Long:
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::LongLong: return 'q';
5574 case BuiltinType::Int128: return 't';
5575 case BuiltinType::Float: return 'f';
5576 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005577 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005578 case BuiltinType::NullPtr: return '*'; // like char*
5579
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005580 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005581 case BuiltinType::Half:
5582 // FIXME: potentially need @encodes for these!
5583 return ' ';
5584
5585 case BuiltinType::ObjCId:
5586 case BuiltinType::ObjCClass:
5587 case BuiltinType::ObjCSel:
5588 llvm_unreachable("@encoding ObjC primitive type");
5589
5590 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005591#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5592 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005593#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005594 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005595 case BuiltinType::OCLClkEvent:
5596 case BuiltinType::OCLQueue:
5597 case BuiltinType::OCLNDRange:
5598 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005599 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005600 case BuiltinType::Dependent:
5601#define BUILTIN_TYPE(KIND, ID)
5602#define PLACEHOLDER_TYPE(KIND, ID) \
5603 case BuiltinType::KIND:
5604#include "clang/AST/BuiltinTypes.def"
5605 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005606 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005607 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005608}
5609
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005610static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5611 EnumDecl *Enum = ET->getDecl();
5612
5613 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5614 if (!Enum->isFixed())
5615 return 'i';
5616
5617 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005618 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5619 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005620}
5621
Jay Foad39c79802011-01-12 09:06:06 +00005622static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005623 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005624 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005625 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005626 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5627 // The GNU runtime requires more information; bitfields are encoded as b,
5628 // then the offset (in bits) of the first element, then the type of the
5629 // bitfield, then the size in bits. For example, in this structure:
5630 //
5631 // struct
5632 // {
5633 // int integer;
5634 // int flags:2;
5635 // };
5636 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5637 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5638 // information is not especially sensible, but we're stuck with it for
5639 // compatibility with GCC, although providing it breaks anything that
5640 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005641 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005642 const RecordDecl *RD = FD->getParent();
5643 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005644 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005645 if (const EnumType *ET = T->getAs<EnumType>())
5646 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005647 else {
5648 const BuiltinType *BT = T->castAs<BuiltinType>();
5649 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5650 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005651 }
Richard Smithcaf33902011-10-10 18:28:20 +00005652 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005653}
5654
Daniel Dunbar07d07852009-10-18 21:17:35 +00005655// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005656void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5657 bool ExpandPointedToStructures,
5658 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005659 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005660 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005661 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005662 bool StructField,
5663 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005664 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005665 bool EncodePointerToObjCTypedef,
5666 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005667 CanQualType CT = getCanonicalType(T);
5668 switch (CT->getTypeClass()) {
5669 case Type::Builtin:
5670 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005671 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005672 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005673 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5674 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5675 else
5676 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005677 return;
Mike Stump11289f42009-09-09 15:08:12 +00005678
John McCall393a78d2012-12-20 02:45:14 +00005679 case Type::Complex: {
5680 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005681 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005682 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005683 return;
5684 }
John McCall393a78d2012-12-20 02:45:14 +00005685
5686 case Type::Atomic: {
5687 const AtomicType *AT = T->castAs<AtomicType>();
5688 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005689 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005690 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005691 }
John McCall393a78d2012-12-20 02:45:14 +00005692
5693 // encoding for pointer or reference types.
5694 case Type::Pointer:
5695 case Type::LValueReference:
5696 case Type::RValueReference: {
5697 QualType PointeeTy;
5698 if (isa<PointerType>(CT)) {
5699 const PointerType *PT = T->castAs<PointerType>();
5700 if (PT->isObjCSelType()) {
5701 S += ':';
5702 return;
5703 }
5704 PointeeTy = PT->getPointeeType();
5705 } else {
5706 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5707 }
5708
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005709 bool isReadOnly = false;
5710 // For historical/compatibility reasons, the read-only qualifier of the
5711 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5712 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005713 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005714 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005715 if (OutermostType && T.isConstQualified()) {
5716 isReadOnly = true;
5717 S += 'r';
5718 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005719 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005720 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005721 while (P->getAs<PointerType>())
5722 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005723 if (P.isConstQualified()) {
5724 isReadOnly = true;
5725 S += 'r';
5726 }
5727 }
5728 if (isReadOnly) {
5729 // Another legacy compatibility encoding. Some ObjC qualifier and type
5730 // combinations need to be rearranged.
5731 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005732 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005733 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005734 }
Mike Stump11289f42009-09-09 15:08:12 +00005735
Anders Carlssond8499822007-10-29 05:01:08 +00005736 if (PointeeTy->isCharType()) {
5737 // char pointer types should be encoded as '*' unless it is a
5738 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005739 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005740 S += '*';
5741 return;
5742 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005743 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005744 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5745 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5746 S += '#';
5747 return;
5748 }
5749 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5750 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5751 S += '@';
5752 return;
5753 }
5754 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005755 }
Anders Carlssond8499822007-10-29 05:01:08 +00005756 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005757 getLegacyIntegralTypeEncoding(PointeeTy);
5758
Mike Stump11289f42009-09-09 15:08:12 +00005759 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005760 nullptr, false, false, false, false, false, false,
5761 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005762 return;
5763 }
John McCall393a78d2012-12-20 02:45:14 +00005764
5765 case Type::ConstantArray:
5766 case Type::IncompleteArray:
5767 case Type::VariableArray: {
5768 const ArrayType *AT = cast<ArrayType>(CT);
5769
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005770 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005771 // Incomplete arrays are encoded as a pointer to the array element.
5772 S += '^';
5773
Mike Stump11289f42009-09-09 15:08:12 +00005774 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005775 false, ExpandStructures, FD);
5776 } else {
5777 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005778
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005779 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5780 S += llvm::utostr(CAT->getSize().getZExtValue());
5781 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005782 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005783 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5784 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005785 S += '0';
5786 }
Mike Stump11289f42009-09-09 15:08:12 +00005787
5788 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005789 false, ExpandStructures, FD,
5790 false, false, false, false, false, false,
5791 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005792 S += ']';
5793 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005794 return;
5795 }
Mike Stump11289f42009-09-09 15:08:12 +00005796
John McCall393a78d2012-12-20 02:45:14 +00005797 case Type::FunctionNoProto:
5798 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005799 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005800 return;
Mike Stump11289f42009-09-09 15:08:12 +00005801
John McCall393a78d2012-12-20 02:45:14 +00005802 case Type::Record: {
5803 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005804 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005805 // Anonymous structures print as '?'
5806 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5807 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005808 if (ClassTemplateSpecializationDecl *Spec
5809 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5810 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005811 llvm::raw_string_ostream OS(S);
5812 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00005813 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005814 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005815 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005816 } else {
5817 S += '?';
5818 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005819 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005820 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005821 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005822 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005823 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005824 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005825 if (FD) {
5826 S += '"';
5827 S += Field->getNameAsString();
5828 S += '"';
5829 }
Mike Stump11289f42009-09-09 15:08:12 +00005830
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005831 // Special case bit-fields.
5832 if (Field->isBitField()) {
5833 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005834 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005835 } else {
5836 QualType qt = Field->getType();
5837 getLegacyIntegralTypeEncoding(qt);
5838 getObjCEncodingForTypeImpl(qt, S, false, true,
5839 FD, /*OutermostType*/false,
5840 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005841 /*StructField*/true,
5842 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005843 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005844 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005845 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005846 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005847 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005848 return;
5849 }
Mike Stump11289f42009-09-09 15:08:12 +00005850
John McCall393a78d2012-12-20 02:45:14 +00005851 case Type::BlockPointer: {
5852 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005853 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005854 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005855 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005856
5857 S += '<';
5858 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005859 getObjCEncodingForTypeImpl(
5860 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5861 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005862 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5863 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005864 // Block self
5865 S += "@?";
5866 // Block parameters
5867 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005868 for (const auto &I : FPT->param_types())
5869 getObjCEncodingForTypeImpl(
5870 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5871 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005872 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5873 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005874 }
5875 S += '>';
5876 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005877 return;
5878 }
Mike Stump11289f42009-09-09 15:08:12 +00005879
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005880 case Type::ObjCObject: {
5881 // hack to match legacy encoding of *id and *Class
5882 QualType Ty = getObjCObjectPointerType(CT);
5883 if (Ty->isObjCIdType()) {
5884 S += "{objc_object=}";
5885 return;
5886 }
5887 else if (Ty->isObjCClassType()) {
5888 S += "{objc_class=}";
5889 return;
5890 }
5891 }
5892
John McCall393a78d2012-12-20 02:45:14 +00005893 case Type::ObjCInterface: {
5894 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005895 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005896 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005897 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005898 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005899 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005900 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005901 DeepCollectObjCIvars(OI, true, Ivars);
5902 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005903 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005904 if (Field->isBitField())
5905 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005906 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005907 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5908 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005909 EncodePointerToObjCTypedef,
5910 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005911 }
5912 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005913 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005914 }
Mike Stump11289f42009-09-09 15:08:12 +00005915
John McCall393a78d2012-12-20 02:45:14 +00005916 case Type::ObjCObjectPointer: {
5917 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005918 if (OPT->isObjCIdType()) {
5919 S += '@';
5920 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005921 }
Mike Stump11289f42009-09-09 15:08:12 +00005922
Steve Narofff0c86112009-10-28 22:03:49 +00005923 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5924 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5925 // Since this is a binary compatibility issue, need to consult with runtime
5926 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005927 S += '#';
5928 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005929 }
Mike Stump11289f42009-09-09 15:08:12 +00005930
Chris Lattnere7cabb92009-07-13 00:10:46 +00005931 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005932 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005933 ExpandPointedToStructures,
5934 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005935 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005936 // Note that we do extended encoding of protocol qualifer list
5937 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005938 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005939 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005940 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005941 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005942 S += '>';
5943 }
5944 S += '"';
5945 }
5946 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005947 }
Mike Stump11289f42009-09-09 15:08:12 +00005948
Chris Lattnere7cabb92009-07-13 00:10:46 +00005949 QualType PointeeTy = OPT->getPointeeType();
5950 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005951 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5952 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005953 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005954 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005955 // {...};
5956 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005957 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005958 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005959 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5960 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5961 DeepCollectObjCIvars(OI, true, Ivars);
5962 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5963 if (cast<FieldDecl>(Ivars[i]) == FD) {
5964 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005965 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005966 S += '}';
5967 return;
5968 }
5969 }
5970 }
Mike Stump11289f42009-09-09 15:08:12 +00005971 getObjCEncodingForTypeImpl(PointeeTy, S,
5972 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005973 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005974 false, false, false, false, false,
5975 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005976 return;
5977 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005978
5979 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005980 if (OPT->getInterfaceDecl() &&
5981 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005982 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005983 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005984 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005985 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005986 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005987 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005988 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005989 S += '"';
5990 }
5991 return;
5992 }
Mike Stump11289f42009-09-09 15:08:12 +00005993
John McCalla9e6e8d2010-05-17 23:56:34 +00005994 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005995 // FIXME: we shoul do better than that. 'M' is available.
5996 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005997 // This matches gcc's encoding, even though technically it is insufficient.
5998 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005999 case Type::Vector:
6000 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006001 // Until we have a coherent encoding of these three types, issue warning.
6002 { if (NotEncodedT)
6003 *NotEncodedT = T;
6004 return;
6005 }
6006
6007 // We could see an undeduced auto type here during error recovery.
6008 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006009 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00006010 return;
6011
Xiuli Pan9c14e282016-01-09 12:53:17 +00006012 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006013#define ABSTRACT_TYPE(KIND, BASE)
6014#define TYPE(KIND, BASE)
6015#define DEPENDENT_TYPE(KIND, BASE) \
6016 case Type::KIND:
6017#define NON_CANONICAL_TYPE(KIND, BASE) \
6018 case Type::KIND:
6019#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6020 case Type::KIND:
6021#include "clang/AST/TypeNodes.def"
6022 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006023 }
John McCall393a78d2012-12-20 02:45:14 +00006024 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006025}
6026
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006027void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6028 std::string &S,
6029 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006030 bool includeVBases,
6031 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006032 assert(RDecl && "Expected non-null RecordDecl");
6033 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006034 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006035 return;
6036
6037 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6038 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6039 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6040
6041 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006042 for (const auto &BI : CXXRec->bases()) {
6043 if (!BI.isVirtual()) {
6044 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006045 if (base->isEmpty())
6046 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006047 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006048 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6049 std::make_pair(offs, base));
6050 }
6051 }
6052 }
6053
6054 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006055 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006056 uint64_t offs = layout.getFieldOffset(i);
6057 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006058 std::make_pair(offs, Field));
6059 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006060 }
6061
6062 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006063 for (const auto &BI : CXXRec->vbases()) {
6064 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006065 if (base->isEmpty())
6066 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006067 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006068 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6069 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006070 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6071 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006072 }
6073 }
6074
6075 CharUnits size;
6076 if (CXXRec) {
6077 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6078 } else {
6079 size = layout.getSize();
6080 }
6081
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006082#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006083 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006084#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006085 std::multimap<uint64_t, NamedDecl *>::iterator
6086 CurLayObj = FieldOrBaseOffsets.begin();
6087
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006088 if (CXXRec && CXXRec->isDynamicClass() &&
6089 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006090 if (FD) {
6091 S += "\"_vptr$";
6092 std::string recname = CXXRec->getNameAsString();
6093 if (recname.empty()) recname = "?";
6094 S += recname;
6095 S += '"';
6096 }
6097 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006098#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006099 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006100#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006101 }
6102
6103 if (!RDecl->hasFlexibleArrayMember()) {
6104 // Mark the end of the structure.
6105 uint64_t offs = toBits(size);
6106 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006107 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006108 }
6109
6110 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006111#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006112 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006113 if (CurOffs < CurLayObj->first) {
6114 uint64_t padding = CurLayObj->first - CurOffs;
6115 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6116 // packing/alignment of members is different that normal, in which case
6117 // the encoding will be out-of-sync with the real layout.
6118 // If the runtime switches to just consider the size of types without
6119 // taking into account alignment, we could make padding explicit in the
6120 // encoding (e.g. using arrays of chars). The encoding strings would be
6121 // longer then though.
6122 CurOffs += padding;
6123 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006124#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006125
6126 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006127 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006128 break; // reached end of structure.
6129
6130 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6131 // We expand the bases without their virtual bases since those are going
6132 // in the initial structure. Note that this differs from gcc which
6133 // expands virtual bases each time one is encountered in the hierarchy,
6134 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006135 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6136 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006137 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006138#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006139 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006140#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006141 } else {
6142 FieldDecl *field = cast<FieldDecl>(dcl);
6143 if (FD) {
6144 S += '"';
6145 S += field->getNameAsString();
6146 S += '"';
6147 }
6148
6149 if (field->isBitField()) {
6150 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006151#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006152 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006153#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006154 } else {
6155 QualType qt = field->getType();
6156 getLegacyIntegralTypeEncoding(qt);
6157 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6158 /*OutermostType*/false,
6159 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006160 /*StructField*/true,
6161 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006162#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006163 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006164#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006165 }
6166 }
6167 }
6168}
6169
Mike Stump11289f42009-09-09 15:08:12 +00006170void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006171 std::string& S) const {
6172 if (QT & Decl::OBJC_TQ_In)
6173 S += 'n';
6174 if (QT & Decl::OBJC_TQ_Inout)
6175 S += 'N';
6176 if (QT & Decl::OBJC_TQ_Out)
6177 S += 'o';
6178 if (QT & Decl::OBJC_TQ_Bycopy)
6179 S += 'O';
6180 if (QT & Decl::OBJC_TQ_Byref)
6181 S += 'R';
6182 if (QT & Decl::OBJC_TQ_Oneway)
6183 S += 'V';
6184}
6185
Douglas Gregor3ea72692011-08-12 05:46:01 +00006186TypedefDecl *ASTContext::getObjCIdDecl() const {
6187 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006188 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006189 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006190 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006191 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006192 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006193}
6194
Douglas Gregor52e02802011-08-12 06:17:30 +00006195TypedefDecl *ASTContext::getObjCSelDecl() const {
6196 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006197 QualType T = getPointerType(ObjCBuiltinSelTy);
6198 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006199 }
6200 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006201}
6202
Douglas Gregor0a586182011-08-12 05:59:41 +00006203TypedefDecl *ASTContext::getObjCClassDecl() const {
6204 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006205 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006206 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006207 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006208 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006209 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006210}
6211
Douglas Gregord53ae832012-01-17 18:09:05 +00006212ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6213 if (!ObjCProtocolClassDecl) {
6214 ObjCProtocolClassDecl
6215 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6216 SourceLocation(),
6217 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006218 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006219 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006220 SourceLocation(), true);
6221 }
6222
6223 return ObjCProtocolClassDecl;
6224}
6225
Meador Inge5d3fb222012-06-16 03:34:49 +00006226//===----------------------------------------------------------------------===//
6227// __builtin_va_list Construction Functions
6228//===----------------------------------------------------------------------===//
6229
Charles Davisc7d5c942015-09-17 20:55:33 +00006230static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6231 StringRef Name) {
6232 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006233 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006234 return Context->buildImplicitTypedef(T, Name);
6235}
6236
6237static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6238 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6239}
6240
6241static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6242 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006243}
6244
6245static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6246 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006247 QualType T = Context->getPointerType(Context->VoidTy);
6248 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006249}
6250
Tim Northover9bb857a2013-01-31 12:13:10 +00006251static TypedefDecl *
6252CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006253 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006254 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006255 if (Context->getLangOpts().CPlusPlus) {
6256 // namespace std { struct __va_list {
6257 NamespaceDecl *NS;
6258 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6259 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006260 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006261 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006262 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006263 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006264 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006265 }
6266
6267 VaListTagDecl->startDefinition();
6268
6269 const size_t NumFields = 5;
6270 QualType FieldTypes[NumFields];
6271 const char *FieldNames[NumFields];
6272
6273 // void *__stack;
6274 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6275 FieldNames[0] = "__stack";
6276
6277 // void *__gr_top;
6278 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6279 FieldNames[1] = "__gr_top";
6280
6281 // void *__vr_top;
6282 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6283 FieldNames[2] = "__vr_top";
6284
6285 // int __gr_offs;
6286 FieldTypes[3] = Context->IntTy;
6287 FieldNames[3] = "__gr_offs";
6288
6289 // int __vr_offs;
6290 FieldTypes[4] = Context->IntTy;
6291 FieldNames[4] = "__vr_offs";
6292
6293 // Create fields
6294 for (unsigned i = 0; i < NumFields; ++i) {
6295 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6296 VaListTagDecl,
6297 SourceLocation(),
6298 SourceLocation(),
6299 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006300 FieldTypes[i], /*TInfo=*/nullptr,
6301 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006302 /*Mutable=*/false,
6303 ICIS_NoInit);
6304 Field->setAccess(AS_public);
6305 VaListTagDecl->addDecl(Field);
6306 }
6307 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006308 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006309 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006310
6311 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006312 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006313}
6314
Meador Inge5d3fb222012-06-16 03:34:49 +00006315static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6316 // typedef struct __va_list_tag {
6317 RecordDecl *VaListTagDecl;
6318
Alp Toker2dea15b2013-12-17 01:22:38 +00006319 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006320 VaListTagDecl->startDefinition();
6321
6322 const size_t NumFields = 5;
6323 QualType FieldTypes[NumFields];
6324 const char *FieldNames[NumFields];
6325
6326 // unsigned char gpr;
6327 FieldTypes[0] = Context->UnsignedCharTy;
6328 FieldNames[0] = "gpr";
6329
6330 // unsigned char fpr;
6331 FieldTypes[1] = Context->UnsignedCharTy;
6332 FieldNames[1] = "fpr";
6333
6334 // unsigned short reserved;
6335 FieldTypes[2] = Context->UnsignedShortTy;
6336 FieldNames[2] = "reserved";
6337
6338 // void* overflow_arg_area;
6339 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6340 FieldNames[3] = "overflow_arg_area";
6341
6342 // void* reg_save_area;
6343 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6344 FieldNames[4] = "reg_save_area";
6345
6346 // Create fields
6347 for (unsigned i = 0; i < NumFields; ++i) {
6348 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6349 SourceLocation(),
6350 SourceLocation(),
6351 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006352 FieldTypes[i], /*TInfo=*/nullptr,
6353 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006354 /*Mutable=*/false,
6355 ICIS_NoInit);
6356 Field->setAccess(AS_public);
6357 VaListTagDecl->addDecl(Field);
6358 }
6359 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006360 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006361 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6362
6363 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006364 TypedefDecl *VaListTagTypedefDecl =
6365 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6366
Meador Inge5d3fb222012-06-16 03:34:49 +00006367 QualType VaListTagTypedefType =
6368 Context->getTypedefType(VaListTagTypedefDecl);
6369
6370 // typedef __va_list_tag __builtin_va_list[1];
6371 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6372 QualType VaListTagArrayType
6373 = Context->getConstantArrayType(VaListTagTypedefType,
6374 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006375 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006376}
6377
6378static TypedefDecl *
6379CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006380 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006381 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006382 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006383 VaListTagDecl->startDefinition();
6384
6385 const size_t NumFields = 4;
6386 QualType FieldTypes[NumFields];
6387 const char *FieldNames[NumFields];
6388
6389 // unsigned gp_offset;
6390 FieldTypes[0] = Context->UnsignedIntTy;
6391 FieldNames[0] = "gp_offset";
6392
6393 // unsigned fp_offset;
6394 FieldTypes[1] = Context->UnsignedIntTy;
6395 FieldNames[1] = "fp_offset";
6396
6397 // void* overflow_arg_area;
6398 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6399 FieldNames[2] = "overflow_arg_area";
6400
6401 // void* reg_save_area;
6402 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6403 FieldNames[3] = "reg_save_area";
6404
6405 // Create fields
6406 for (unsigned i = 0; i < NumFields; ++i) {
6407 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6408 VaListTagDecl,
6409 SourceLocation(),
6410 SourceLocation(),
6411 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006412 FieldTypes[i], /*TInfo=*/nullptr,
6413 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006414 /*Mutable=*/false,
6415 ICIS_NoInit);
6416 Field->setAccess(AS_public);
6417 VaListTagDecl->addDecl(Field);
6418 }
6419 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006420 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006421 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6422
Richard Smith9b88a4c2015-07-27 05:40:23 +00006423 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006424
Richard Smith9b88a4c2015-07-27 05:40:23 +00006425 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006426 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006427 QualType VaListTagArrayType =
6428 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006429 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006430}
6431
6432static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6433 // typedef int __builtin_va_list[4];
6434 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6435 QualType IntArrayType
6436 = Context->getConstantArrayType(Context->IntTy,
6437 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006438 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006439}
6440
Logan Chien57086ce2012-10-10 06:56:20 +00006441static TypedefDecl *
6442CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006443 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006444 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006445 if (Context->getLangOpts().CPlusPlus) {
6446 // namespace std { struct __va_list {
6447 NamespaceDecl *NS;
6448 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6449 Context->getTranslationUnitDecl(),
6450 /*Inline*/false, SourceLocation(),
6451 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006452 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006453 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006454 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006455 }
6456
6457 VaListDecl->startDefinition();
6458
6459 // void * __ap;
6460 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6461 VaListDecl,
6462 SourceLocation(),
6463 SourceLocation(),
6464 &Context->Idents.get("__ap"),
6465 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006466 /*TInfo=*/nullptr,
6467 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006468 /*Mutable=*/false,
6469 ICIS_NoInit);
6470 Field->setAccess(AS_public);
6471 VaListDecl->addDecl(Field);
6472
6473 // };
6474 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006475 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006476
6477 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006478 QualType T = Context->getRecordType(VaListDecl);
6479 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006480}
6481
Ulrich Weigand47445072013-05-06 16:26:41 +00006482static TypedefDecl *
6483CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006484 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006485 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006486 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006487 VaListTagDecl->startDefinition();
6488
6489 const size_t NumFields = 4;
6490 QualType FieldTypes[NumFields];
6491 const char *FieldNames[NumFields];
6492
6493 // long __gpr;
6494 FieldTypes[0] = Context->LongTy;
6495 FieldNames[0] = "__gpr";
6496
6497 // long __fpr;
6498 FieldTypes[1] = Context->LongTy;
6499 FieldNames[1] = "__fpr";
6500
6501 // void *__overflow_arg_area;
6502 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6503 FieldNames[2] = "__overflow_arg_area";
6504
6505 // void *__reg_save_area;
6506 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6507 FieldNames[3] = "__reg_save_area";
6508
6509 // Create fields
6510 for (unsigned i = 0; i < NumFields; ++i) {
6511 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6512 VaListTagDecl,
6513 SourceLocation(),
6514 SourceLocation(),
6515 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006516 FieldTypes[i], /*TInfo=*/nullptr,
6517 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006518 /*Mutable=*/false,
6519 ICIS_NoInit);
6520 Field->setAccess(AS_public);
6521 VaListTagDecl->addDecl(Field);
6522 }
6523 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006524 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006525 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006526
Richard Smith9b88a4c2015-07-27 05:40:23 +00006527 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006528
6529 // typedef __va_list_tag __builtin_va_list[1];
6530 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006531 QualType VaListTagArrayType =
6532 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006533
Alp Toker56b5cc92013-12-15 10:36:26 +00006534 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006535}
6536
Meador Inge5d3fb222012-06-16 03:34:49 +00006537static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6538 TargetInfo::BuiltinVaListKind Kind) {
6539 switch (Kind) {
6540 case TargetInfo::CharPtrBuiltinVaList:
6541 return CreateCharPtrBuiltinVaListDecl(Context);
6542 case TargetInfo::VoidPtrBuiltinVaList:
6543 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006544 case TargetInfo::AArch64ABIBuiltinVaList:
6545 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006546 case TargetInfo::PowerABIBuiltinVaList:
6547 return CreatePowerABIBuiltinVaListDecl(Context);
6548 case TargetInfo::X86_64ABIBuiltinVaList:
6549 return CreateX86_64ABIBuiltinVaListDecl(Context);
6550 case TargetInfo::PNaClABIBuiltinVaList:
6551 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006552 case TargetInfo::AAPCSABIBuiltinVaList:
6553 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006554 case TargetInfo::SystemZBuiltinVaList:
6555 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006556 }
6557
6558 llvm_unreachable("Unhandled __builtin_va_list type kind");
6559}
6560
6561TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006562 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006563 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006564 assert(BuiltinVaListDecl->isImplicit());
6565 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006566
6567 return BuiltinVaListDecl;
6568}
6569
Richard Smith9b88a4c2015-07-27 05:40:23 +00006570Decl *ASTContext::getVaListTagDecl() const {
6571 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006572 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006573 if (!VaListTagDecl)
6574 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006575
Richard Smith9b88a4c2015-07-27 05:40:23 +00006576 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006577}
6578
Charles Davisc7d5c942015-09-17 20:55:33 +00006579TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6580 if (!BuiltinMSVaListDecl)
6581 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6582
6583 return BuiltinMSVaListDecl;
6584}
6585
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006586void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006587 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006588 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006589
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006590 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006591}
6592
John McCalld28ae272009-12-02 08:04:21 +00006593/// \brief Retrieve the template name that corresponds to a non-empty
6594/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006595TemplateName
6596ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6597 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006598 unsigned size = End - Begin;
6599 assert(size > 1 && "set is not overloaded!");
6600
6601 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6602 size * sizeof(FunctionTemplateDecl*));
6603 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6604
6605 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006606 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006607 NamedDecl *D = *I;
6608 assert(isa<FunctionTemplateDecl>(D) ||
6609 (isa<UsingShadowDecl>(D) &&
6610 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6611 *Storage++ = D;
6612 }
6613
6614 return TemplateName(OT);
6615}
6616
Douglas Gregordc572a32009-03-30 22:58:21 +00006617/// \brief Retrieve the template name that represents a qualified
6618/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006619TemplateName
6620ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6621 bool TemplateKeyword,
6622 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006623 assert(NNS && "Missing nested-name-specifier in qualified template name");
6624
Douglas Gregorc42075a2010-02-04 18:10:26 +00006625 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006626 llvm::FoldingSetNodeID ID;
6627 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6628
Craig Topper36250ad2014-05-12 05:36:57 +00006629 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006630 QualifiedTemplateName *QTN =
6631 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6632 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006633 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6634 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006635 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6636 }
6637
6638 return TemplateName(QTN);
6639}
6640
6641/// \brief Retrieve the template name that represents a dependent
6642/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006643TemplateName
6644ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6645 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006646 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006647 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006648
6649 llvm::FoldingSetNodeID ID;
6650 DependentTemplateName::Profile(ID, NNS, Name);
6651
Craig Topper36250ad2014-05-12 05:36:57 +00006652 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006653 DependentTemplateName *QTN =
6654 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6655
6656 if (QTN)
6657 return TemplateName(QTN);
6658
6659 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6660 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006661 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6662 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006663 } else {
6664 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006665 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6666 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006667 DependentTemplateName *CheckQTN =
6668 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6669 assert(!CheckQTN && "Dependent type name canonicalization broken");
6670 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006671 }
6672
6673 DependentTemplateNames.InsertNode(QTN, InsertPos);
6674 return TemplateName(QTN);
6675}
6676
Douglas Gregor71395fa2009-11-04 00:56:37 +00006677/// \brief Retrieve the template name that represents a dependent
6678/// template name such as \c MetaFun::template operator+.
6679TemplateName
6680ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006681 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006682 assert((!NNS || NNS->isDependent()) &&
6683 "Nested name specifier must be dependent");
6684
6685 llvm::FoldingSetNodeID ID;
6686 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006687
6688 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006689 DependentTemplateName *QTN
6690 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006691
6692 if (QTN)
6693 return TemplateName(QTN);
6694
6695 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6696 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006697 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6698 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006699 } else {
6700 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006701 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6702 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006703
6704 DependentTemplateName *CheckQTN
6705 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6706 assert(!CheckQTN && "Dependent template name canonicalization broken");
6707 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006708 }
6709
6710 DependentTemplateNames.InsertNode(QTN, InsertPos);
6711 return TemplateName(QTN);
6712}
6713
Douglas Gregor5590be02011-01-15 06:45:20 +00006714TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006715ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6716 TemplateName replacement) const {
6717 llvm::FoldingSetNodeID ID;
6718 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006719
6720 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006721 SubstTemplateTemplateParmStorage *subst
6722 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6723
6724 if (!subst) {
6725 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6726 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6727 }
6728
6729 return TemplateName(subst);
6730}
6731
6732TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006733ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6734 const TemplateArgument &ArgPack) const {
6735 ASTContext &Self = const_cast<ASTContext &>(*this);
6736 llvm::FoldingSetNodeID ID;
6737 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006738
6739 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006740 SubstTemplateTemplateParmPackStorage *Subst
6741 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6742
6743 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006744 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006745 ArgPack.pack_size(),
6746 ArgPack.pack_begin());
6747 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6748 }
6749
6750 return TemplateName(Subst);
6751}
6752
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006753/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006754/// TargetInfo, produce the corresponding type. The unsigned @p Type
6755/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006756CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006757 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006758 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006759 case TargetInfo::SignedChar: return SignedCharTy;
6760 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006761 case TargetInfo::SignedShort: return ShortTy;
6762 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6763 case TargetInfo::SignedInt: return IntTy;
6764 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6765 case TargetInfo::SignedLong: return LongTy;
6766 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6767 case TargetInfo::SignedLongLong: return LongLongTy;
6768 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6769 }
6770
David Blaikie83d382b2011-09-23 05:06:16 +00006771 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006772}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006773
6774//===----------------------------------------------------------------------===//
6775// Type Predicates.
6776//===----------------------------------------------------------------------===//
6777
Fariborz Jahanian96207692009-02-18 21:49:28 +00006778/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6779/// garbage collection attribute.
6780///
John McCall553d45a2011-01-12 00:34:59 +00006781Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006782 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006783 return Qualifiers::GCNone;
6784
David Blaikiebbafb8a2012-03-11 07:00:24 +00006785 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006786 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6787
6788 // Default behaviour under objective-C's gc is for ObjC pointers
6789 // (or pointers to them) be treated as though they were declared
6790 // as __strong.
6791 if (GCAttrs == Qualifiers::GCNone) {
6792 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6793 return Qualifiers::Strong;
6794 else if (Ty->isPointerType())
6795 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6796 } else {
6797 // It's not valid to set GC attributes on anything that isn't a
6798 // pointer.
6799#ifndef NDEBUG
6800 QualType CT = Ty->getCanonicalTypeInternal();
6801 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6802 CT = AT->getElementType();
6803 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6804#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006805 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006806 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006807}
6808
Chris Lattner49af6a42008-04-07 06:51:04 +00006809//===----------------------------------------------------------------------===//
6810// Type Compatibility Testing
6811//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006812
Mike Stump11289f42009-09-09 15:08:12 +00006813/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006814/// compatible.
6815static bool areCompatVectorTypes(const VectorType *LHS,
6816 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006817 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006818 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006819 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006820}
6821
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006822bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6823 QualType SecondVec) {
6824 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6825 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6826
6827 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6828 return true;
6829
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006830 // Treat Neon vector types and most AltiVec vector types as if they are the
6831 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006832 const VectorType *First = FirstVec->getAs<VectorType>();
6833 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006834 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006835 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006836 First->getVectorKind() != VectorType::AltiVecPixel &&
6837 First->getVectorKind() != VectorType::AltiVecBool &&
6838 Second->getVectorKind() != VectorType::AltiVecPixel &&
6839 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006840 return true;
6841
6842 return false;
6843}
6844
Steve Naroff8e6aee52009-07-23 01:01:38 +00006845//===----------------------------------------------------------------------===//
6846// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6847//===----------------------------------------------------------------------===//
6848
6849/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6850/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006851bool
6852ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6853 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006854 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006855 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006856 for (auto *PI : rProto->protocols())
6857 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006858 return true;
6859 return false;
6860}
6861
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006862/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6863/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006864bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6865 QualType rhs) {
6866 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6867 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6868 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6869
Aaron Ballman83731462014-03-17 16:14:00 +00006870 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006871 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006872 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006873 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6874 match = true;
6875 break;
6876 }
6877 }
6878 if (!match)
6879 return false;
6880 }
6881 return true;
6882}
6883
Steve Naroff8e6aee52009-07-23 01:01:38 +00006884/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6885/// ObjCQualifiedIDType.
6886bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6887 bool compare) {
6888 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006889 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006890 lhs->isObjCIdType() || lhs->isObjCClassType())
6891 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006892 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006893 rhs->isObjCIdType() || rhs->isObjCClassType())
6894 return true;
6895
6896 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006897 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006898
Steve Naroff8e6aee52009-07-23 01:01:38 +00006899 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006900
Steve Naroff8e6aee52009-07-23 01:01:38 +00006901 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006902 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006903 // make sure we check the class hierarchy.
6904 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006905 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006906 // when comparing an id<P> on lhs with a static type on rhs,
6907 // see if static class implements all of id's protocols, directly or
6908 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006909 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006910 return false;
6911 }
6912 }
6913 // If there are no qualifiers and no interface, we have an 'id'.
6914 return true;
6915 }
Mike Stump11289f42009-09-09 15:08:12 +00006916 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006917 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006918 bool match = false;
6919
6920 // when comparing an id<P> on lhs with a static type on rhs,
6921 // see if static class implements all of id's protocols, directly or
6922 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006923 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006924 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6925 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6926 match = true;
6927 break;
6928 }
6929 }
Mike Stump11289f42009-09-09 15:08:12 +00006930 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006931 // make sure we check the class hierarchy.
6932 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006933 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006934 // when comparing an id<P> on lhs with a static type on rhs,
6935 // see if static class implements all of id's protocols, directly or
6936 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006937 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006938 match = true;
6939 break;
6940 }
6941 }
6942 }
6943 if (!match)
6944 return false;
6945 }
Mike Stump11289f42009-09-09 15:08:12 +00006946
Steve Naroff8e6aee52009-07-23 01:01:38 +00006947 return true;
6948 }
Mike Stump11289f42009-09-09 15:08:12 +00006949
Steve Naroff8e6aee52009-07-23 01:01:38 +00006950 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6951 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6952
Mike Stump11289f42009-09-09 15:08:12 +00006953 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006954 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006955 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006956 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006957 bool match = false;
6958
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006959 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006960 // see if static class implements all of id's protocols, directly or
6961 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006962 // First, lhs protocols in the qualifier list must be found, direct
6963 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006964 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006965 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6966 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6967 match = true;
6968 break;
6969 }
6970 }
6971 if (!match)
6972 return false;
6973 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006974
6975 // Static class's protocols, or its super class or category protocols
6976 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6977 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6978 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6979 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6980 // This is rather dubious but matches gcc's behavior. If lhs has
6981 // no type qualifier and its class has no static protocol(s)
6982 // assume that it is mismatch.
6983 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6984 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006985 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006986 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006987 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006988 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6989 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6990 match = true;
6991 break;
6992 }
6993 }
6994 if (!match)
6995 return false;
6996 }
6997 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006998 return true;
6999 }
7000 return false;
7001}
7002
Eli Friedman47f77112008-08-22 00:56:42 +00007003/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007004/// compatible for assignment from RHS to LHS. This handles validation of any
7005/// protocol qualifiers on the LHS or RHS.
7006///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007007bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7008 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007009 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7010 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7011
Steve Naroff1329fa02009-07-15 18:40:39 +00007012 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007013 if (LHS->isObjCUnqualifiedIdOrClass() ||
7014 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007015 return true;
7016
Douglas Gregorab209d82015-07-07 03:58:42 +00007017 // Function object that propagates a successful result or handles
7018 // __kindof types.
7019 auto finish = [&](bool succeeded) -> bool {
7020 if (succeeded)
7021 return true;
7022
7023 if (!RHS->isKindOfType())
7024 return false;
7025
7026 // Strip off __kindof and protocol qualifiers, then check whether
7027 // we can assign the other way.
7028 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7029 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7030 };
7031
7032 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7033 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7034 QualType(RHSOPT,0),
7035 false));
7036 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007037
Douglas Gregorab209d82015-07-07 03:58:42 +00007038 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7039 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7040 QualType(RHSOPT,0)));
7041 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007042
John McCall8b07ec22010-05-15 11:32:37 +00007043 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007044 if (LHS->getInterface() && RHS->getInterface()) {
7045 return finish(canAssignObjCInterfaces(LHS, RHS));
7046 }
Mike Stump11289f42009-09-09 15:08:12 +00007047
Steve Naroff8e6aee52009-07-23 01:01:38 +00007048 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007049}
7050
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007051/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007052/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007053/// arguments in block literals. When passed as arguments, passing 'A*' where
7054/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7055/// not OK. For the return type, the opposite is not OK.
7056bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7057 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007058 const ObjCObjectPointerType *RHSOPT,
7059 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007060
7061 // Function object that propagates a successful result or handles
7062 // __kindof types.
7063 auto finish = [&](bool succeeded) -> bool {
7064 if (succeeded)
7065 return true;
7066
7067 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7068 if (!Expected->isKindOfType())
7069 return false;
7070
7071 // Strip off __kindof and protocol qualifiers, then check whether
7072 // we can assign the other way.
7073 return canAssignObjCInterfacesInBlockPointer(
7074 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7075 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7076 BlockReturnType);
7077 };
7078
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007079 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007080 return true;
7081
7082 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007083 return finish(RHSOPT->isObjCBuiltinType() ||
7084 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007085 }
7086
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007087 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007088 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7089 QualType(RHSOPT,0),
7090 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007091
7092 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7093 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7094 if (LHS && RHS) { // We have 2 user-defined types.
7095 if (LHS != RHS) {
7096 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007097 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007098 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007099 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007100 }
7101 else
7102 return true;
7103 }
7104 return false;
7105}
7106
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007107/// Comparison routine for Objective-C protocols to be used with
7108/// llvm::array_pod_sort.
7109static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7110 ObjCProtocolDecl * const *rhs) {
7111 return (*lhs)->getName().compare((*rhs)->getName());
7112
7113}
7114
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007115/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007116/// of protocols inherited from two distinct objective-c pointer objects with
7117/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007118/// It is used to build composite qualifier list of the composite type of
7119/// the conditional expression involving two objective-c pointer objects.
7120static
7121void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007122 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007123 const ObjCObjectPointerType *LHSOPT,
7124 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007125 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007126
John McCall8b07ec22010-05-15 11:32:37 +00007127 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7128 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7129 assert(LHS->getInterface() && "LHS must have an interface base");
7130 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007131
7132 // Add all of the protocols for the LHS.
7133 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7134
7135 // Start with the protocol qualifiers.
7136 for (auto proto : LHS->quals()) {
7137 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007138 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007139
7140 // Also add the protocols associated with the LHS interface.
7141 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7142
7143 // Add all of the protocls for the RHS.
7144 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7145
7146 // Start with the protocol qualifiers.
7147 for (auto proto : RHS->quals()) {
7148 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007149 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007150
7151 // Also add the protocols associated with the RHS interface.
7152 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7153
7154 // Compute the intersection of the collected protocol sets.
7155 for (auto proto : LHSProtocolSet) {
7156 if (RHSProtocolSet.count(proto))
7157 IntersectionSet.push_back(proto);
7158 }
7159
7160 // Compute the set of protocols that is implied by either the common type or
7161 // the protocols within the intersection.
7162 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7163 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7164
7165 // Remove any implied protocols from the list of inherited protocols.
7166 if (!ImpliedProtocols.empty()) {
7167 IntersectionSet.erase(
7168 std::remove_if(IntersectionSet.begin(),
7169 IntersectionSet.end(),
7170 [&](ObjCProtocolDecl *proto) -> bool {
7171 return ImpliedProtocols.count(proto) > 0;
7172 }),
7173 IntersectionSet.end());
7174 }
7175
7176 // Sort the remaining protocols by name.
7177 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7178 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007179}
7180
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007181/// Determine whether the first type is a subtype of the second.
7182static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7183 QualType rhs) {
7184 // Common case: two object pointers.
7185 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7186 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7187 if (lhsOPT && rhsOPT)
7188 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7189
7190 // Two block pointers.
7191 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7192 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7193 if (lhsBlock && rhsBlock)
7194 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7195
7196 // If either is an unqualified 'id' and the other is a block, it's
7197 // acceptable.
7198 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7199 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7200 return true;
7201
7202 return false;
7203}
7204
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007205// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007206static bool sameObjCTypeArgs(ASTContext &ctx,
7207 const ObjCInterfaceDecl *iface,
7208 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007209 ArrayRef<QualType> rhsArgs,
7210 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007211 if (lhsArgs.size() != rhsArgs.size())
7212 return false;
7213
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007214 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007215 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007216 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7217 continue;
7218
7219 switch (typeParams->begin()[i]->getVariance()) {
7220 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007221 if (!stripKindOf ||
7222 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7223 rhsArgs[i].stripObjCKindOfType(ctx))) {
7224 return false;
7225 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007226 break;
7227
7228 case ObjCTypeParamVariance::Covariant:
7229 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7230 return false;
7231 break;
7232
7233 case ObjCTypeParamVariance::Contravariant:
7234 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7235 return false;
7236 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007237 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007238 }
7239
7240 return true;
7241}
7242
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007243QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007244 const ObjCObjectPointerType *Lptr,
7245 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007246 const ObjCObjectType *LHS = Lptr->getObjectType();
7247 const ObjCObjectType *RHS = Rptr->getObjectType();
7248 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7249 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007250
7251 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007252 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007253
Manman Renc46f7d12016-05-06 19:35:02 +00007254 // When either LHS or RHS is a kindof type, we should return a kindof type.
7255 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7256 // kindof(A).
7257 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7258
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007259 // Follow the left-hand side up the class hierarchy until we either hit a
7260 // root or find the RHS. Record the ancestors in case we don't find it.
7261 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7262 LHSAncestors;
7263 while (true) {
7264 // Record this ancestor. We'll need this if the common type isn't in the
7265 // path from the LHS to the root.
7266 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007267
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007268 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7269 // Get the type arguments.
7270 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7271 bool anyChanges = false;
7272 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7273 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007274 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7275 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007276 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007277 return QualType();
7278 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7279 // If only one has type arguments, the result will not have type
7280 // arguments.
7281 LHSTypeArgs = { };
7282 anyChanges = true;
7283 }
7284
7285 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007286 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007287 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7288 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007289 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007290 anyChanges = true;
7291
7292 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007293 // If we need to return a kindof type but LHS is not a kindof type, we
7294 // build a new result type.
7295 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007296 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007297 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007298 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007299 return getObjCObjectPointerType(Result);
7300 }
7301
7302 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007303 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007304
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007305 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007306 QualType LHSSuperType = LHS->getSuperClassType();
7307 if (LHSSuperType.isNull())
7308 break;
7309
7310 LHS = LHSSuperType->castAs<ObjCObjectType>();
7311 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007312
7313 // We didn't find anything by following the LHS to its root; now check
7314 // the RHS against the cached set of ancestors.
7315 while (true) {
7316 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7317 if (KnownLHS != LHSAncestors.end()) {
7318 LHS = KnownLHS->second;
7319
7320 // Get the type arguments.
7321 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7322 bool anyChanges = false;
7323 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7324 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007325 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7326 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007327 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007328 return QualType();
7329 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7330 // If only one has type arguments, the result will not have type
7331 // arguments.
7332 RHSTypeArgs = { };
7333 anyChanges = true;
7334 }
7335
7336 // Compute the intersection of protocols.
7337 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7338 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7339 Protocols);
7340 if (!Protocols.empty())
7341 anyChanges = true;
7342
Manman Renc46f7d12016-05-06 19:35:02 +00007343 // If we need to return a kindof type but RHS is not a kindof type, we
7344 // build a new result type.
7345 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007346 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007347 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007348 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007349 return getObjCObjectPointerType(Result);
7350 }
7351
7352 return getObjCObjectPointerType(QualType(RHS, 0));
7353 }
7354
7355 // Find the superclass of the RHS.
7356 QualType RHSSuperType = RHS->getSuperClassType();
7357 if (RHSSuperType.isNull())
7358 break;
7359
7360 RHS = RHSSuperType->castAs<ObjCObjectType>();
7361 }
7362
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007363 return QualType();
7364}
7365
John McCall8b07ec22010-05-15 11:32:37 +00007366bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7367 const ObjCObjectType *RHS) {
7368 assert(LHS->getInterface() && "LHS is not an interface type");
7369 assert(RHS->getInterface() && "RHS is not an interface type");
7370
Chris Lattner49af6a42008-04-07 06:51:04 +00007371 // Verify that the base decls are compatible: the RHS must be a subclass of
7372 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007373 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7374 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7375 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007376 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007377
Douglas Gregore83b9562015-07-07 03:57:53 +00007378 // If the LHS has protocol qualifiers, determine whether all of them are
7379 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7380 // LHS).
7381 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007382 // OK if conversion of LHS to SuperClass results in narrowing of types
7383 // ; i.e., SuperClass may implement at least one of the protocols
7384 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7385 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7386 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7387 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7388 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7389 // qualifiers.
7390 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007391 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007392 // If there is no protocols associated with RHS, it is not a match.
7393 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007394 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007395
7396 for (const auto *LHSProto : LHS->quals()) {
7397 bool SuperImplementsProtocol = false;
7398 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7399 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7400 SuperImplementsProtocol = true;
7401 break;
7402 }
7403 if (!SuperImplementsProtocol)
7404 return false;
7405 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007406 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007407
7408 // If the LHS is specialized, we may need to check type arguments.
7409 if (LHS->isSpecialized()) {
7410 // Follow the superclass chain until we've matched the LHS class in the
7411 // hierarchy. This substitutes type arguments through.
7412 const ObjCObjectType *RHSSuper = RHS;
7413 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7414 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7415
7416 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007417 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007418 !sameObjCTypeArgs(*this, LHS->getInterface(),
7419 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007420 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007421 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007422 }
7423 }
7424
7425 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007426}
7427
Steve Naroffb7605152009-02-12 17:52:19 +00007428bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7429 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007430 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7431 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007432
Steve Naroff7cae42b2009-07-10 23:34:53 +00007433 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007434 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007435
7436 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7437 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007438}
7439
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007440bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7441 return canAssignObjCInterfaces(
7442 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7443 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7444}
7445
Mike Stump11289f42009-09-09 15:08:12 +00007446/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007447/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007448/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007449/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007450bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7451 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007452 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007453 return hasSameType(LHS, RHS);
7454
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007455 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007456}
7457
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007458bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007459 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007460}
7461
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007462bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7463 return !mergeTypes(LHS, RHS, true).isNull();
7464}
7465
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007466/// mergeTransparentUnionType - if T is a transparent union type and a member
7467/// of T is compatible with SubType, return the merged type, else return
7468/// QualType()
7469QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7470 bool OfBlockPointer,
7471 bool Unqualified) {
7472 if (const RecordType *UT = T->getAsUnionType()) {
7473 RecordDecl *UD = UT->getDecl();
7474 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007475 for (const auto *I : UD->fields()) {
7476 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007477 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7478 if (!MT.isNull())
7479 return MT;
7480 }
7481 }
7482 }
7483
7484 return QualType();
7485}
7486
Alp Toker9cacbab2014-01-20 20:26:09 +00007487/// mergeFunctionParameterTypes - merge two types which appear as function
7488/// parameter types
7489QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7490 bool OfBlockPointer,
7491 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007492 // GNU extension: two types are compatible if they appear as a function
7493 // argument, one of the types is a transparent union type and the other
7494 // type is compatible with a union member
7495 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7496 Unqualified);
7497 if (!lmerge.isNull())
7498 return lmerge;
7499
7500 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7501 Unqualified);
7502 if (!rmerge.isNull())
7503 return rmerge;
7504
7505 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7506}
7507
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007508QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007509 bool OfBlockPointer,
7510 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007511 const FunctionType *lbase = lhs->getAs<FunctionType>();
7512 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007513 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7514 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007515 bool allLTypes = true;
7516 bool allRTypes = true;
7517
7518 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007519 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007520 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007521 QualType RHS = rbase->getReturnType();
7522 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007523 bool UnqualifiedResult = Unqualified;
7524 if (!UnqualifiedResult)
7525 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007526 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007527 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007528 else
Alp Toker314cc812014-01-25 16:55:45 +00007529 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007530 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007531 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007532
7533 if (Unqualified)
7534 retType = retType.getUnqualifiedType();
7535
Alp Toker314cc812014-01-25 16:55:45 +00007536 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7537 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007538 if (Unqualified) {
7539 LRetType = LRetType.getUnqualifiedType();
7540 RRetType = RRetType.getUnqualifiedType();
7541 }
7542
7543 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007544 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007545 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007546 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007547
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007548 // FIXME: double check this
7549 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7550 // rbase->getRegParmAttr() != 0 &&
7551 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007552 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7553 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007554
Douglas Gregor8c940862010-01-18 17:14:39 +00007555 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007556 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007557 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007558
John McCall8c6b56f2010-12-15 01:06:38 +00007559 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007560 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7561 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007562 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7563 return QualType();
7564
John McCall31168b02011-06-15 23:02:42 +00007565 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7566 return QualType();
7567
John McCall8c6b56f2010-12-15 01:06:38 +00007568 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7569 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007570
Rafael Espindola8778c282012-11-29 16:09:03 +00007571 if (lbaseInfo.getNoReturn() != NoReturn)
7572 allLTypes = false;
7573 if (rbaseInfo.getNoReturn() != NoReturn)
7574 allRTypes = false;
7575
John McCall31168b02011-06-15 23:02:42 +00007576 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007577
Eli Friedman47f77112008-08-22 00:56:42 +00007578 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007579 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7580 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007581 // Compatible functions must have the same number of parameters
7582 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007583 return QualType();
7584
7585 // Variadic and non-variadic functions aren't compatible
7586 if (lproto->isVariadic() != rproto->isVariadic())
7587 return QualType();
7588
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007589 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7590 return QualType();
7591
John McCall18afab72016-03-01 00:49:02 +00007592 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007593 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007594
7595 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007596 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007597 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7598 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7599 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7600 QualType paramType = mergeFunctionParameterTypes(
7601 lParamType, rParamType, OfBlockPointer, Unqualified);
7602 if (paramType.isNull())
7603 return QualType();
7604
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007605 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007606 paramType = paramType.getUnqualifiedType();
7607
7608 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007609 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007610 lParamType = lParamType.getUnqualifiedType();
7611 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007612 }
Alp Toker601b22c2014-01-21 23:35:24 +00007613
7614 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007615 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007616 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007617 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007618 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007619
Eli Friedman47f77112008-08-22 00:56:42 +00007620 if (allLTypes) return lhs;
7621 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007622
7623 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7624 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007625 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007626 }
7627
7628 if (lproto) allRTypes = false;
7629 if (rproto) allLTypes = false;
7630
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007631 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007632 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007633 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007634 if (proto->isVariadic()) return QualType();
7635 // Check that the types are compatible with the types that
7636 // would result from default argument promotions (C99 6.7.5.3p15).
7637 // The only types actually affected are promotable integer
7638 // types and floats, which would be passed as a different
7639 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007640 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7641 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007642
Eli Friedman448ce402012-08-30 00:44:15 +00007643 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007644 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007645 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7646 paramTy = Enum->getDecl()->getIntegerType();
7647 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007648 return QualType();
7649 }
Alp Toker601b22c2014-01-21 23:35:24 +00007650
7651 if (paramTy->isPromotableIntegerType() ||
7652 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007653 return QualType();
7654 }
7655
7656 if (allLTypes) return lhs;
7657 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007658
7659 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7660 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007661 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007662 }
7663
7664 if (allLTypes) return lhs;
7665 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007666 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007667}
7668
John McCall433c2e62013-03-21 00:10:07 +00007669/// Given that we have an enum type and a non-enum type, try to merge them.
7670static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7671 QualType other, bool isBlockReturnType) {
7672 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7673 // a signed integer type, or an unsigned integer type.
7674 // Compatibility is based on the underlying type, not the promotion
7675 // type.
7676 QualType underlyingType = ET->getDecl()->getIntegerType();
7677 if (underlyingType.isNull()) return QualType();
7678 if (Context.hasSameType(underlyingType, other))
7679 return other;
7680
7681 // In block return types, we're more permissive and accept any
7682 // integral type of the same size.
7683 if (isBlockReturnType && other->isIntegerType() &&
7684 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7685 return other;
7686
7687 return QualType();
7688}
7689
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007690QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007691 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007692 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007693 // C++ [expr]: If an expression initially has the type "reference to T", the
7694 // type is adjusted to "T" prior to any further analysis, the expression
7695 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007696 // expression is an lvalue unless the reference is an rvalue reference and
7697 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007698 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7699 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007700
7701 if (Unqualified) {
7702 LHS = LHS.getUnqualifiedType();
7703 RHS = RHS.getUnqualifiedType();
7704 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007705
Eli Friedman47f77112008-08-22 00:56:42 +00007706 QualType LHSCan = getCanonicalType(LHS),
7707 RHSCan = getCanonicalType(RHS);
7708
7709 // If two types are identical, they are compatible.
7710 if (LHSCan == RHSCan)
7711 return LHS;
7712
John McCall8ccfcb52009-09-24 19:53:00 +00007713 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007714 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7715 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007716 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007717 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00007718 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007719 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7720 return QualType();
7721 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7722 return LHS;
7723 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7724 return RHS;
7725 }
John McCall8ccfcb52009-09-24 19:53:00 +00007726 // If any of these qualifiers are different, we have a type
7727 // mismatch.
7728 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007729 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7730 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007731 return QualType();
7732
7733 // Exactly one GC qualifier difference is allowed: __strong is
7734 // okay if the other type has no GC qualifier but is an Objective
7735 // C object pointer (i.e. implicitly strong by default). We fix
7736 // this by pretending that the unqualified type was actually
7737 // qualified __strong.
7738 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7739 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7740 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7741
7742 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7743 return QualType();
7744
7745 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7746 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7747 }
7748 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7749 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7750 }
Eli Friedman47f77112008-08-22 00:56:42 +00007751 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007752 }
7753
7754 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007755
Eli Friedmandcca6332009-06-01 01:22:52 +00007756 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7757 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007758
Chris Lattnerfd652912008-01-14 05:45:46 +00007759 // We want to consider the two function types to be the same for these
7760 // comparisons, just force one to the other.
7761 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7762 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007763
7764 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007765 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7766 LHSClass = Type::ConstantArray;
7767 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7768 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007769
John McCall8b07ec22010-05-15 11:32:37 +00007770 // ObjCInterfaces are just specialized ObjCObjects.
7771 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7772 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7773
Nate Begemance4d7fc2008-04-18 23:10:10 +00007774 // Canonicalize ExtVector -> Vector.
7775 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7776 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007777
Chris Lattner95554662008-04-07 05:43:21 +00007778 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007779 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007780 // Note that we only have special rules for turning block enum
7781 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007782 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007783 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007784 }
John McCall9dd450b2009-09-21 23:43:11 +00007785 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007786 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007787 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007788 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007789 if (OfBlockPointer && !BlockReturnType) {
7790 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7791 return LHS;
7792 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7793 return RHS;
7794 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007795
Eli Friedman47f77112008-08-22 00:56:42 +00007796 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007797 }
Eli Friedman47f77112008-08-22 00:56:42 +00007798
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007799 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007800 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007801#define TYPE(Class, Base)
7802#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007803#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007804#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7805#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7806#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007807 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007808
Richard Smith27d807c2013-04-30 13:56:41 +00007809 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007810 case Type::LValueReference:
7811 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007812 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007813 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007814
John McCall8b07ec22010-05-15 11:32:37 +00007815 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007816 case Type::IncompleteArray:
7817 case Type::VariableArray:
7818 case Type::FunctionProto:
7819 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007820 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007821
Chris Lattnerfd652912008-01-14 05:45:46 +00007822 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007823 {
7824 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007825 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7826 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007827 if (Unqualified) {
7828 LHSPointee = LHSPointee.getUnqualifiedType();
7829 RHSPointee = RHSPointee.getUnqualifiedType();
7830 }
7831 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7832 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007833 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007834 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007835 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007836 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007837 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007838 return getPointerType(ResultType);
7839 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007840 case Type::BlockPointer:
7841 {
7842 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007843 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7844 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007845 if (Unqualified) {
7846 LHSPointee = LHSPointee.getUnqualifiedType();
7847 RHSPointee = RHSPointee.getUnqualifiedType();
7848 }
7849 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7850 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007851 if (ResultType.isNull()) return QualType();
7852 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7853 return LHS;
7854 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7855 return RHS;
7856 return getBlockPointerType(ResultType);
7857 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007858 case Type::Atomic:
7859 {
7860 // Merge two pointer types, while trying to preserve typedef info
7861 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7862 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7863 if (Unqualified) {
7864 LHSValue = LHSValue.getUnqualifiedType();
7865 RHSValue = RHSValue.getUnqualifiedType();
7866 }
7867 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7868 Unqualified);
7869 if (ResultType.isNull()) return QualType();
7870 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7871 return LHS;
7872 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7873 return RHS;
7874 return getAtomicType(ResultType);
7875 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007876 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007877 {
7878 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7879 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7880 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7881 return QualType();
7882
7883 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7884 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007885 if (Unqualified) {
7886 LHSElem = LHSElem.getUnqualifiedType();
7887 RHSElem = RHSElem.getUnqualifiedType();
7888 }
7889
7890 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007891 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007892 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7893 return LHS;
7894 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7895 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007896 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7897 ArrayType::ArraySizeModifier(), 0);
7898 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7899 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007900 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7901 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007902 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7903 return LHS;
7904 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7905 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007906 if (LVAT) {
7907 // FIXME: This isn't correct! But tricky to implement because
7908 // the array's size has to be the size of LHS, but the type
7909 // has to be different.
7910 return LHS;
7911 }
7912 if (RVAT) {
7913 // FIXME: This isn't correct! But tricky to implement because
7914 // the array's size has to be the size of RHS, but the type
7915 // has to be different.
7916 return RHS;
7917 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007918 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7919 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007920 return getIncompleteArrayType(ResultType,
7921 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007922 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007923 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007924 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007925 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007926 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007927 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007928 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007929 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007930 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007931 case Type::Complex:
7932 // Distinct complex types are incompatible.
7933 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007934 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007935 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007936 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7937 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007938 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007939 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007940 case Type::ObjCObject: {
7941 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007942 // FIXME: This should be type compatibility, e.g. whether
7943 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007944 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7945 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7946 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007947 return LHS;
7948
Eli Friedman47f77112008-08-22 00:56:42 +00007949 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007950 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007951 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007952 if (OfBlockPointer) {
7953 if (canAssignObjCInterfacesInBlockPointer(
7954 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007955 RHS->getAs<ObjCObjectPointerType>(),
7956 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007957 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007958 return QualType();
7959 }
John McCall9dd450b2009-09-21 23:43:11 +00007960 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7961 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007962 return LHS;
7963
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007964 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007965 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00007966 case Type::Pipe:
7967 {
7968 // Merge two pointer types, while trying to preserve typedef info
7969 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7970 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7971 if (Unqualified) {
7972 LHSValue = LHSValue.getUnqualifiedType();
7973 RHSValue = RHSValue.getUnqualifiedType();
7974 }
7975 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7976 Unqualified);
7977 if (ResultType.isNull()) return QualType();
7978 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7979 return LHS;
7980 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7981 return RHS;
7982 return getPipeType(ResultType);
7983 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007984 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007985
David Blaikie8a40f702012-01-17 06:56:22 +00007986 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007987}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007988
John McCall18afab72016-03-01 00:49:02 +00007989bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7990 const FunctionProtoType *firstFnType,
7991 const FunctionProtoType *secondFnType) {
7992 // Fast path: if the first type doesn't have ext parameter infos,
7993 // we match if and only if they second type also doesn't have them.
7994 if (!firstFnType->hasExtParameterInfos())
7995 return !secondFnType->hasExtParameterInfos();
7996
7997 // Otherwise, we can only match if the second type has them.
7998 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007999 return false;
John McCall18afab72016-03-01 00:49:02 +00008000
8001 auto firstEPI = firstFnType->getExtParameterInfos();
8002 auto secondEPI = secondFnType->getExtParameterInfos();
8003 assert(firstEPI.size() == secondEPI.size());
8004
8005 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8006 if (firstEPI[i] != secondEPI[i])
8007 return false;
8008 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008009 return true;
8010}
8011
Chandler Carruth21c90602015-12-30 03:24:14 +00008012void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8013 ObjCLayouts[CD] = nullptr;
8014}
8015
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008016/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8017/// 'RHS' attributes and returns the merged version; including for function
8018/// return types.
8019QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8020 QualType LHSCan = getCanonicalType(LHS),
8021 RHSCan = getCanonicalType(RHS);
8022 // If two types are identical, they are compatible.
8023 if (LHSCan == RHSCan)
8024 return LHS;
8025 if (RHSCan->isFunctionType()) {
8026 if (!LHSCan->isFunctionType())
8027 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008028 QualType OldReturnType =
8029 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008030 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008031 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008032 QualType ResReturnType =
8033 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8034 if (ResReturnType.isNull())
8035 return QualType();
8036 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8037 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8038 // In either case, use OldReturnType to build the new function type.
8039 const FunctionType *F = LHS->getAs<FunctionType>();
8040 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008041 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8042 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008043 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008044 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008045 return ResultType;
8046 }
8047 }
8048 return QualType();
8049 }
8050
8051 // If the qualifiers are different, the types can still be merged.
8052 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8053 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8054 if (LQuals != RQuals) {
8055 // If any of these qualifiers are different, we have a type mismatch.
8056 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8057 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8058 return QualType();
8059
8060 // Exactly one GC qualifier difference is allowed: __strong is
8061 // okay if the other type has no GC qualifier but is an Objective
8062 // C object pointer (i.e. implicitly strong by default). We fix
8063 // this by pretending that the unqualified type was actually
8064 // qualified __strong.
8065 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8066 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8067 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8068
8069 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8070 return QualType();
8071
8072 if (GC_L == Qualifiers::Strong)
8073 return LHS;
8074 if (GC_R == Qualifiers::Strong)
8075 return RHS;
8076 return QualType();
8077 }
8078
8079 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8080 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8081 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8082 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8083 if (ResQT == LHSBaseQT)
8084 return LHS;
8085 if (ResQT == RHSBaseQT)
8086 return RHS;
8087 }
8088 return QualType();
8089}
8090
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008091//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008092// Integer Predicates
8093//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008094
Jay Foad39c79802011-01-12 09:06:06 +00008095unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008096 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008097 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008098 if (T->isBooleanType())
8099 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008100 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008101 return (unsigned)getTypeSize(T);
8102}
8103
Abramo Bagnara13640492012-09-09 10:21:24 +00008104QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008105 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008106
8107 // Turn <4 x signed int> -> <4 x unsigned int>
8108 if (const VectorType *VTy = T->getAs<VectorType>())
8109 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008110 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008111
8112 // For enums, we return the unsigned version of the base type.
8113 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008114 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008115
8116 const BuiltinType *BTy = T->getAs<BuiltinType>();
8117 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008118 switch (BTy->getKind()) {
8119 case BuiltinType::Char_S:
8120 case BuiltinType::SChar:
8121 return UnsignedCharTy;
8122 case BuiltinType::Short:
8123 return UnsignedShortTy;
8124 case BuiltinType::Int:
8125 return UnsignedIntTy;
8126 case BuiltinType::Long:
8127 return UnsignedLongTy;
8128 case BuiltinType::LongLong:
8129 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008130 case BuiltinType::Int128:
8131 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008132 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008133 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008134 }
8135}
8136
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008137ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008138
Richard Smith1fa5d642013-05-11 05:45:24 +00008139void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8140 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008141
8142//===----------------------------------------------------------------------===//
8143// Builtin Type Computation
8144//===----------------------------------------------------------------------===//
8145
8146/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008147/// pointer over the consumed characters. This returns the resultant type. If
8148/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8149/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8150/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008151///
8152/// RequiresICE is filled in on return to indicate whether the value is required
8153/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008154static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008155 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008156 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008157 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008158 // Modifiers.
8159 int HowLong = 0;
8160 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008161 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008162
Chris Lattnerdc226c22010-10-01 22:42:38 +00008163 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008164 bool Done = false;
8165 while (!Done) {
8166 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008167 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008168 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008169 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008170 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008171 case 'S':
8172 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8173 assert(!Signed && "Can't use 'S' modifier multiple times!");
8174 Signed = true;
8175 break;
8176 case 'U':
8177 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008178 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008179 Unsigned = true;
8180 break;
8181 case 'L':
8182 assert(HowLong <= 2 && "Can't have LLLL modifier");
8183 ++HowLong;
8184 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008185 case 'W':
8186 // This modifier represents int64 type.
8187 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8188 switch (Context.getTargetInfo().getInt64Type()) {
8189 default:
8190 llvm_unreachable("Unexpected integer type");
8191 case TargetInfo::SignedLong:
8192 HowLong = 1;
8193 break;
8194 case TargetInfo::SignedLongLong:
8195 HowLong = 2;
8196 break;
8197 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008198 }
8199 }
8200
8201 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008202
Chris Lattnerecd79c62009-06-14 00:45:47 +00008203 // Read the base type.
8204 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008205 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008206 case 'v':
8207 assert(HowLong == 0 && !Signed && !Unsigned &&
8208 "Bad modifiers used with 'v'!");
8209 Type = Context.VoidTy;
8210 break;
Jack Carter24bef982013-08-15 15:16:57 +00008211 case 'h':
8212 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008213 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008214 Type = Context.HalfTy;
8215 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008216 case 'f':
8217 assert(HowLong == 0 && !Signed && !Unsigned &&
8218 "Bad modifiers used with 'f'!");
8219 Type = Context.FloatTy;
8220 break;
8221 case 'd':
8222 assert(HowLong < 2 && !Signed && !Unsigned &&
8223 "Bad modifiers used with 'd'!");
8224 if (HowLong)
8225 Type = Context.LongDoubleTy;
8226 else
8227 Type = Context.DoubleTy;
8228 break;
8229 case 's':
8230 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8231 if (Unsigned)
8232 Type = Context.UnsignedShortTy;
8233 else
8234 Type = Context.ShortTy;
8235 break;
8236 case 'i':
8237 if (HowLong == 3)
8238 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8239 else if (HowLong == 2)
8240 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8241 else if (HowLong == 1)
8242 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8243 else
8244 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8245 break;
8246 case 'c':
8247 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8248 if (Signed)
8249 Type = Context.SignedCharTy;
8250 else if (Unsigned)
8251 Type = Context.UnsignedCharTy;
8252 else
8253 Type = Context.CharTy;
8254 break;
8255 case 'b': // boolean
8256 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8257 Type = Context.BoolTy;
8258 break;
8259 case 'z': // size_t.
8260 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8261 Type = Context.getSizeType();
8262 break;
8263 case 'F':
8264 Type = Context.getCFConstantStringType();
8265 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008266 case 'G':
8267 Type = Context.getObjCIdType();
8268 break;
8269 case 'H':
8270 Type = Context.getObjCSelType();
8271 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008272 case 'M':
8273 Type = Context.getObjCSuperType();
8274 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008275 case 'a':
8276 Type = Context.getBuiltinVaListType();
8277 assert(!Type.isNull() && "builtin va list type not initialized!");
8278 break;
8279 case 'A':
8280 // This is a "reference" to a va_list; however, what exactly
8281 // this means depends on how va_list is defined. There are two
8282 // different kinds of va_list: ones passed by value, and ones
8283 // passed by reference. An example of a by-value va_list is
8284 // x86, where va_list is a char*. An example of by-ref va_list
8285 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8286 // we want this argument to be a char*&; for x86-64, we want
8287 // it to be a __va_list_tag*.
8288 Type = Context.getBuiltinVaListType();
8289 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008290 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008291 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008292 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008293 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008294 break;
8295 case 'V': {
8296 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008297 unsigned NumElements = strtoul(Str, &End, 10);
8298 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008299 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008300
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008301 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8302 RequiresICE, false);
8303 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008304
8305 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008306 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008307 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008308 break;
8309 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008310 case 'E': {
8311 char *End;
8312
8313 unsigned NumElements = strtoul(Str, &End, 10);
8314 assert(End != Str && "Missing vector size");
8315
8316 Str = End;
8317
8318 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8319 false);
8320 Type = Context.getExtVectorType(ElementType, NumElements);
8321 break;
8322 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008323 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008324 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8325 false);
8326 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008327 Type = Context.getComplexType(ElementType);
8328 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008329 }
8330 case 'Y' : {
8331 Type = Context.getPointerDiffType();
8332 break;
8333 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008334 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008335 Type = Context.getFILEType();
8336 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008337 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008338 return QualType();
8339 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008340 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008341 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008342 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008343 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008344 else
8345 Type = Context.getjmp_bufType();
8346
Mike Stump2adb4da2009-07-28 23:47:15 +00008347 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008348 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008349 return QualType();
8350 }
8351 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008352 case 'K':
8353 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8354 Type = Context.getucontext_tType();
8355
8356 if (Type.isNull()) {
8357 Error = ASTContext::GE_Missing_ucontext;
8358 return QualType();
8359 }
8360 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008361 case 'p':
8362 Type = Context.getProcessIDType();
8363 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008364 }
Mike Stump11289f42009-09-09 15:08:12 +00008365
Chris Lattnerdc226c22010-10-01 22:42:38 +00008366 // If there are modifiers and if we're allowed to parse them, go for it.
8367 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008368 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008369 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008370 default: Done = true; --Str; break;
8371 case '*':
8372 case '&': {
8373 // Both pointers and references can have their pointee types
8374 // qualified with an address space.
8375 char *End;
8376 unsigned AddrSpace = strtoul(Str, &End, 10);
8377 if (End != Str && AddrSpace != 0) {
8378 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8379 Str = End;
8380 }
8381 if (c == '*')
8382 Type = Context.getPointerType(Type);
8383 else
8384 Type = Context.getLValueReferenceType(Type);
8385 break;
8386 }
8387 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8388 case 'C':
8389 Type = Type.withConst();
8390 break;
8391 case 'D':
8392 Type = Context.getVolatileType(Type);
8393 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008394 case 'R':
8395 Type = Type.withRestrict();
8396 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008397 }
8398 }
Chris Lattner84733392010-10-01 07:13:18 +00008399
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008400 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008401 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008402
Chris Lattnerecd79c62009-06-14 00:45:47 +00008403 return Type;
8404}
8405
8406/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008407QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008408 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008409 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008410 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008411
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008412 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008413
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008414 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008415 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008416 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8417 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008418 if (Error != GE_None)
8419 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008420
8421 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8422
Chris Lattnerecd79c62009-06-14 00:45:47 +00008423 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008424 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008425 if (Error != GE_None)
8426 return QualType();
8427
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008428 // If this argument is required to be an IntegerConstantExpression and the
8429 // caller cares, fill in the bitmask we return.
8430 if (RequiresICE && IntegerConstantArgs)
8431 *IntegerConstantArgs |= 1 << ArgTypes.size();
8432
Chris Lattnerecd79c62009-06-14 00:45:47 +00008433 // Do array -> pointer decay. The builtin should use the decayed type.
8434 if (Ty->isArrayType())
8435 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008436
Chris Lattnerecd79c62009-06-14 00:45:47 +00008437 ArgTypes.push_back(Ty);
8438 }
8439
David Majnemerba3e5ec2015-03-13 18:26:17 +00008440 if (Id == Builtin::BI__GetExceptionInfo)
8441 return QualType();
8442
Chris Lattnerecd79c62009-06-14 00:45:47 +00008443 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8444 "'.' should only occur at end of builtin type list!");
8445
Reid Kleckner78af0702013-08-27 23:08:25 +00008446 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008447 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8448
8449 bool Variadic = (TypeStr[0] == '.');
8450
8451 // We really shouldn't be making a no-proto type here, especially in C++.
8452 if (ArgTypes.empty() && Variadic)
8453 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008454
John McCalldb40c7f2010-12-14 08:05:40 +00008455 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008456 EPI.ExtInfo = EI;
8457 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008458
Jordan Rose5c382722013-03-08 21:51:21 +00008459 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008460}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008461
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008462static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8463 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008464 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008465 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008466
Rafael Espindola3ae00052013-05-13 00:12:11 +00008467 GVALinkage External = GVA_StrongExternal;
8468 switch (FD->getTemplateSpecializationKind()) {
8469 case TSK_Undeclared:
8470 case TSK_ExplicitSpecialization:
8471 External = GVA_StrongExternal;
8472 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008473
Rafael Espindola3ae00052013-05-13 00:12:11 +00008474 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008475 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008476
David Majnemerc3d07332014-05-15 06:25:57 +00008477 // C++11 [temp.explicit]p10:
8478 // [ Note: The intent is that an inline function that is the subject of
8479 // an explicit instantiation declaration will still be implicitly
8480 // instantiated when used so that the body can be considered for
8481 // inlining, but that no out-of-line copy of the inline function would be
8482 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008483 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008484 return GVA_AvailableExternally;
8485
Rafael Espindola3ae00052013-05-13 00:12:11 +00008486 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008487 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008488 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008489 }
8490
8491 if (!FD->isInlined())
8492 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008493
David Majnemer3f021502015-10-08 04:53:31 +00008494 if ((!Context.getLangOpts().CPlusPlus &&
8495 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008496 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008497 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008498 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8499
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008500 // GNU or C99 inline semantics. Determine whether this symbol should be
8501 // externally visible.
8502 if (FD->isInlineDefinitionExternallyVisible())
8503 return External;
8504
8505 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008506 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008507 }
8508
David Majnemer54e3ba52014-04-02 23:17:29 +00008509 // Functions specified with extern and inline in -fms-compatibility mode
8510 // forcibly get emitted. While the body of the function cannot be later
8511 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008512 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008513 return GVA_StrongODR;
8514
David Majnemer27d69db2014-04-28 22:17:59 +00008515 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008516}
8517
Artem Belevichca2b9512016-05-02 20:30:03 +00008518static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8519 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008520 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8521 // dllexport/dllimport on inline functions.
8522 if (D->hasAttr<DLLImportAttr>()) {
8523 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8524 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008525 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008526 if (L == GVA_DiscardableODR)
8527 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008528 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8529 D->hasAttr<CUDAGlobalAttr>()) {
8530 // Device-side functions with __global__ attribute must always be
8531 // visible externally so they can be launched from host.
8532 if (L == GVA_DiscardableODR || L == GVA_Internal)
8533 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008534 }
8535 return L;
8536}
8537
8538GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008539 return adjustGVALinkageForAttributes(
8540 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008541}
8542
8543static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8544 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008545 if (!VD->isExternallyVisible())
8546 return GVA_Internal;
8547
David Majnemer27d69db2014-04-28 22:17:59 +00008548 if (VD->isStaticLocal()) {
8549 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8550 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8551 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8552 LexicalContext = LexicalContext->getLexicalParent();
8553
Richard Smith9e2341d2015-03-23 03:25:59 +00008554 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008555 // enclosing function.
8556 if (LexicalContext)
8557 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008558 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008559
8560 // GVA_StrongODR function linkage is stronger than what we need,
8561 // downgrade to GVA_DiscardableODR.
8562 // This allows us to discard the variable if we never end up needing it.
8563 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8564 : StaticLocalLinkage;
8565 }
8566
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008567 // MSVC treats in-class initialized static data members as definitions.
8568 // By giving them non-strong linkage, out-of-line definitions won't
8569 // cause link errors.
8570 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8571 return GVA_DiscardableODR;
8572
Richard Smithd9b90092016-07-02 01:32:16 +00008573 // Most non-template variables have strong linkage; inline variables are
8574 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8575 GVALinkage StrongLinkage;
8576 switch (Context.getInlineVariableDefinitionKind(VD)) {
8577 case ASTContext::InlineVariableDefinitionKind::None:
8578 StrongLinkage = GVA_StrongExternal;
8579 break;
8580 case ASTContext::InlineVariableDefinitionKind::Weak:
8581 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008582 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008583 break;
8584 case ASTContext::InlineVariableDefinitionKind::Strong:
8585 StrongLinkage = GVA_StrongODR;
8586 break;
8587 }
Richard Smith62f19e72016-06-25 00:15:56 +00008588
Richard Smith8809a0c2013-09-27 20:14:12 +00008589 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008590 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008591 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008592
David Majnemer6d1780c2015-07-17 23:36:49 +00008593 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008594 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8595 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008596 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008597 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008598
Rafael Espindola3ae00052013-05-13 00:12:11 +00008599 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008600 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008601
David Majnemer27d69db2014-04-28 22:17:59 +00008602 case TSK_ExplicitInstantiationDeclaration:
8603 return GVA_AvailableExternally;
8604
Rafael Espindola3ae00052013-05-13 00:12:11 +00008605 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008606 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008607 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008608
8609 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008610}
8611
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008612GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008613 return adjustGVALinkageForAttributes(
8614 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008615}
8616
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008617bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008618 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8619 if (!VD->isFileVarDecl())
8620 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008621 // Global named register variables (GNU extension) are never emitted.
8622 if (VD->getStorageClass() == SC_Register)
8623 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008624 if (VD->getDescribedVarTemplate() ||
8625 isa<VarTemplatePartialSpecializationDecl>(VD))
8626 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008627 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8628 // We never need to emit an uninstantiated function template.
8629 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8630 return false;
Nico Weber66220292016-03-02 17:28:48 +00008631 } else if (isa<PragmaCommentDecl>(D))
8632 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008633 else if (isa<OMPThreadPrivateDecl>(D) ||
8634 D->hasAttr<OMPDeclareTargetDeclAttr>())
8635 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008636 else if (isa<PragmaDetectMismatchDecl>(D))
8637 return true;
Nico Weber66220292016-03-02 17:28:48 +00008638 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008639 return !D->getDeclContext()->isDependentContext();
8640 else if (isa<OMPDeclareReductionDecl>(D))
8641 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00008642 else if (isa<ImportDecl>(D))
8643 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00008644 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008645 return false;
8646
8647 // If this is a member of a class template, we do not need to emit it.
8648 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008649 return false;
8650
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008651 // Weak references don't produce any output by themselves.
8652 if (D->hasAttr<WeakRefAttr>())
8653 return false;
8654
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008655 // Aliases and used decls are required.
8656 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8657 return true;
8658
8659 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8660 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008661 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008662 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008663
8664 // Constructors and destructors are required.
8665 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8666 return true;
8667
John McCall6bd2a892013-01-25 22:31:03 +00008668 // The key function for a class is required. This rule only comes
8669 // into play when inline functions can be key functions, though.
8670 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8671 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8672 const CXXRecordDecl *RD = MD->getParent();
8673 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8674 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8675 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8676 return true;
8677 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008678 }
8679 }
8680
8681 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8682
8683 // static, static inline, always_inline, and extern inline functions can
8684 // always be deferred. Normal inline functions can be deferred in C99/C++.
8685 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008686 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8687 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008688 return false;
8689 return true;
8690 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008691
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008692 const VarDecl *VD = cast<VarDecl>(D);
8693 assert(VD->isFileVarDecl() && "Expected file scoped var");
8694
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008695 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8696 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008697 return false;
8698
Richard Smitha0e5e542012-11-12 21:38:00 +00008699 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008700 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008701 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8702 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008703 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008704
Richard Smitha0e5e542012-11-12 21:38:00 +00008705 // Variables that have destruction with side-effects are required.
8706 if (VD->getType().isDestructedType())
8707 return true;
8708
8709 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008710 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8711 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008712 return true;
8713
8714 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008715}
Charles Davis53c59df2010-08-16 03:33:14 +00008716
Reid Kleckner78af0702013-08-27 23:08:25 +00008717CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8718 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008719 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008720 if (IsCXXMethod)
8721 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008722
Alexey Bataeva7547182016-05-18 09:06:38 +00008723 switch (LangOpts.getDefaultCallingConv()) {
8724 case LangOptions::DCC_None:
8725 break;
8726 case LangOptions::DCC_CDecl:
8727 return CC_C;
8728 case LangOptions::DCC_FastCall:
8729 if (getTargetInfo().hasFeature("sse2"))
8730 return CC_X86FastCall;
8731 break;
8732 case LangOptions::DCC_StdCall:
8733 if (!IsVariadic)
8734 return CC_X86StdCall;
8735 break;
8736 case LangOptions::DCC_VectorCall:
8737 // __vectorcall cannot be applied to variadic functions.
8738 if (!IsVariadic)
8739 return CC_X86VectorCall;
8740 break;
8741 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008742 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008743}
8744
Jay Foad39c79802011-01-12 09:06:06 +00008745bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008746 // Pass through to the C++ ABI object
8747 return ABI->isNearlyEmpty(RD);
8748}
8749
Reid Kleckner96f8f932014-02-05 17:27:08 +00008750VTableContextBase *ASTContext::getVTableContext() {
8751 if (!VTContext.get()) {
8752 if (Target->getCXXABI().isMicrosoft())
8753 VTContext.reset(new MicrosoftVTableContext(*this));
8754 else
8755 VTContext.reset(new ItaniumVTableContext(*this));
8756 }
8757 return VTContext.get();
8758}
8759
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008760MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008761 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008762 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008763 case TargetCXXABI::GenericItanium:
8764 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008765 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008766 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008767 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008768 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008769 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008770 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008771 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008772 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008773 }
David Blaikie83d382b2011-09-23 05:06:16 +00008774 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008775}
8776
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008777CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008778
8779size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008780 return ASTRecordLayouts.getMemorySize() +
8781 llvm::capacity_in_bytes(ObjCLayouts) +
8782 llvm::capacity_in_bytes(KeyFunctions) +
8783 llvm::capacity_in_bytes(ObjCImpls) +
8784 llvm::capacity_in_bytes(BlockVarCopyInits) +
8785 llvm::capacity_in_bytes(DeclAttrs) +
8786 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8787 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8788 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8789 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8790 llvm::capacity_in_bytes(OverriddenMethods) +
8791 llvm::capacity_in_bytes(Types) +
8792 llvm::capacity_in_bytes(VariableArrayTypes) +
8793 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008794}
Ted Kremenek540017e2011-10-06 05:00:56 +00008795
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008796/// getIntTypeForBitwidth -
8797/// sets integer QualTy according to specified details:
8798/// bitwidth, signed/unsigned.
8799/// Returns empty type if there is no appropriate target types.
8800QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8801 unsigned Signed) const {
8802 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8803 CanQualType QualTy = getFromTargetType(Ty);
8804 if (!QualTy && DestWidth == 128)
8805 return Signed ? Int128Ty : UnsignedInt128Ty;
8806 return QualTy;
8807}
8808
8809/// getRealTypeForBitwidth -
8810/// sets floating point QualTy according to specified bitwidth.
8811/// Returns empty type if there is no appropriate target types.
8812QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8813 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8814 switch (Ty) {
8815 case TargetInfo::Float:
8816 return FloatTy;
8817 case TargetInfo::Double:
8818 return DoubleTy;
8819 case TargetInfo::LongDouble:
8820 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00008821 case TargetInfo::Float128:
8822 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008823 case TargetInfo::NoFloat:
8824 return QualType();
8825 }
8826
8827 llvm_unreachable("Unhandled TargetInfo::RealType value");
8828}
8829
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008830void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8831 if (Number > 1)
8832 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008833}
8834
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008835unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008836 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008837 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008838}
8839
David Majnemer2206bf52014-03-05 08:57:59 +00008840void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8841 if (Number > 1)
8842 StaticLocalNumbers[VD] = Number;
8843}
8844
8845unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008846 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00008847 return I != StaticLocalNumbers.end() ? I->second : 1;
8848}
8849
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008850MangleNumberingContext &
8851ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008852 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8853 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8854 if (!MCtx)
8855 MCtx = createMangleNumberingContext();
8856 return *MCtx;
8857}
8858
8859MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8860 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008861}
8862
David Majnemere7a818f2015-03-06 18:53:55 +00008863const CXXConstructorDecl *
8864ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8865 return ABI->getCopyConstructorForExceptionObject(
8866 cast<CXXRecordDecl>(RD->getFirstDecl()));
8867}
8868
8869void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8870 CXXConstructorDecl *CD) {
8871 return ABI->addCopyConstructorForExceptionObject(
8872 cast<CXXRecordDecl>(RD->getFirstDecl()),
8873 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8874}
8875
David Majnemerdfa6d202015-03-11 18:36:39 +00008876void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8877 unsigned ParmIdx, Expr *DAE) {
8878 ABI->addDefaultArgExprForConstructor(
8879 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8880}
8881
8882Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8883 unsigned ParmIdx) {
8884 return ABI->getDefaultArgExprForConstructor(
8885 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8886}
8887
David Majnemer00350522015-08-31 18:48:39 +00008888void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8889 TypedefNameDecl *DD) {
8890 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8891}
8892
8893TypedefNameDecl *
8894ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8895 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8896}
8897
8898void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8899 DeclaratorDecl *DD) {
8900 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8901}
8902
8903DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8904 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8905}
8906
Ted Kremenek540017e2011-10-06 05:00:56 +00008907void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8908 ParamIndices[D] = index;
8909}
8910
8911unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8912 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8913 assert(I != ParamIndices.end() &&
8914 "ParmIndices lacks entry set by ParmVarDecl");
8915 return I->second;
8916}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008917
Richard Smithe6c01442013-06-05 00:46:14 +00008918APValue *
8919ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8920 bool MayCreate) {
8921 assert(E && E->getStorageDuration() == SD_Static &&
8922 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008923 if (MayCreate) {
8924 APValue *&MTVI = MaterializedTemporaryValues[E];
8925 if (!MTVI)
8926 MTVI = new (*this) APValue;
8927 return MTVI;
8928 }
Richard Smithe6c01442013-06-05 00:46:14 +00008929
David Majnemer2dcef9e2015-08-13 23:50:15 +00008930 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008931}
8932
Fariborz Jahanian615de762013-05-28 17:37:39 +00008933bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8934 const llvm::Triple &T = getTargetInfo().getTriple();
8935 if (!T.isOSDarwin())
8936 return false;
8937
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008938 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8939 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8940 return false;
8941
Fariborz Jahanian615de762013-05-28 17:37:39 +00008942 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8943 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8944 uint64_t Size = sizeChars.getQuantity();
8945 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8946 unsigned Align = alignChars.getQuantity();
8947 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8948 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8949}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008950
8951namespace {
8952
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008953ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8954 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008955 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008956 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008957 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008958 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008959 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008960}
8961
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008962/// Template specializations to abstract away from pointers and TypeLocs.
8963/// @{
8964template <typename T>
8965ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8966 return ast_type_traits::DynTypedNode::create(*Node);
8967}
8968template <>
8969ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8970 return ast_type_traits::DynTypedNode::create(Node);
8971}
8972template <>
8973ast_type_traits::DynTypedNode
8974createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8975 return ast_type_traits::DynTypedNode::create(Node);
8976}
8977/// @}
8978
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008979 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8980 /// parents as defined by the \c RecursiveASTVisitor.
8981 ///
8982 /// Note that the relationship described here is purely in terms of AST
8983 /// traversal - there are other relationships (for example declaration context)
8984 /// in the AST that are better modeled by special matchers.
8985 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008986 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008987 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008988 public:
8989 /// \brief Builds and returns the translation unit's parent map.
8990 ///
8991 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008992 static std::pair<ASTContext::ParentMapPointers *,
8993 ASTContext::ParentMapOtherNodes *>
8994 buildMap(TranslationUnitDecl &TU) {
8995 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8996 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008997 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008998 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008999 }
9000
9001 private:
9002 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9003
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009004 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9005 ASTContext::ParentMapOtherNodes *OtherParents)
9006 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009007
9008 bool shouldVisitTemplateInstantiations() const {
9009 return true;
9010 }
9011 bool shouldVisitImplicitCode() const {
9012 return true;
9013 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009014
Richard Smith85838722015-11-24 03:09:01 +00009015 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9016 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009017 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009018 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009019 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009020 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009021 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009022 // FIXME: Currently we add the same parent multiple times, but only
9023 // when no memoization data is available for the type.
9024 // For example when we visit all subexpressions of template
9025 // instantiations; this is suboptimal, but benign: the only way to
9026 // visit those is with hasAncestor / hasParent, and those do not create
9027 // new matches.
9028 // The plan is to enable DynTypedNode to be storable in a map or hash
9029 // map. The main problem there is to implement hash functions /
9030 // comparison operators for all types that DynTypedNode supports that
9031 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009032 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009033 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009034 if (const auto *D = ParentStack.back().get<Decl>())
9035 NodeOrVector = D;
9036 else if (const auto *S = ParentStack.back().get<Stmt>())
9037 NodeOrVector = S;
9038 else
9039 NodeOrVector =
9040 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009041 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009042 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9043 auto *Vector = new ASTContext::ParentVector(
9044 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009045 if (auto *Node =
9046 NodeOrVector
9047 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9048 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009049 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009050 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009051
9052 auto *Vector =
9053 NodeOrVector.template get<ASTContext::ParentVector *>();
9054 // Skip duplicates for types that have memoization data.
9055 // We must check that the type has memoization data before calling
9056 // std::find() because DynTypedNode::operator== can't compare all
9057 // types.
9058 bool Found = ParentStack.back().getMemoizationData() &&
9059 std::find(Vector->begin(), Vector->end(),
9060 ParentStack.back()) != Vector->end();
9061 if (!Found)
9062 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009063 }
9064 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009065 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009066 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009067 ParentStack.pop_back();
9068 return Result;
9069 }
9070
9071 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009072 return TraverseNode(DeclNode, DeclNode,
9073 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009074 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009075 }
9076
9077 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009078 return TraverseNode(StmtNode, StmtNode,
9079 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009080 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009081 }
9082
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009083 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009084 return TraverseNode(
9085 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9086 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9087 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009088 }
9089
9090 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9091 return TraverseNode(
9092 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009093 [&] {
9094 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9095 },
9096 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009097 }
9098
9099 ASTContext::ParentMapPointers *Parents;
9100 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009101 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9102
9103 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9104 };
9105
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009106} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009107
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009108template <typename NodeTy, typename MapTy>
9109static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9110 const MapTy &Map) {
9111 auto I = Map.find(Node);
9112 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009113 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009114 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009115 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009116 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009117 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009118 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009119}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009120
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009121ASTContext::DynTypedNodeList
9122ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9123 if (!PointerParents) {
9124 // We always need to run over the whole translation unit, as
9125 // hasAncestor can escape any subtree.
9126 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9127 PointerParents.reset(Maps.first);
9128 OtherParents.reset(Maps.second);
9129 }
9130 if (Node.getNodeKind().hasPointerIdentity())
9131 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9132 return getDynNodeFromMap(Node, *OtherParents);
9133}
9134
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009135bool
9136ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9137 const ObjCMethodDecl *MethodImpl) {
9138 // No point trying to match an unavailable/deprecated mothod.
9139 if (MethodDecl->hasAttr<UnavailableAttr>()
9140 || MethodDecl->hasAttr<DeprecatedAttr>())
9141 return false;
9142 if (MethodDecl->getObjCDeclQualifier() !=
9143 MethodImpl->getObjCDeclQualifier())
9144 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009145 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009146 return false;
9147
9148 if (MethodDecl->param_size() != MethodImpl->param_size())
9149 return false;
9150
9151 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9152 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9153 EF = MethodDecl->param_end();
9154 IM != EM && IF != EF; ++IM, ++IF) {
9155 const ParmVarDecl *DeclVar = (*IF);
9156 const ParmVarDecl *ImplVar = (*IM);
9157 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9158 return false;
9159 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9160 return false;
9161 }
9162 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9163
9164}
Richard Smith053f6c62014-05-16 23:01:30 +00009165
9166// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9167// doesn't include ASTContext.h
9168template
9169clang::LazyGenerationalUpdatePtr<
9170 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9171clang::LazyGenerationalUpdatePtr<
9172 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9173 const clang::ASTContext &Ctx, Decl *Value);