blob: fbc8874e93e5fe6b522e5f3fca9132cc9a6e81b8 [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 {
Sjoerd Meijer9aeedde2017-09-08 10:20:52 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000635 ExpandedTypes,
636 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000656 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000657
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000661 TTP->getPosition(),
662 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000663 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000666 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000667 SourceLocation(),
668 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000672 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
Charles Davis53c59df2010-08-16 03:33:14 +0000681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000682 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000687 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000688 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000689 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000690 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000693 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000694 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000695 return CreateMicrosoftCXXABI(*this);
696 }
David Blaikie8a40f702012-01-17 06:56:22 +0000697 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000698}
699
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000706 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000708 3, // opencl_local
709 2, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000710 4, // opencl_generic
711 5, // cuda_device
712 6, // cuda_constant
713 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000714 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000715 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000716 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000717 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000718 }
719}
720
David Tweed31d09b02013-09-13 12:04:22 +0000721static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
722 const LangOptions &LangOpts) {
723 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000724 case LangOptions::ASMM_Target:
725 return TI.useAddressSpaceMapMangling();
726 case LangOptions::ASMM_On:
727 return true;
728 case LangOptions::ASMM_Off:
729 return false;
730 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000731 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000732}
733
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000734ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000735 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000736 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000737 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
738 DependentTemplateSpecializationTypes(this_()),
739 SubstTemplateTemplateParmPacks(this_()),
740 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000741 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
742 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
743 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000744 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
745 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
746 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
747 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
748 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000749 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
750 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000751 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000752 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
753 LangOpts.XRayNeverInstrumentFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000754 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
755 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
756 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
757 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000758 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000759 TUDecl = TranslationUnitDecl::Create(*this);
760}
761
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000762ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000763 ReleaseParentMapEntries();
764
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000765 // Release the DenseMaps associated with DeclContext objects.
766 // FIXME: Is this the ideal solution?
767 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000768
Manuel Klimeka7328992013-06-03 13:51:33 +0000769 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000770 for (auto &Pair : Deallocations)
771 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000774 // because they can contain DenseMaps.
775 for (llvm::DenseMap<const ObjCContainerDecl*,
776 const ASTRecordLayout*>::iterator
777 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781
Ted Kremenek076baeb2010-06-08 23:00:58 +0000782 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
783 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
784 // Increment in loop to prevent using deallocated memory.
785 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
786 R->Destroy(*this);
787 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000788
789 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
790 AEnd = DeclAttrs.end();
791 A != AEnd; ++A)
792 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000793
David Majnemere694f3e2015-08-14 14:43:50 +0000794 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
795 MaterializedTemporaryValues)
796 MTVPair.second->~APValue();
797
Richard Smith423f46f2016-07-20 21:38:26 +0000798 for (const auto &Value : ModuleInitializers)
799 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000800}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000801
Manuel Klimek95403e62014-05-21 13:28:59 +0000802void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000803 if (!PointerParents) return;
804 for (const auto &Entry : *PointerParents) {
805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
806 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
807 } else if (Entry.second.is<ParentVector *>()) {
808 delete Entry.second.get<ParentVector *>();
809 }
810 }
811 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000812 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
813 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000814 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000815 delete Entry.second.get<ParentVector *>();
816 }
817 }
818}
819
Douglas Gregor1a809332010-05-23 18:26:36 +0000820void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000821 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000822}
823
Mike Stump11289f42009-09-09 15:08:12 +0000824void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000825ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000826 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000827}
828
Chris Lattner4eb445d2007-01-26 01:27:23 +0000829void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << "\n*** AST Context Stats:\n";
831 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000832
Douglas Gregora30d0462009-05-26 14:40:08 +0000833 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000834#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000835#define ABSTRACT_TYPE(Name, Parent)
836#include "clang/AST/TypeNodes.def"
837 0 // Extra
838 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000839
Chris Lattner4eb445d2007-01-26 01:27:23 +0000840 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
841 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000843 }
844
Douglas Gregora30d0462009-05-26 14:40:08 +0000845 unsigned Idx = 0;
846 unsigned TotalBytes = 0;
847#define TYPE(Name, Parent) \
848 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000849 llvm::errs() << " " << counts[Idx] << " " << #Name \
850 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000851 TotalBytes += counts[Idx] * sizeof(Name##Type); \
852 ++Idx;
853#define ABSTRACT_TYPE(Name, Parent)
854#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000855
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
857
Douglas Gregor7454c562010-07-02 20:37:36 +0000858 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000859 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
860 << NumImplicitDefaultConstructors
861 << " implicit default constructors created\n";
862 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
863 << NumImplicitCopyConstructors
864 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000865 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000866 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
867 << NumImplicitMoveConstructors
868 << " implicit move constructors created\n";
869 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
870 << NumImplicitCopyAssignmentOperators
871 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000872 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000873 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
874 << NumImplicitMoveAssignmentOperators
875 << " implicit move assignment operators created\n";
876 llvm::errs() << NumImplicitDestructorsDeclared << "/"
877 << NumImplicitDestructors
878 << " implicit destructors created\n";
879
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000880 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000881 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000882 ExternalSource->PrintStats();
883 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000884
Douglas Gregor5b11d492010-07-25 17:53:33 +0000885 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000886}
887
Richard Smith42413142015-05-15 20:05:43 +0000888void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
889 bool NotifyListeners) {
890 if (NotifyListeners)
891 if (auto *Listener = getASTMutationListener())
892 Listener->RedefinedHiddenDefinition(ND, M);
893
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000894 if (getLangOpts().ModulesLocalVisibility)
895 MergedDefModules[ND].push_back(M);
896 else
Richard Smith90dc5252017-06-23 01:04:34 +0000897 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000898}
899
900void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
901 auto It = MergedDefModules.find(ND);
902 if (It == MergedDefModules.end())
903 return;
904
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000905 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000906 llvm::DenseSet<Module*> Found;
907 for (Module *&M : Merged)
908 if (!Found.insert(M).second)
909 M = nullptr;
910 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
911}
912
Richard Smithdc1f0422016-07-20 19:10:16 +0000913void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
914 if (LazyInitializers.empty())
915 return;
916
917 auto *Source = Ctx.getExternalSource();
918 assert(Source && "lazy initializers but no external source");
919
920 auto LazyInits = std::move(LazyInitializers);
921 LazyInitializers.clear();
922
923 for (auto ID : LazyInits)
924 Initializers.push_back(Source->GetExternalDecl(ID));
925
926 assert(LazyInitializers.empty() &&
927 "GetExternalDecl for lazy module initializer added more inits");
928}
929
930void ASTContext::addModuleInitializer(Module *M, Decl *D) {
931 // One special case: if we add a module initializer that imports another
932 // module, and that module's only initializer is an ImportDecl, simplify.
933 if (auto *ID = dyn_cast<ImportDecl>(D)) {
934 auto It = ModuleInitializers.find(ID->getImportedModule());
935
936 // Maybe the ImportDecl does nothing at all. (Common case.)
937 if (It == ModuleInitializers.end())
938 return;
939
940 // Maybe the ImportDecl only imports another ImportDecl.
941 auto &Imported = *It->second;
942 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
943 Imported.resolve(*this);
944 auto *OnlyDecl = Imported.Initializers.front();
945 if (isa<ImportDecl>(OnlyDecl))
946 D = OnlyDecl;
947 }
948 }
949
950 auto *&Inits = ModuleInitializers[M];
951 if (!Inits)
952 Inits = new (*this) PerModuleInitializers;
953 Inits->Initializers.push_back(D);
954}
955
956void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
957 auto *&Inits = ModuleInitializers[M];
958 if (!Inits)
959 Inits = new (*this) PerModuleInitializers;
960 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
961 IDs.begin(), IDs.end());
962}
963
964ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
965 auto It = ModuleInitializers.find(M);
966 if (It == ModuleInitializers.end())
967 return None;
968
969 auto *Inits = It->second;
970 Inits->resolve(*this);
971 return Inits->Initializers;
972}
973
Richard Smithf19e1272015-03-07 00:04:49 +0000974ExternCContextDecl *ASTContext::getExternCContextDecl() const {
975 if (!ExternCContext)
976 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
977
978 return ExternCContext;
979}
980
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000981BuiltinTemplateDecl *
982ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
983 const IdentifierInfo *II) const {
984 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
985 BuiltinTemplate->setImplicit();
986 TUDecl->addDecl(BuiltinTemplate);
987
988 return BuiltinTemplate;
989}
990
991BuiltinTemplateDecl *
992ASTContext::getMakeIntegerSeqDecl() const {
993 if (!MakeIntegerSeqDecl)
994 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
995 getMakeIntegerSeqName());
996 return MakeIntegerSeqDecl;
997}
998
Eric Fiselier6ad68552016-07-01 01:24:09 +0000999BuiltinTemplateDecl *
1000ASTContext::getTypePackElementDecl() const {
1001 if (!TypePackElementDecl)
1002 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1003 getTypePackElementName());
1004 return TypePackElementDecl;
1005}
1006
Alp Toker2dea15b2013-12-17 01:22:38 +00001007RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1008 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001009 SourceLocation Loc;
1010 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001011 if (getLangOpts().CPlusPlus)
1012 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1013 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001015 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1016 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001017 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001018 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1019 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001020 return NewDecl;
1021}
1022
1023TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1024 StringRef Name) const {
1025 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1026 TypedefDecl *NewDecl = TypedefDecl::Create(
1027 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1028 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1029 NewDecl->setImplicit();
1030 return NewDecl;
1031}
1032
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001034 if (!Int128Decl)
1035 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001036 return Int128Decl;
1037}
1038
1039TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001040 if (!UInt128Decl)
1041 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001042 return UInt128Decl;
1043}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001044
John McCall48f2d582009-10-23 23:03:21 +00001045void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001046 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001047 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001048 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001049}
1050
Artem Belevichb5bc9232015-09-22 17:23:22 +00001051void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1052 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001053 assert((!this->Target || this->Target == &Target) &&
1054 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001055 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001056
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001058 this->AuxTarget = AuxTarget;
1059
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060 ABI.reset(createCXXABI(Target));
1061 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001062 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001063
Chris Lattner970e54e2006-11-12 00:37:36 +00001064 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001065 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattner970e54e2006-11-12 00:37:36 +00001067 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001068 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001069 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001070 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001071 InitBuiltinType(CharTy, BuiltinType::Char_S);
1072 else
1073 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001074 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001075 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1076 InitBuiltinType(ShortTy, BuiltinType::Short);
1077 InitBuiltinType(IntTy, BuiltinType::Int);
1078 InitBuiltinType(LongTy, BuiltinType::Long);
1079 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner970e54e2006-11-12 00:37:36 +00001081 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001082 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1083 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1084 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1085 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1086 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001087
Chris Lattner970e54e2006-11-12 00:37:36 +00001088 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001089 InitBuiltinType(FloatTy, BuiltinType::Float);
1090 InitBuiltinType(DoubleTy, BuiltinType::Double);
1091 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001092
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001093 // GNU extension, __float128 for IEEE quadruple precision
1094 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1095
Chris Lattnerf122cef2009-04-30 02:43:43 +00001096 // GNU extension, 128-bit integers.
1097 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1098 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1099
Hans Wennborg0d81e012013-05-10 10:08:40 +00001100 // C++ 3.9.1p5
1101 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1102 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1103 else // -fshort-wchar makes wchar_t be unsigned.
1104 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1105 if (LangOpts.CPlusPlus && LangOpts.WChar)
1106 WideCharTy = WCharTy;
1107 else {
1108 // C99 (or C++ using -fno-wchar).
1109 WideCharTy = getFromTargetType(Target.getWCharType());
1110 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001111
James Molloy36365542012-05-04 10:55:22 +00001112 WIntTy = getFromTargetType(Target.getWIntType());
1113
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001114 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1115 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1116 else // C99
1117 Char16Ty = getFromTargetType(Target.getChar16Type());
1118
1119 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1120 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1121 else // C99
1122 Char32Ty = getFromTargetType(Target.getChar32Type());
1123
Douglas Gregor4619e432008-12-05 23:32:09 +00001124 // Placeholder type for type-dependent expressions whose type is
1125 // completely unknown. No code should ever check a type against
1126 // DependentTy and users should never see it; however, it is here to
1127 // help diagnose failures to properly check for type-dependent
1128 // expressions.
1129 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130
John McCall36e7fe32010-10-12 00:20:44 +00001131 // Placeholder type for functions.
1132 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1133
John McCall0009fcc2011-04-26 20:42:42 +00001134 // Placeholder type for bound members.
1135 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1136
John McCall526ab472011-10-25 17:37:35 +00001137 // Placeholder type for pseudo-objects.
1138 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1139
John McCall31996342011-04-07 08:22:57 +00001140 // "any" type; useful for debugger-like clients.
1141 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1142
John McCall8a6b59a2011-10-17 18:09:15 +00001143 // Placeholder type for unbridged ARC casts.
1144 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1145
Eli Friedman34866c72012-08-31 00:14:07 +00001146 // Placeholder type for builtin functions.
1147 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1148
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001149 // Placeholder type for OMP array sections.
1150 if (LangOpts.OpenMP)
1151 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1152
Chris Lattner970e54e2006-11-12 00:37:36 +00001153 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001154 FloatComplexTy = getComplexType(FloatTy);
1155 DoubleComplexTy = getComplexType(DoubleTy);
1156 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001157 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001159 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001160 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1161 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001162 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001163
Alexey Bader954ba212016-04-08 13:40:33 +00001164 if (LangOpts.OpenCL) {
1165#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1166 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001167#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001168
Guy Benyei61054192013-02-07 10:55:47 +00001169 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001170 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001171 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1172 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001173 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001174 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001175
1176 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001177 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1178 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001179
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001180 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001181
1182 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001183
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001184 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001185 if (LangOpts.OpenCLVersion >= 200) {
1186 auto Q = VoidTy.getQualifiers();
1187 Q.setAddressSpace(LangAS::opencl_generic);
1188 VoidPtrTy = getPointerType(getCanonicalType(
1189 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1190 } else {
1191 VoidPtrTy = getPointerType(VoidTy);
1192 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001193
1194 // nullptr type (C++0x 2.14.7)
1195 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001196
1197 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1198 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001199
1200 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001201 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001202}
1203
David Blaikie9c902b52011-09-25 23:23:43 +00001204DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001205 return SourceMgr.getDiagnostics();
1206}
1207
Douglas Gregor561eceb2010-08-30 16:49:28 +00001208AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1209 AttrVec *&Result = DeclAttrs[D];
1210 if (!Result) {
1211 void *Mem = Allocate(sizeof(AttrVec));
1212 Result = new (Mem) AttrVec;
1213 }
1214
1215 return *Result;
1216}
1217
1218/// \brief Erase the attributes corresponding to the given declaration.
1219void ASTContext::eraseDeclAttrs(const Decl *D) {
1220 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1221 if (Pos != DeclAttrs.end()) {
1222 Pos->second->~AttrVec();
1223 DeclAttrs.erase(Pos);
1224 }
1225}
1226
Larisse Voufo39a1e502013-08-06 01:03:05 +00001227// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001228MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001229ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001230 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001231 return getTemplateOrSpecializationInfo(Var)
1232 .dyn_cast<MemberSpecializationInfo *>();
1233}
1234
1235ASTContext::TemplateOrSpecializationInfo
1236ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1237 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1238 TemplateOrInstantiation.find(Var);
1239 if (Pos == TemplateOrInstantiation.end())
1240 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001241
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001242 return Pos->second;
1243}
1244
Mike Stump11289f42009-09-09 15:08:12 +00001245void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001246ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001247 TemplateSpecializationKind TSK,
1248 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001249 assert(Inst->isStaticDataMember() && "Not a static data member");
1250 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001251 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1252 Tmpl, TSK, PointOfInstantiation));
1253}
1254
1255void
1256ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1257 TemplateOrSpecializationInfo TSI) {
1258 assert(!TemplateOrInstantiation[Inst] &&
1259 "Already noted what the variable was instantiated from");
1260 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001261}
1262
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001263FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1264 const FunctionDecl *FD){
1265 assert(FD && "Specialization is 0");
1266 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001267 = ClassScopeSpecializationPattern.find(FD);
1268 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001269 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001270
1271 return Pos->second;
1272}
1273
1274void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1275 FunctionDecl *Pattern) {
1276 assert(FD && "Specialization is 0");
1277 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001278 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001279}
1280
John McCalle61f2ba2009-11-18 02:36:19 +00001281NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001282ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1283 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001284 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001285 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001286
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001287 return Pos->second;
1288}
1289
1290void
Richard Smithd8a9e372016-12-18 21:39:37 +00001291ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001292 assert((isa<UsingDecl>(Pattern) ||
1293 isa<UnresolvedUsingValueDecl>(Pattern) ||
1294 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1295 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001296 assert((isa<UsingDecl>(Inst) ||
1297 isa<UnresolvedUsingValueDecl>(Inst) ||
1298 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1299 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001300 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1301 InstantiatedFromUsingDecl[Inst] = Pattern;
1302}
1303
1304UsingShadowDecl *
1305ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1306 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1307 = InstantiatedFromUsingShadowDecl.find(Inst);
1308 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001309 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001310
1311 return Pos->second;
1312}
1313
1314void
1315ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1316 UsingShadowDecl *Pattern) {
1317 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1318 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001319}
1320
Anders Carlsson5da84842009-09-01 04:26:58 +00001321FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1322 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1323 = InstantiatedFromUnnamedFieldDecl.find(Field);
1324 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001325 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001326
Anders Carlsson5da84842009-09-01 04:26:58 +00001327 return Pos->second;
1328}
1329
1330void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1331 FieldDecl *Tmpl) {
1332 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1333 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1334 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1335 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001336
Anders Carlsson5da84842009-09-01 04:26:58 +00001337 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1338}
1339
Douglas Gregor832940b2010-03-02 23:58:15 +00001340ASTContext::overridden_cxx_method_iterator
1341ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001342 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1343 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001344 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001345 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001346 return Pos->second.begin();
1347}
1348
1349ASTContext::overridden_cxx_method_iterator
1350ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001351 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1352 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001353 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001354 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001355 return Pos->second.end();
1356}
1357
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001358unsigned
1359ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001360 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1361 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001362 if (Pos == OverriddenMethods.end())
1363 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001364 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001365}
1366
Clement Courbet6ecaec82016-07-05 07:49:31 +00001367ASTContext::overridden_method_range
1368ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1369 return overridden_method_range(overridden_methods_begin(Method),
1370 overridden_methods_end(Method));
1371}
1372
Douglas Gregor832940b2010-03-02 23:58:15 +00001373void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1374 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001375 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001376 OverriddenMethods[Method].push_back(Overridden);
1377}
1378
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001379void ASTContext::getOverriddenMethods(
1380 const NamedDecl *D,
1381 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001382 assert(D);
1383
1384 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001385 Overridden.append(overridden_methods_begin(CXXMethod),
1386 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001387 return;
1388 }
1389
1390 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1391 if (!Method)
1392 return;
1393
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001394 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1395 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001396 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001397}
1398
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001399void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1400 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1401 assert(!Import->isFromASTFile() && "Non-local import declaration");
1402 if (!FirstLocalImport) {
1403 FirstLocalImport = Import;
1404 LastLocalImport = Import;
1405 return;
1406 }
1407
1408 LastLocalImport->NextLocalImport = Import;
1409 LastLocalImport = Import;
1410}
1411
Chris Lattner53cfe802007-07-18 17:52:12 +00001412//===----------------------------------------------------------------------===//
1413// Type Sizing and Analysis
1414//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001415
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001416/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1417/// scalar floating point type.
1418const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001419 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001420 assert(BT && "Not a floating point type!");
1421 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001422 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijer9aeedde2017-09-08 10:20:52 +00001423 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001424 case BuiltinType::Float: return Target->getFloatFormat();
1425 case BuiltinType::Double: return Target->getDoubleFormat();
1426 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001427 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001428 }
1429}
1430
Rafael Espindola71eccb32013-08-08 19:53:46 +00001431CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001432 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001433
John McCall94268702010-10-08 18:24:19 +00001434 bool UseAlignAttrOnly = false;
1435 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1436 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001437
John McCall94268702010-10-08 18:24:19 +00001438 // __attribute__((aligned)) can increase or decrease alignment
1439 // *except* on a struct or struct member, where it only increases
1440 // alignment unless 'packed' is also specified.
1441 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001442 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001443 // ignore that possibility; Sema should diagnose it.
1444 if (isa<FieldDecl>(D)) {
1445 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1446 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1447 } else {
1448 UseAlignAttrOnly = true;
1449 }
1450 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001451 else if (isa<FieldDecl>(D))
1452 UseAlignAttrOnly =
1453 D->hasAttr<PackedAttr>() ||
1454 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001455
John McCall4e819612011-01-20 07:57:12 +00001456 // If we're using the align attribute only, just ignore everything
1457 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001458 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001459 // do nothing
1460
John McCall94268702010-10-08 18:24:19 +00001461 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001462 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001463 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001464 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001465 T = RT->getPointeeType();
1466 else
1467 T = getPointerType(RT->getPointeeType());
1468 }
Richard Smithf6d70302014-06-10 23:34:28 +00001469 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001470 if (T->isFunctionType())
1471 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1472 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001473 // Adjust alignments of declarations with array type by the
1474 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001475 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001476 unsigned MinWidth = Target->getLargeArrayMinWidth();
1477 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001478 if (isa<VariableArrayType>(arrayType))
1479 Align = std::max(Align, Target->getLargeArrayAlign());
1480 else if (isa<ConstantArrayType>(arrayType) &&
1481 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1482 Align = std::max(Align, Target->getLargeArrayAlign());
1483 }
John McCall33ddac02011-01-19 10:06:00 +00001484 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001485 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001486 if (BaseT.getQualifiers().hasUnaligned())
1487 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001488 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001489 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001490 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1491 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001492 }
John McCall4e819612011-01-20 07:57:12 +00001493
1494 // Fields can be subject to extra alignment constraints, like if
1495 // the field is packed, the struct is packed, or the struct has a
1496 // a max-field-alignment constraint (#pragma pack). So calculate
1497 // the actual alignment of the field within the struct, and then
1498 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001499 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1500 const RecordDecl *Parent = Field->getParent();
1501 // We can only produce a sensible answer if the record is valid.
1502 if (!Parent->isInvalidDecl()) {
1503 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001504
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001505 // Start with the record's overall alignment.
1506 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001507
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001508 // Use the GCD of that and the offset within the record.
1509 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1510 if (Offset > 0) {
1511 // Alignment is always a power of 2, so the GCD will be a power of 2,
1512 // which means we get to do this crazy thing instead of Euclid's.
1513 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1514 if (LowBitOfOffset < FieldAlign)
1515 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1516 }
1517
1518 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001519 }
Charles Davis3fc51072010-02-23 04:52:00 +00001520 }
Chris Lattner68061312009-01-24 21:53:27 +00001521 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001522
Ken Dyckcc56c542011-01-15 18:38:59 +00001523 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001524}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001525
John McCallf1249922012-08-21 04:10:00 +00001526// getTypeInfoDataSizeInChars - Return the size of a type, in
1527// chars. If the type is a record, its data size is returned. This is
1528// the size of the memcpy that's performed when assigning this type
1529// using a trivial copy/move assignment operator.
1530std::pair<CharUnits, CharUnits>
1531ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1532 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1533
1534 // In C++, objects can sometimes be allocated into the tail padding
1535 // of a base-class subobject. We decide whether that's possible
1536 // during class layout, so here we can just trust the layout results.
1537 if (getLangOpts().CPlusPlus) {
1538 if (const RecordType *RT = T->getAs<RecordType>()) {
1539 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1540 sizeAndAlign.first = layout.getDataSize();
1541 }
1542 }
1543
1544 return sizeAndAlign;
1545}
1546
Richard Trieu04d2d942013-05-14 21:59:17 +00001547/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1548/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1549std::pair<CharUnits, CharUnits>
1550static getConstantArrayInfoInChars(const ASTContext &Context,
1551 const ConstantArrayType *CAT) {
1552 std::pair<CharUnits, CharUnits> EltInfo =
1553 Context.getTypeInfoInChars(CAT->getElementType());
1554 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001555 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1556 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001557 "Overflow in array type char size evaluation");
1558 uint64_t Width = EltInfo.first.getQuantity() * Size;
1559 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001560 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1561 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001562 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001563 return std::make_pair(CharUnits::fromQuantity(Width),
1564 CharUnits::fromQuantity(Align));
1565}
1566
John McCall87fe5d52010-05-20 01:18:31 +00001567std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001568ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001569 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1570 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001571 TypeInfo Info = getTypeInfo(T);
1572 return std::make_pair(toCharUnitsFromBits(Info.Width),
1573 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001574}
1575
1576std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001577ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001578 return getTypeInfoInChars(T.getTypePtr());
1579}
1580
David Majnemer34b57492014-07-30 01:30:47 +00001581bool ASTContext::isAlignmentRequired(const Type *T) const {
1582 return getTypeInfo(T).AlignIsRequired;
1583}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001584
David Majnemer34b57492014-07-30 01:30:47 +00001585bool ASTContext::isAlignmentRequired(QualType T) const {
1586 return isAlignmentRequired(T.getTypePtr());
1587}
1588
Richard Smithb2f0f052016-10-10 18:54:32 +00001589unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1590 // An alignment on a typedef overrides anything else.
1591 if (auto *TT = T->getAs<TypedefType>())
1592 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1593 return Align;
1594
1595 // If we have an (array of) complete type, we're done.
1596 T = getBaseElementType(T);
1597 if (!T->isIncompleteType())
1598 return getTypeAlign(T);
1599
1600 // If we had an array type, its element type might be a typedef
1601 // type with an alignment attribute.
1602 if (auto *TT = T->getAs<TypedefType>())
1603 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1604 return Align;
1605
1606 // Otherwise, see if the declaration of the type had an attribute.
1607 if (auto *TT = T->getAs<TagType>())
1608 return TT->getDecl()->getMaxAlignment();
1609
1610 return 0;
1611}
1612
David Majnemer34b57492014-07-30 01:30:47 +00001613TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001614 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1615 if (I != MemoizedTypeInfo.end())
1616 return I->second;
1617
1618 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1619 TypeInfo TI = getTypeInfoImpl(T);
1620 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001621 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001622}
1623
1624/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1625/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001626///
1627/// FIXME: Pointers into different addr spaces could have different sizes and
1628/// alignment requirements: getPointerInfo should take an AddrSpace, this
1629/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001630TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1631 uint64_t Width = 0;
1632 unsigned Align = 8;
1633 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001634 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001635 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001636#define TYPE(Class, Base)
1637#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001638#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001639#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001640#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1641 case Type::Class: \
1642 assert(!T->isDependentType() && "should not see dependent types here"); \
1643 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001644#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001645 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001646
Chris Lattner355332d2007-07-13 22:27:08 +00001647 case Type::FunctionNoProto:
1648 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001649 // GCC extension: alignof(function) = 32 bits
1650 Width = 0;
1651 Align = 32;
1652 break;
1653
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001654 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001655 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001656 Width = 0;
1657 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1658 break;
1659
Steve Naroff5c131802007-08-30 01:06:46 +00001660 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001661 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001662
David Majnemer34b57492014-07-30 01:30:47 +00001663 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001664 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001665 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001666 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001667 Width = EltInfo.Width * Size;
1668 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001669 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1670 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001671 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001672 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001673 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001674 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001675 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001676 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001677 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1678 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001679 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001680 // If the alignment is not a power of 2, round up to the next power of 2.
1681 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001682 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001683 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001684 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001685 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001686 // Adjust the alignment based on the target max.
1687 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1688 if (TargetVectorAlign && TargetVectorAlign < Align)
1689 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001690 break;
1691 }
Chris Lattner647fb222007-07-18 18:26:58 +00001692
Chris Lattner7570e9c2008-03-08 08:52:55 +00001693 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001694 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001695 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001696 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001697 // GCC extension: alignof(void) = 8 bits.
1698 Width = 0;
1699 Align = 8;
1700 break;
1701
Chris Lattner6a4f7452007-12-19 19:23:28 +00001702 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001703 Width = Target->getBoolWidth();
1704 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001705 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001706 case BuiltinType::Char_S:
1707 case BuiltinType::Char_U:
1708 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001709 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001710 Width = Target->getCharWidth();
1711 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001712 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001713 case BuiltinType::WChar_S:
1714 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001715 Width = Target->getWCharWidth();
1716 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001717 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001718 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001719 Width = Target->getChar16Width();
1720 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001721 break;
1722 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001723 Width = Target->getChar32Width();
1724 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001725 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001726 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001727 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001728 Width = Target->getShortWidth();
1729 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001730 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001731 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001732 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001733 Width = Target->getIntWidth();
1734 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001735 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001736 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001737 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001738 Width = Target->getLongWidth();
1739 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001740 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001741 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001742 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001743 Width = Target->getLongLongWidth();
1744 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001745 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001746 case BuiltinType::Int128:
1747 case BuiltinType::UInt128:
1748 Width = 128;
1749 Align = 128; // int128_t is 128-bit aligned on all targets.
1750 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001751 case BuiltinType::Half:
1752 Width = Target->getHalfWidth();
1753 Align = Target->getHalfAlign();
1754 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001755 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001756 Width = Target->getFloatWidth();
1757 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001758 break;
1759 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001760 Width = Target->getDoubleWidth();
1761 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001762 break;
1763 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001764 Width = Target->getLongDoubleWidth();
1765 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001766 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001767 case BuiltinType::Float128:
1768 Width = Target->getFloat128Width();
1769 Align = Target->getFloat128Align();
1770 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001771 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001772 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1773 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001774 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001775 case BuiltinType::ObjCId:
1776 case BuiltinType::ObjCClass:
1777 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001778 Width = Target->getPointerWidth(0);
1779 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001780 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001781 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001782 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001783 case BuiltinType::OCLClkEvent:
1784 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001785 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001786#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1787 case BuiltinType::Id:
1788#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001789 AS = getTargetAddressSpace(Target->getOpenCLTypeAddrSpace(T));
1790 Width = Target->getPointerWidth(AS);
1791 Align = Target->getPointerAlign(AS);
1792 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001793 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001794 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001795 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001796 Width = Target->getPointerWidth(0);
1797 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001798 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001799 case Type::BlockPointer: {
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001800 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001801 Width = Target->getPointerWidth(AS);
1802 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001803 break;
1804 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001805 case Type::LValueReference:
1806 case Type::RValueReference: {
1807 // alignof and sizeof should never enter this code path here, so we go
1808 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001809 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001810 Width = Target->getPointerWidth(AS);
1811 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001812 break;
1813 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001814 case Type::Pointer: {
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001815 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001816 Width = Target->getPointerWidth(AS);
1817 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001818 break;
1819 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001820 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001821 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001822 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001823 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001824 }
Chris Lattner647fb222007-07-18 18:26:58 +00001825 case Type::Complex: {
1826 // Complex types have the same alignment as their elements, but twice the
1827 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001828 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1829 Width = EltInfo.Width * 2;
1830 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001831 break;
1832 }
John McCall8b07ec22010-05-15 11:32:37 +00001833 case Type::ObjCObject:
1834 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001835 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001836 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001837 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001838 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001839 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001840 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001841 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001842 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001843 break;
1844 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001845 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001846 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001847 const TagType *TT = cast<TagType>(T);
1848
1849 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001850 Width = 8;
1851 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001852 break;
1853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
David Majnemer475b25e2015-01-21 10:54:38 +00001855 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1856 const EnumDecl *ED = ET->getDecl();
1857 TypeInfo Info =
1858 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1859 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1860 Info.Align = AttrAlign;
1861 Info.AlignIsRequired = true;
1862 }
1863 return Info;
1864 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001865
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001866 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001867 const RecordDecl *RD = RT->getDecl();
1868 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001869 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001870 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001871 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001872 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001873 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001874
Chris Lattner63d2b362009-10-22 05:17:15 +00001875 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001876 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1877 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001878
Richard Smith600b5262017-01-26 20:40:47 +00001879 case Type::Auto:
1880 case Type::DeducedTemplateSpecialization: {
1881 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001882 assert(!A->getDeducedType().isNull() &&
1883 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001884 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001885 }
1886
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001887 case Type::Paren:
1888 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1889
Manman Rene6be26c2016-09-13 17:25:08 +00001890 case Type::ObjCTypeParam:
1891 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1892
Douglas Gregoref462e62009-04-30 17:32:17 +00001893 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001894 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001895 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001896 // If the typedef has an aligned attribute on it, it overrides any computed
1897 // alignment we have. This violates the GCC documentation (which says that
1898 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001899 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001900 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001901 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001902 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001903 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001904 AlignIsRequired = Info.AlignIsRequired;
1905 }
David Majnemer34b57492014-07-30 01:30:47 +00001906 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001907 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001908 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001909
Abramo Bagnara6150c882010-05-11 21:36:43 +00001910 case Type::Elaborated:
1911 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001912
John McCall81904512011-01-06 01:58:22 +00001913 case Type::Attributed:
1914 return getTypeInfo(
1915 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1916
Eli Friedman0dfb8892011-10-06 23:00:33 +00001917 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001918 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001919 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1920 Width = Info.Width;
1921 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001922
1923 // If the size of the type doesn't exceed the platform's max
1924 // atomic promotion width, make the size and alignment more
1925 // favorable to atomic operations:
1926 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1927 // Round the size up to a power of 2.
1928 if (!llvm::isPowerOf2_64(Width))
1929 Width = llvm::NextPowerOf2(Width);
1930
1931 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001932 Align = static_cast<unsigned>(Width);
1933 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001934 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001935 break;
1936
1937 case Type::Pipe: {
Anastasia Stulovab3398932017-06-05 11:27:03 +00001938 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1939 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Xiuli Pan9c14e282016-01-09 12:53:17 +00001940 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001941
Douglas Gregoref462e62009-04-30 17:32:17 +00001942 }
Mike Stump11289f42009-09-09 15:08:12 +00001943
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001944 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001945 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001946}
1947
Alexey Bataev00396512015-07-02 03:40:19 +00001948unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1949 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1950 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1951 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1952 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1953 getTargetInfo().getABI() == "elfv1-qpx" &&
1954 T->isSpecificBuiltinType(BuiltinType::Double))
1955 SimdAlign = 256;
1956 return SimdAlign;
1957}
1958
Ken Dyckcc56c542011-01-15 18:38:59 +00001959/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1960CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1961 return CharUnits::fromQuantity(BitSize / getCharWidth());
1962}
1963
Ken Dyckb0fcc592011-02-11 01:54:29 +00001964/// toBits - Convert a size in characters to a size in characters.
1965int64_t ASTContext::toBits(CharUnits CharSize) const {
1966 return CharSize.getQuantity() * getCharWidth();
1967}
1968
Ken Dyck8c89d592009-12-22 14:23:30 +00001969/// getTypeSizeInChars - Return the size of the specified type, in characters.
1970/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001971CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001972 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001973}
Jay Foad39c79802011-01-12 09:06:06 +00001974CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001975 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001976}
1977
Ken Dycka6046ab2010-01-26 17:25:18 +00001978/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001979/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001980CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001981 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001982}
Jay Foad39c79802011-01-12 09:06:06 +00001983CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001984 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001985}
1986
Chris Lattnera3402cd2009-01-27 18:08:34 +00001987/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1988/// type for the current target in bits. This can be different than the ABI
1989/// alignment in cases where it is beneficial for performance to overalign
1990/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001991unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001992 TypeInfo TI = getTypeInfo(T);
1993 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001994
David Majnemere1544562015-04-24 01:25:05 +00001995 T = T->getBaseElementTypeUnsafe();
1996
1997 // The preferred alignment of member pointers is that of a pointer.
1998 if (T->isMemberPointerType())
1999 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2000
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002001 if (!Target->allowsLargerPreferedTypeAlignment())
2002 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002003
Eli Friedman7ab09572009-05-25 21:27:19 +00002004 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002005 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002006 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002007 if (const EnumType *ET = T->getAs<EnumType>())
2008 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002009 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002010 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2011 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002012 // Don't increase the alignment if an alignment attribute was specified on a
2013 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002014 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002015 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002016
Chris Lattnera3402cd2009-01-27 18:08:34 +00002017 return ABIAlign;
2018}
2019
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002020/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2021/// for __attribute__((aligned)) on this target, to be used if no alignment
2022/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002023unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002024 return getTargetInfo().getDefaultAlignForAttributeAligned();
2025}
2026
Ulrich Weigandfa806422013-05-06 16:23:57 +00002027/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2028/// to a global variable of the specified type.
2029unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2030 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2031}
2032
2033/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2034/// should be given to a global variable of the specified type.
2035CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2036 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2037}
2038
David Majnemer08ef2ba2015-06-23 20:34:18 +00002039CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2040 CharUnits Offset = CharUnits::Zero();
2041 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2042 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2043 Offset += Layout->getBaseClassOffset(Base);
2044 Layout = &getASTRecordLayout(Base);
2045 }
2046 return Offset;
2047}
2048
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002049/// DeepCollectObjCIvars -
2050/// This routine first collects all declared, but not synthesized, ivars in
2051/// super class and then collects all ivars, including those synthesized for
2052/// current class. This routine is used for implementation of current class
2053/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002054///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002055void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2056 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002057 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002058 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2059 DeepCollectObjCIvars(SuperClass, false, Ivars);
2060 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002061 for (const auto *I : OI->ivars())
2062 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002063 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002064 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002065 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002066 Iv= Iv->getNextIvar())
2067 Ivars.push_back(Iv);
2068 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002069}
2070
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002071/// CollectInheritedProtocols - Collect all protocols in current class and
2072/// those inherited by it.
2073void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002074 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002075 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002076 // We can use protocol_iterator here instead of
2077 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002078 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002079 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002080 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002081
2082 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002083 for (const auto *Cat : OI->visible_categories())
2084 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002085
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002086 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2087 while (SD) {
2088 CollectInheritedProtocols(SD, Protocols);
2089 SD = SD->getSuperClass();
2090 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002091 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002092 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002093 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002094 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002095 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002096 // Insert the protocol.
2097 if (!Protocols.insert(
2098 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2099 return;
2100
2101 for (auto *Proto : OP->protocols())
2102 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002103 }
2104}
2105
Jay Foad39c79802011-01-12 09:06:06 +00002106unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002107 unsigned count = 0;
2108 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002109 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002110 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002111
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002112 // Count ivar defined in this class's implementation. This
2113 // includes synthesized ivars.
2114 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002115 count += ImplDecl->ivar_size();
2116
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002117 return count;
2118}
2119
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002120bool ASTContext::isSentinelNullExpr(const Expr *E) {
2121 if (!E)
2122 return false;
2123
2124 // nullptr_t is always treated as null.
2125 if (E->getType()->isNullPtrType()) return true;
2126
2127 if (E->getType()->isAnyPointerType() &&
2128 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2129 Expr::NPC_ValueDependentIsNull))
2130 return true;
2131
2132 // Unfortunately, __null has type 'int'.
2133 if (isa<GNUNullExpr>(E)) return true;
2134
2135 return false;
2136}
2137
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002138/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2139ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2140 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2141 I = ObjCImpls.find(D);
2142 if (I != ObjCImpls.end())
2143 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002144 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002145}
2146/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2147ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2148 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2149 I = ObjCImpls.find(D);
2150 if (I != ObjCImpls.end())
2151 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002152 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002153}
2154
2155/// \brief Set the implementation of ObjCInterfaceDecl.
2156void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2157 ObjCImplementationDecl *ImplD) {
2158 assert(IFaceD && ImplD && "Passed null params");
2159 ObjCImpls[IFaceD] = ImplD;
2160}
2161/// \brief Set the implementation of ObjCCategoryDecl.
2162void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2163 ObjCCategoryImplDecl *ImplD) {
2164 assert(CatD && ImplD && "Passed null params");
2165 ObjCImpls[CatD] = ImplD;
2166}
2167
Chandler Carruth21c90602015-12-30 03:24:14 +00002168const ObjCMethodDecl *
2169ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2170 return ObjCMethodRedecls.lookup(MD);
2171}
2172
2173void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2174 const ObjCMethodDecl *Redecl) {
2175 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2176 ObjCMethodRedecls[MD] = Redecl;
2177}
2178
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002179const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2180 const NamedDecl *ND) const {
2181 if (const ObjCInterfaceDecl *ID =
2182 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002183 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002184 if (const ObjCCategoryDecl *CD =
2185 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002186 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002187 if (const ObjCImplDecl *IMD =
2188 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002189 return IMD->getClassInterface();
2190
Craig Topper36250ad2014-05-12 05:36:57 +00002191 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002192}
2193
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002194/// \brief Get the copy initialization expression of VarDecl,or NULL if
2195/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002196Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002197 assert(VD && "Passed null params");
2198 assert(VD->hasAttr<BlocksAttr>() &&
2199 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002200 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002201 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002202 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002203}
2204
2205/// \brief Set the copy inialization expression of a block var decl.
2206void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2207 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002208 assert(VD->hasAttr<BlocksAttr>() &&
2209 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002210 BlockVarCopyInits[VD] = Init;
2211}
2212
John McCallbcd03502009-12-07 02:54:59 +00002213TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002214 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002215 if (!DataSize)
2216 DataSize = TypeLoc::getFullDataSizeForType(T);
2217 else
2218 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002219 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002220
John McCallbcd03502009-12-07 02:54:59 +00002221 TypeSourceInfo *TInfo =
2222 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2223 new (TInfo) TypeSourceInfo(T);
2224 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002225}
2226
John McCallbcd03502009-12-07 02:54:59 +00002227TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002228 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002229 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002230 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002231 return DI;
2232}
2233
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002234const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002235ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002236 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002237}
2238
2239const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002240ASTContext::getASTObjCImplementationLayout(
2241 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002242 return getObjCLayout(D->getClassInterface(), D);
2243}
2244
Chris Lattner983a8bb2007-07-13 22:13:22 +00002245//===----------------------------------------------------------------------===//
2246// Type creation/memoization methods
2247//===----------------------------------------------------------------------===//
2248
Jay Foad39c79802011-01-12 09:06:06 +00002249QualType
John McCall33ddac02011-01-19 10:06:00 +00002250ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2251 unsigned fastQuals = quals.getFastQualifiers();
2252 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002253
2254 // Check if we've already instantiated this type.
2255 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002256 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002257 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002258 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2259 assert(eq->getQualifiers() == quals);
2260 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002261 }
2262
John McCall33ddac02011-01-19 10:06:00 +00002263 // If the base type is not canonical, make the appropriate canonical type.
2264 QualType canon;
2265 if (!baseType->isCanonicalUnqualified()) {
2266 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002267 canonSplit.Quals.addConsistentQualifiers(quals);
2268 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002269
2270 // Re-find the insert position.
2271 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2272 }
2273
2274 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2275 ExtQualNodes.InsertNode(eq, insertPos);
2276 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002277}
2278
Jay Foad39c79802011-01-12 09:06:06 +00002279QualType
2280ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002281 QualType CanT = getCanonicalType(T);
2282 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002283 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002284
John McCall8ccfcb52009-09-24 19:53:00 +00002285 // If we are composing extended qualifiers together, merge together
2286 // into one ExtQuals node.
2287 QualifierCollector Quals;
2288 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002289
John McCall8ccfcb52009-09-24 19:53:00 +00002290 // If this type already has an address space specified, it cannot get
2291 // another one.
2292 assert(!Quals.hasAddressSpace() &&
2293 "Type cannot be in multiple addr spaces!");
2294 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002295
John McCall8ccfcb52009-09-24 19:53:00 +00002296 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002297}
2298
Chris Lattnerd60183d2009-02-18 22:53:11 +00002299QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002300 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002301 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002302 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002303 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002304
John McCall53fa7142010-12-24 02:08:15 +00002305 if (const PointerType *ptr = T->getAs<PointerType>()) {
2306 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002307 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002308 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2309 return getPointerType(ResultType);
2310 }
2311 }
Mike Stump11289f42009-09-09 15:08:12 +00002312
John McCall8ccfcb52009-09-24 19:53:00 +00002313 // If we are composing extended qualifiers together, merge together
2314 // into one ExtQuals node.
2315 QualifierCollector Quals;
2316 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002317
John McCall8ccfcb52009-09-24 19:53:00 +00002318 // If this type already has an ObjCGC specified, it cannot get
2319 // another one.
2320 assert(!Quals.hasObjCGCAttr() &&
2321 "Type cannot have multiple ObjCGCs!");
2322 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002323
John McCall8ccfcb52009-09-24 19:53:00 +00002324 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002325}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002326
John McCall4f5019e2010-12-19 02:44:49 +00002327const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2328 FunctionType::ExtInfo Info) {
2329 if (T->getExtInfo() == Info)
2330 return T;
2331
2332 QualType Result;
2333 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002334 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002335 } else {
2336 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2337 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2338 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002339 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002340 }
2341
2342 return cast<FunctionType>(Result.getTypePtr());
2343}
2344
Richard Smith2a7d4812013-05-04 07:00:32 +00002345void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2346 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002347 FD = FD->getMostRecentDecl();
2348 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002349 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2350 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002351 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002352 if (FunctionDecl *Next = FD->getPreviousDecl())
2353 FD = Next;
2354 else
2355 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002356 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002357 if (ASTMutationListener *L = getASTMutationListener())
2358 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002359}
2360
Richard Smith0b3a4622014-11-13 20:01:57 +00002361/// Get a function type and produce the equivalent function type with the
2362/// specified exception specification. Type sugar that can be present on a
2363/// declaration of a function with an exception specification is permitted
2364/// and preserved. Other type sugar (for instance, typedefs) is not.
2365static QualType getFunctionTypeWithExceptionSpec(
2366 ASTContext &Context, QualType Orig,
2367 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2368 // Might have some parens.
2369 if (auto *PT = dyn_cast<ParenType>(Orig))
2370 return Context.getParenType(
2371 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2372
2373 // Might have a calling-convention attribute.
2374 if (auto *AT = dyn_cast<AttributedType>(Orig))
2375 return Context.getAttributedType(
2376 AT->getAttrKind(),
2377 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2378 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2379 ESI));
2380
2381 // Anything else must be a function type. Rebuild it with the new exception
2382 // specification.
2383 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2384 return Context.getFunctionType(
2385 Proto->getReturnType(), Proto->getParamTypes(),
2386 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2387}
2388
Richard Smithdfe85e22016-12-15 02:35:39 +00002389bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2390 QualType U) {
2391 return hasSameType(T, U) ||
2392 (getLangOpts().CPlusPlus1z &&
2393 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2394 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2395}
2396
Richard Smith0b3a4622014-11-13 20:01:57 +00002397void ASTContext::adjustExceptionSpec(
2398 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2399 bool AsWritten) {
2400 // Update the type.
2401 QualType Updated =
2402 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2403 FD->setType(Updated);
2404
2405 if (!AsWritten)
2406 return;
2407
2408 // Update the type in the type source information too.
2409 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2410 // If the type and the type-as-written differ, we may need to update
2411 // the type-as-written too.
2412 if (TSInfo->getType() != FD->getType())
2413 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2414
2415 // FIXME: When we get proper type location information for exceptions,
2416 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2417 // up the TypeSourceInfo;
2418 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2419 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2420 "TypeLoc size mismatch from updating exception specification");
2421 TSInfo->overrideType(Updated);
2422 }
2423}
2424
Chris Lattnerc6395932007-06-22 20:56:16 +00002425/// getComplexType - Return the uniqued reference to the type for a complex
2426/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002427QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002428 // Unique pointers, to guarantee there is only one pointer of a particular
2429 // structure.
2430 llvm::FoldingSetNodeID ID;
2431 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002432
Craig Topper36250ad2014-05-12 05:36:57 +00002433 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002434 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2435 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002436
Chris Lattnerc6395932007-06-22 20:56:16 +00002437 // If the pointee type isn't canonical, this won't be a canonical type either,
2438 // so fill in the canonical type field.
2439 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002440 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002441 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002442
Chris Lattnerc6395932007-06-22 20:56:16 +00002443 // Get the new insert position for the node we care about.
2444 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002445 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002446 }
John McCall90d1c2d2009-09-24 23:30:46 +00002447 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002448 Types.push_back(New);
2449 ComplexTypes.InsertNode(New, InsertPos);
2450 return QualType(New, 0);
2451}
2452
Chris Lattner970e54e2006-11-12 00:37:36 +00002453/// getPointerType - Return the uniqued reference to the type for a pointer to
2454/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002455QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002456 // Unique pointers, to guarantee there is only one pointer of a particular
2457 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002458 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002459 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002460
Craig Topper36250ad2014-05-12 05:36:57 +00002461 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002462 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002463 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Chris Lattner7ccecb92006-11-12 08:50:50 +00002465 // If the pointee type isn't canonical, this won't be a canonical type either,
2466 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002467 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002468 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002469 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002470
Bob Wilsonc8541f22013-03-15 17:12:43 +00002471 // Get the new insert position for the node we care about.
2472 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002473 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002474 }
John McCall90d1c2d2009-09-24 23:30:46 +00002475 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002476 Types.push_back(New);
2477 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002478 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002479}
2480
Reid Kleckner0503a872013-12-05 01:23:43 +00002481QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2482 llvm::FoldingSetNodeID ID;
2483 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002484 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002485 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2486 if (AT)
2487 return QualType(AT, 0);
2488
2489 QualType Canonical = getCanonicalType(New);
2490
2491 // Get the new insert position for the node we care about.
2492 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002493 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002494
2495 AT = new (*this, TypeAlignment)
2496 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2497 Types.push_back(AT);
2498 AdjustedTypes.InsertNode(AT, InsertPos);
2499 return QualType(AT, 0);
2500}
2501
Reid Kleckner8a365022013-06-24 17:51:48 +00002502QualType ASTContext::getDecayedType(QualType T) const {
2503 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2504
Reid Kleckner8a365022013-06-24 17:51:48 +00002505 QualType Decayed;
2506
2507 // C99 6.7.5.3p7:
2508 // A declaration of a parameter as "array of type" shall be
2509 // adjusted to "qualified pointer to type", where the type
2510 // qualifiers (if any) are those specified within the [ and ] of
2511 // the array type derivation.
2512 if (T->isArrayType())
2513 Decayed = getArrayDecayedType(T);
2514
2515 // C99 6.7.5.3p8:
2516 // A declaration of a parameter as "function returning type"
2517 // shall be adjusted to "pointer to function returning type", as
2518 // in 6.3.2.1.
2519 if (T->isFunctionType())
2520 Decayed = getPointerType(T);
2521
Reid Kleckner0503a872013-12-05 01:23:43 +00002522 llvm::FoldingSetNodeID ID;
2523 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002524 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002525 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2526 if (AT)
2527 return QualType(AT, 0);
2528
Reid Kleckner8a365022013-06-24 17:51:48 +00002529 QualType Canonical = getCanonicalType(Decayed);
2530
2531 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002532 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002533 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002534
Reid Kleckner0503a872013-12-05 01:23:43 +00002535 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2536 Types.push_back(AT);
2537 AdjustedTypes.InsertNode(AT, InsertPos);
2538 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002539}
2540
Mike Stump11289f42009-09-09 15:08:12 +00002541/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002542/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002543QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002544 assert(T->isFunctionType() && "block of function types only");
2545 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002546 // structure.
2547 llvm::FoldingSetNodeID ID;
2548 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002549
Craig Topper36250ad2014-05-12 05:36:57 +00002550 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002551 if (BlockPointerType *PT =
2552 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2553 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002554
2555 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002556 // type either so fill in the canonical type field.
2557 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002558 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002559 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002560
Steve Naroffec33ed92008-08-27 16:04:49 +00002561 // Get the new insert position for the node we care about.
2562 BlockPointerType *NewIP =
2563 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002564 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002565 }
John McCall90d1c2d2009-09-24 23:30:46 +00002566 BlockPointerType *New
2567 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002568 Types.push_back(New);
2569 BlockPointerTypes.InsertNode(New, InsertPos);
2570 return QualType(New, 0);
2571}
2572
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002573/// getLValueReferenceType - Return the uniqued reference to the type for an
2574/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002575QualType
2576ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002577 assert(getCanonicalType(T) != OverloadTy &&
2578 "Unresolved overloaded function type");
2579
Bill Wendling3708c182007-05-27 10:15:43 +00002580 // Unique pointers, to guarantee there is only one pointer of a particular
2581 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002582 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002583 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002584
Craig Topper36250ad2014-05-12 05:36:57 +00002585 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002586 if (LValueReferenceType *RT =
2587 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002588 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002589
John McCallfc93cf92009-10-22 22:37:11 +00002590 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2591
Bill Wendling3708c182007-05-27 10:15:43 +00002592 // If the referencee type isn't canonical, this won't be a canonical type
2593 // either, so fill in the canonical type field.
2594 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002595 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2596 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2597 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002598
Bill Wendling3708c182007-05-27 10:15:43 +00002599 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002600 LValueReferenceType *NewIP =
2601 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002602 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002603 }
2604
John McCall90d1c2d2009-09-24 23:30:46 +00002605 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002606 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2607 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002608 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002609 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002610
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002611 return QualType(New, 0);
2612}
2613
2614/// getRValueReferenceType - Return the uniqued reference to the type for an
2615/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002616QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002617 // Unique pointers, to guarantee there is only one pointer of a particular
2618 // structure.
2619 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002620 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002621
Craig Topper36250ad2014-05-12 05:36:57 +00002622 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002623 if (RValueReferenceType *RT =
2624 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2625 return QualType(RT, 0);
2626
John McCallfc93cf92009-10-22 22:37:11 +00002627 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2628
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002629 // If the referencee type isn't canonical, this won't be a canonical type
2630 // either, so fill in the canonical type field.
2631 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002632 if (InnerRef || !T.isCanonical()) {
2633 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2634 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002635
2636 // Get the new insert position for the node we care about.
2637 RValueReferenceType *NewIP =
2638 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002639 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002640 }
2641
John McCall90d1c2d2009-09-24 23:30:46 +00002642 RValueReferenceType *New
2643 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002644 Types.push_back(New);
2645 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002646 return QualType(New, 0);
2647}
2648
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002649/// getMemberPointerType - Return the uniqued reference to the type for a
2650/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002651QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002652 // Unique pointers, to guarantee there is only one pointer of a particular
2653 // structure.
2654 llvm::FoldingSetNodeID ID;
2655 MemberPointerType::Profile(ID, T, Cls);
2656
Craig Topper36250ad2014-05-12 05:36:57 +00002657 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002658 if (MemberPointerType *PT =
2659 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2660 return QualType(PT, 0);
2661
2662 // If the pointee or class type isn't canonical, this won't be a canonical
2663 // type either, so fill in the canonical type field.
2664 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002665 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002666 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2667
2668 // Get the new insert position for the node we care about.
2669 MemberPointerType *NewIP =
2670 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002671 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002672 }
John McCall90d1c2d2009-09-24 23:30:46 +00002673 MemberPointerType *New
2674 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002675 Types.push_back(New);
2676 MemberPointerTypes.InsertNode(New, InsertPos);
2677 return QualType(New, 0);
2678}
2679
Mike Stump11289f42009-09-09 15:08:12 +00002680/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002681/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002682QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002683 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002684 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002685 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002686 assert((EltTy->isDependentType() ||
2687 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002688 "Constant array of VLAs is illegal!");
2689
Chris Lattnere2df3f92009-05-13 04:12:56 +00002690 // Convert the array size into a canonical width matching the pointer size for
2691 // the target.
2692 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002693 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002694
Chris Lattner23b7eb62007-06-15 23:05:46 +00002695 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002696 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002697
Craig Topper36250ad2014-05-12 05:36:57 +00002698 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002699 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002700 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002701 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002702
John McCall33ddac02011-01-19 10:06:00 +00002703 // If the element type isn't canonical or has qualifiers, this won't
2704 // be a canonical type either, so fill in the canonical type field.
2705 QualType Canon;
2706 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2707 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002708 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002709 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002710 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002711
Chris Lattner36f8e652007-01-27 08:31:04 +00002712 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002713 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002714 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002715 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
John McCall90d1c2d2009-09-24 23:30:46 +00002718 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002719 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002720 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002721 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002722 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002723}
2724
John McCall06549462011-01-18 08:40:38 +00002725/// getVariableArrayDecayedType - Turns the given type, which may be
2726/// variably-modified, into the corresponding type with all the known
2727/// sizes replaced with [*].
2728QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2729 // Vastly most common case.
2730 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002731
John McCall06549462011-01-18 08:40:38 +00002732 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002733
John McCall06549462011-01-18 08:40:38 +00002734 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002735 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002736 switch (ty->getTypeClass()) {
2737#define TYPE(Class, Base)
2738#define ABSTRACT_TYPE(Class, Base)
2739#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2740#include "clang/AST/TypeNodes.def"
2741 llvm_unreachable("didn't desugar past all non-canonical types?");
2742
2743 // These types should never be variably-modified.
2744 case Type::Builtin:
2745 case Type::Complex:
2746 case Type::Vector:
2747 case Type::ExtVector:
2748 case Type::DependentSizedExtVector:
2749 case Type::ObjCObject:
2750 case Type::ObjCInterface:
2751 case Type::ObjCObjectPointer:
2752 case Type::Record:
2753 case Type::Enum:
2754 case Type::UnresolvedUsing:
2755 case Type::TypeOfExpr:
2756 case Type::TypeOf:
2757 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002758 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002759 case Type::DependentName:
2760 case Type::InjectedClassName:
2761 case Type::TemplateSpecialization:
2762 case Type::DependentTemplateSpecialization:
2763 case Type::TemplateTypeParm:
2764 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002765 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002766 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002767 case Type::PackExpansion:
2768 llvm_unreachable("type should never be variably-modified");
2769
2770 // These types can be variably-modified but should never need to
2771 // further decay.
2772 case Type::FunctionNoProto:
2773 case Type::FunctionProto:
2774 case Type::BlockPointer:
2775 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002776 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002777 return type;
2778
2779 // These types can be variably-modified. All these modifications
2780 // preserve structure except as noted by comments.
2781 // TODO: if we ever care about optimizing VLAs, there are no-op
2782 // optimizations available here.
2783 case Type::Pointer:
2784 result = getPointerType(getVariableArrayDecayedType(
2785 cast<PointerType>(ty)->getPointeeType()));
2786 break;
2787
2788 case Type::LValueReference: {
2789 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2790 result = getLValueReferenceType(
2791 getVariableArrayDecayedType(lv->getPointeeType()),
2792 lv->isSpelledAsLValue());
2793 break;
2794 }
2795
2796 case Type::RValueReference: {
2797 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2798 result = getRValueReferenceType(
2799 getVariableArrayDecayedType(lv->getPointeeType()));
2800 break;
2801 }
2802
Eli Friedman0dfb8892011-10-06 23:00:33 +00002803 case Type::Atomic: {
2804 const AtomicType *at = cast<AtomicType>(ty);
2805 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2806 break;
2807 }
2808
John McCall06549462011-01-18 08:40:38 +00002809 case Type::ConstantArray: {
2810 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2811 result = getConstantArrayType(
2812 getVariableArrayDecayedType(cat->getElementType()),
2813 cat->getSize(),
2814 cat->getSizeModifier(),
2815 cat->getIndexTypeCVRQualifiers());
2816 break;
2817 }
2818
2819 case Type::DependentSizedArray: {
2820 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2821 result = getDependentSizedArrayType(
2822 getVariableArrayDecayedType(dat->getElementType()),
2823 dat->getSizeExpr(),
2824 dat->getSizeModifier(),
2825 dat->getIndexTypeCVRQualifiers(),
2826 dat->getBracketsRange());
2827 break;
2828 }
2829
2830 // Turn incomplete types into [*] types.
2831 case Type::IncompleteArray: {
2832 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2833 result = getVariableArrayType(
2834 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002835 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002836 ArrayType::Normal,
2837 iat->getIndexTypeCVRQualifiers(),
2838 SourceRange());
2839 break;
2840 }
2841
2842 // Turn VLA types into [*] types.
2843 case Type::VariableArray: {
2844 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2845 result = getVariableArrayType(
2846 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002847 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002848 ArrayType::Star,
2849 vat->getIndexTypeCVRQualifiers(),
2850 vat->getBracketsRange());
2851 break;
2852 }
2853 }
2854
2855 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002856 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002857}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002858
Steve Naroffcadebd02007-08-30 18:14:25 +00002859/// getVariableArrayType - Returns a non-unique reference to the type for a
2860/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002861QualType ASTContext::getVariableArrayType(QualType EltTy,
2862 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002863 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002864 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002865 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002866 // Since we don't unique expressions, it isn't possible to unique VLA's
2867 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002868 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002869
John McCall33ddac02011-01-19 10:06:00 +00002870 // Be sure to pull qualifiers off the element type.
2871 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2872 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002873 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002874 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002875 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002876 }
2877
John McCall90d1c2d2009-09-24 23:30:46 +00002878 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002879 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002880
2881 VariableArrayTypes.push_back(New);
2882 Types.push_back(New);
2883 return QualType(New, 0);
2884}
2885
Douglas Gregor4619e432008-12-05 23:32:09 +00002886/// getDependentSizedArrayType - Returns a non-unique reference to
2887/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002888/// type.
John McCall33ddac02011-01-19 10:06:00 +00002889QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2890 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002891 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002892 unsigned elementTypeQuals,
2893 SourceRange brackets) const {
2894 assert((!numElements || numElements->isTypeDependent() ||
2895 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002896 "Size must be type- or value-dependent!");
2897
John McCall33ddac02011-01-19 10:06:00 +00002898 // Dependently-sized array types that do not have a specified number
2899 // of elements will have their sizes deduced from a dependent
2900 // initializer. We do no canonicalization here at all, which is okay
2901 // because they can't be used in most locations.
2902 if (!numElements) {
2903 DependentSizedArrayType *newType
2904 = new (*this, TypeAlignment)
2905 DependentSizedArrayType(*this, elementType, QualType(),
2906 numElements, ASM, elementTypeQuals,
2907 brackets);
2908 Types.push_back(newType);
2909 return QualType(newType, 0);
2910 }
2911
2912 // Otherwise, we actually build a new type every time, but we
2913 // also build a canonical type.
2914
2915 SplitQualType canonElementType = getCanonicalType(elementType).split();
2916
Craig Topper36250ad2014-05-12 05:36:57 +00002917 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002918 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002919 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002920 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002921 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002922
John McCall33ddac02011-01-19 10:06:00 +00002923 // Look for an existing type with these properties.
2924 DependentSizedArrayType *canonTy =
2925 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002926
John McCall33ddac02011-01-19 10:06:00 +00002927 // If we don't have one, build one.
2928 if (!canonTy) {
2929 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002930 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002931 QualType(), numElements, ASM, elementTypeQuals,
2932 brackets);
2933 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2934 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002935 }
2936
John McCall33ddac02011-01-19 10:06:00 +00002937 // Apply qualifiers from the element type to the array.
2938 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002939 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002940
David Majnemer16a74702015-07-24 05:54:19 +00002941 // If we didn't need extra canonicalization for the element type or the size
2942 // expression, then just use that as our result.
2943 if (QualType(canonElementType.Ty, 0) == elementType &&
2944 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002945 return canon;
2946
2947 // Otherwise, we need to build a type which follows the spelling
2948 // of the element type.
2949 DependentSizedArrayType *sugaredType
2950 = new (*this, TypeAlignment)
2951 DependentSizedArrayType(*this, elementType, canon, numElements,
2952 ASM, elementTypeQuals, brackets);
2953 Types.push_back(sugaredType);
2954 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002955}
2956
John McCall33ddac02011-01-19 10:06:00 +00002957QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002958 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002959 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002960 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002961 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002962
Craig Topper36250ad2014-05-12 05:36:57 +00002963 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002964 if (IncompleteArrayType *iat =
2965 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2966 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002967
2968 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002969 // either, so fill in the canonical type field. We also have to pull
2970 // qualifiers off the element type.
2971 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002972
John McCall33ddac02011-01-19 10:06:00 +00002973 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2974 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002975 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002976 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002977 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002978
2979 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002980 IncompleteArrayType *existing =
2981 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2982 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002983 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002984
John McCall33ddac02011-01-19 10:06:00 +00002985 IncompleteArrayType *newType = new (*this, TypeAlignment)
2986 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002987
John McCall33ddac02011-01-19 10:06:00 +00002988 IncompleteArrayTypes.InsertNode(newType, insertPos);
2989 Types.push_back(newType);
2990 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002991}
2992
Steve Naroff91fcddb2007-07-18 18:00:27 +00002993/// getVectorType - Return the unique reference to a vector type of
2994/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002995QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002996 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002997 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002998
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002999 // Check if we've already instantiated a vector of this type.
3000 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003001 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003002
Craig Topper36250ad2014-05-12 05:36:57 +00003003 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003004 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3005 return QualType(VTP, 0);
3006
3007 // If the element type isn't canonical, this won't be a canonical type either,
3008 // so fill in the canonical type field.
3009 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003010 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003011 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003012
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003013 // Get the new insert position for the node we care about.
3014 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003015 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003016 }
John McCall90d1c2d2009-09-24 23:30:46 +00003017 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003018 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003019 VectorTypes.InsertNode(New, InsertPos);
3020 Types.push_back(New);
3021 return QualType(New, 0);
3022}
3023
Nate Begemance4d7fc2008-04-18 23:10:10 +00003024/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003025/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003026QualType
3027ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003028 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003029
Steve Naroff91fcddb2007-07-18 18:00:27 +00003030 // Check if we've already instantiated a vector of this type.
3031 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003032 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003033 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003034 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003035 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3036 return QualType(VTP, 0);
3037
3038 // If the element type isn't canonical, this won't be a canonical type either,
3039 // so fill in the canonical type field.
3040 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003041 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003042 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003043
Steve Naroff91fcddb2007-07-18 18:00:27 +00003044 // Get the new insert position for the node we care about.
3045 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003046 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003047 }
John McCall90d1c2d2009-09-24 23:30:46 +00003048 ExtVectorType *New = new (*this, TypeAlignment)
3049 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003050 VectorTypes.InsertNode(New, InsertPos);
3051 Types.push_back(New);
3052 return QualType(New, 0);
3053}
3054
Jay Foad39c79802011-01-12 09:06:06 +00003055QualType
3056ASTContext::getDependentSizedExtVectorType(QualType vecType,
3057 Expr *SizeExpr,
3058 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003059 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003060 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003061 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003062
Craig Topper36250ad2014-05-12 05:36:57 +00003063 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003064 DependentSizedExtVectorType *Canon
3065 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3066 DependentSizedExtVectorType *New;
3067 if (Canon) {
3068 // We already have a canonical version of this array type; use it as
3069 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003070 New = new (*this, TypeAlignment)
3071 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3072 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003073 } else {
3074 QualType CanonVecTy = getCanonicalType(vecType);
3075 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003076 New = new (*this, TypeAlignment)
3077 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3078 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003079
3080 DependentSizedExtVectorType *CanonCheck
3081 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3082 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3083 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003084 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3085 } else {
3086 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3087 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003088 New = new (*this, TypeAlignment)
3089 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003090 }
3091 }
Mike Stump11289f42009-09-09 15:08:12 +00003092
Douglas Gregor758a8692009-06-17 21:51:59 +00003093 Types.push_back(New);
3094 return QualType(New, 0);
3095}
3096
John McCall18afab72016-03-01 00:49:02 +00003097/// \brief Determine whether \p T is canonical as the result type of a function.
3098static bool isCanonicalResultType(QualType T) {
3099 return T.isCanonical() &&
3100 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3101 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3102}
3103
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003104/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003105///
Jay Foad39c79802011-01-12 09:06:06 +00003106QualType
3107ASTContext::getFunctionNoProtoType(QualType ResultTy,
3108 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003109 // Unique functions, to guarantee there is only one function of a particular
3110 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003111 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003112 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003113
Craig Topper36250ad2014-05-12 05:36:57 +00003114 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003115 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003116 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003117 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003118
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003119 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003120 if (!isCanonicalResultType(ResultTy)) {
3121 Canonical =
3122 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003123
Chris Lattner47955de2007-01-27 08:37:20 +00003124 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003125 FunctionNoProtoType *NewIP =
3126 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003127 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003128 }
Mike Stump11289f42009-09-09 15:08:12 +00003129
John McCall90d1c2d2009-09-24 23:30:46 +00003130 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003131 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003132 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003133 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003134 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003135}
3136
Douglas Gregora602a152015-10-01 20:20:47 +00003137CanQualType
3138ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3139 CanQualType CanResultType = getCanonicalType(ResultType);
3140
3141 // Canonical result types do not have ARC lifetime qualifiers.
3142 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3143 Qualifiers Qs = CanResultType.getQualifiers();
3144 Qs.removeObjCLifetime();
3145 return CanQualType::CreateUnsafe(
3146 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3147 }
3148
3149 return CanResultType;
3150}
3151
Richard Smith3c4f8d22016-10-16 17:54:23 +00003152static bool isCanonicalExceptionSpecification(
3153 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3154 if (ESI.Type == EST_None)
3155 return true;
3156 if (!NoexceptInType)
3157 return false;
3158
3159 // C++17 onwards: exception specification is part of the type, as a simple
3160 // boolean "can this function type throw".
3161 if (ESI.Type == EST_BasicNoexcept)
3162 return true;
3163
3164 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003165 // expansions (so we can't tell whether it's non-throwing) and all its
3166 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003167 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003168 bool AnyPackExpansions = false;
3169 for (QualType ET : ESI.Exceptions) {
3170 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003171 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003172 if (ET->getAs<PackExpansionType>())
3173 AnyPackExpansions = true;
3174 }
3175 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003176 }
3177
Richard Smith2a2cda52016-10-18 19:29:18 +00003178 // A noexcept(expr) specification is (possibly) canonical if expr is
3179 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003180 if (ESI.Type == EST_ComputedNoexcept)
3181 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3182
3183 return false;
3184}
3185
Richard Smith304b1242016-10-18 20:13:25 +00003186QualType ASTContext::getFunctionTypeInternal(
3187 QualType ResultTy, ArrayRef<QualType> ArgArray,
3188 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003189 size_t NumArgs = ArgArray.size();
3190
Richard Smith2a2cda52016-10-18 19:29:18 +00003191 // Unique functions, to guarantee there is only one function of a particular
3192 // structure.
3193 llvm::FoldingSetNodeID ID;
3194 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3195 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003196
Richard Smith2a2cda52016-10-18 19:29:18 +00003197 QualType Canonical;
3198 bool Unique = false;
3199
3200 void *InsertPos = nullptr;
3201 if (FunctionProtoType *FPT =
3202 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3203 QualType Existing = QualType(FPT, 0);
3204
3205 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3206 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003207 // noexcept expression, or we're just looking for a canonical type.
3208 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003209 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003210 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003211 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3212 return Existing;
3213
3214 // We need a new type sugar node for this one, to hold the new noexcept
3215 // expression. We do no canonicalization here, but that's OK since we don't
3216 // expect to see the same noexcept expression much more than once.
3217 Canonical = getCanonicalType(Existing);
3218 Unique = true;
3219 }
3220
3221 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003222 bool IsCanonicalExceptionSpec =
3223 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3224
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003225 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003226 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003227 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003228 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003229 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003230 isCanonical = false;
3231
Richard Smith304b1242016-10-18 20:13:25 +00003232 if (OnlyWantCanonical)
3233 assert(isCanonical &&
3234 "given non-canonical parameters constructing canonical type");
3235
Richard Smith2a2cda52016-10-18 19:29:18 +00003236 // If this type isn't canonical, get the canonical version of it if we don't
3237 // already have it. The exception spec is only partially part of the
3238 // canonical type, and only in C++17 onwards.
3239 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003240 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003241 CanonicalArgs.reserve(NumArgs);
3242 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003243 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003244
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003245 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003246 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003247 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003248
3249 if (IsCanonicalExceptionSpec) {
3250 // Exception spec is already OK.
3251 } else if (NoexceptInType) {
3252 switch (EPI.ExceptionSpec.Type) {
3253 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3254 // We don't know yet. It shouldn't matter what we pick here; no-one
3255 // should ever look at this.
3256 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003257 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003258 CanonicalEPI.ExceptionSpec.Type = EST_None;
3259 break;
3260
Richard Smith2a2cda52016-10-18 19:29:18 +00003261 // A dynamic exception specification is almost always "not noexcept",
3262 // with the exception that a pack expansion might expand to no types.
3263 case EST_Dynamic: {
3264 bool AnyPacks = false;
3265 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3266 if (ET->getAs<PackExpansionType>())
3267 AnyPacks = true;
3268 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3269 }
3270 if (!AnyPacks)
3271 CanonicalEPI.ExceptionSpec.Type = EST_None;
3272 else {
3273 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3274 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3275 }
3276 break;
3277 }
3278
Richard Smith3c4f8d22016-10-16 17:54:23 +00003279 case EST_DynamicNone: case EST_BasicNoexcept:
3280 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3281 break;
3282
3283 case EST_ComputedNoexcept:
3284 llvm::APSInt Value(1);
3285 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3286 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3287 /*IsEvaluated*/false)) {
3288 // This noexcept specification is invalid.
3289 // FIXME: Should this be able to happen?
3290 CanonicalEPI.ExceptionSpec.Type = EST_None;
3291 break;
3292 }
3293
3294 CanonicalEPI.ExceptionSpec.Type =
3295 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3296 break;
3297 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003298 } else {
3299 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3300 }
John McCalldb40c7f2010-12-14 08:05:40 +00003301
Douglas Gregora602a152015-10-01 20:20:47 +00003302 // Adjust the canonical function result type.
3303 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003304 Canonical =
3305 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003306
Chris Lattnerfd4de792007-01-27 01:15:32 +00003307 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003308 FunctionProtoType *NewIP =
3309 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003310 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003311 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003312
John McCall31168b02011-06-15 23:02:42 +00003313 // FunctionProtoType objects are allocated with extra bytes after
3314 // them for three variable size arrays at the end:
3315 // - parameter types
3316 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003317 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003318 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003319 // expression, or information used to resolve the exception
3320 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003321 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003322 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003323
Richard Smith8acb4282014-07-31 21:57:55 +00003324 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3325 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3326 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003327 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003328 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003329 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003330 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003331 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003332 }
John McCall18afab72016-03-01 00:49:02 +00003333
3334 // Put the ExtParameterInfos last. If all were equal, it would make
3335 // more sense to put these before the exception specification, because
3336 // it's much easier to skip past them compared to the elaborate switch
3337 // required to skip the exception specification. However, all is not
3338 // equal; ExtParameterInfos are used to model very uncommon features,
3339 // and it's better not to burden the more common paths.
3340 if (EPI.ExtParameterInfos) {
3341 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3342 }
John McCall31168b02011-06-15 23:02:42 +00003343
John McCalldb40c7f2010-12-14 08:05:40 +00003344 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003345 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003346 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003347 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003348 if (!Unique)
3349 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003350 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003351}
Chris Lattneref51c202006-11-10 07:17:23 +00003352
Joey Goulye3c85de2016-12-01 11:30:49 +00003353QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003354 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003355 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003356
3357 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003358 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003359 return QualType(PT, 0);
3360
3361 // If the pipe element type isn't canonical, this won't be a canonical type
3362 // either, so fill in the canonical type field.
3363 QualType Canonical;
3364 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003365 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003366
3367 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003368 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003369 assert(!NewIP && "Shouldn't be in the map!");
3370 (void)NewIP;
3371 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003372 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003373 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003374 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003375 return QualType(New, 0);
3376}
3377
Joey Goulye3c85de2016-12-01 11:30:49 +00003378QualType ASTContext::getReadPipeType(QualType T) const {
3379 return getPipeType(T, true);
3380}
3381
Joey Gouly5788b782016-11-18 14:10:54 +00003382QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003383 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003384}
3385
John McCalle78aac42010-03-10 03:28:59 +00003386#ifndef NDEBUG
3387static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3388 if (!isa<CXXRecordDecl>(D)) return false;
3389 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3390 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3391 return true;
3392 if (RD->getDescribedClassTemplate() &&
3393 !isa<ClassTemplateSpecializationDecl>(RD))
3394 return true;
3395 return false;
3396}
3397#endif
3398
3399/// getInjectedClassNameType - Return the unique reference to the
3400/// injected class name type for the specified templated declaration.
3401QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003402 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003403 assert(NeedsInjectedClassNameType(Decl));
3404 if (Decl->TypeForDecl) {
3405 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003406 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003407 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3408 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3409 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3410 } else {
John McCall424cec92011-01-19 06:33:43 +00003411 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003412 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003413 Decl->TypeForDecl = newType;
3414 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003415 }
3416 return QualType(Decl->TypeForDecl, 0);
3417}
3418
Douglas Gregor83a586e2008-04-13 21:07:44 +00003419/// getTypeDeclType - Return the unique reference to the type for the
3420/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003421QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003422 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003423 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003424
Richard Smithdda56e42011-04-15 14:24:37 +00003425 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003426 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003427
John McCall96f0b5f2010-03-10 06:48:02 +00003428 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3429 "Template type parameter types are always available.");
3430
John McCall81e38502010-02-16 03:57:14 +00003431 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003432 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003433 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003434 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003435 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003436 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003437 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003438 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003439 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003440 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3441 Decl->TypeForDecl = newType;
3442 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003443 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003444 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003445
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003446 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003447}
3448
Chris Lattner32d920b2007-01-26 02:01:53 +00003449/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003450/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003451QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003452ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3453 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003454 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003455
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003456 if (Canonical.isNull())
3457 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003458 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003459 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003460 Decl->TypeForDecl = newType;
3461 Types.push_back(newType);
3462 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003463}
3464
Jay Foad39c79802011-01-12 09:06:06 +00003465QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003466 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3467
Douglas Gregorec9fd132012-01-14 16:38:05 +00003468 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003469 if (PrevDecl->TypeForDecl)
3470 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3471
John McCall424cec92011-01-19 06:33:43 +00003472 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3473 Decl->TypeForDecl = newType;
3474 Types.push_back(newType);
3475 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003476}
3477
Jay Foad39c79802011-01-12 09:06:06 +00003478QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003479 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3480
Douglas Gregorec9fd132012-01-14 16:38:05 +00003481 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003482 if (PrevDecl->TypeForDecl)
3483 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3484
John McCall424cec92011-01-19 06:33:43 +00003485 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3486 Decl->TypeForDecl = newType;
3487 Types.push_back(newType);
3488 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003489}
3490
John McCall81904512011-01-06 01:58:22 +00003491QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3492 QualType modifiedType,
3493 QualType equivalentType) {
3494 llvm::FoldingSetNodeID id;
3495 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3496
Craig Topper36250ad2014-05-12 05:36:57 +00003497 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003498 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3499 if (type) return QualType(type, 0);
3500
3501 QualType canon = getCanonicalType(equivalentType);
3502 type = new (*this, TypeAlignment)
3503 AttributedType(canon, attrKind, modifiedType, equivalentType);
3504
3505 Types.push_back(type);
3506 AttributedTypes.InsertNode(type, insertPos);
3507
3508 return QualType(type, 0);
3509}
3510
John McCallcebee162009-10-18 09:09:24 +00003511/// \brief Retrieve a substitution-result type.
3512QualType
3513ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003514 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003515 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003516 && "replacement types must always be canonical");
3517
3518 llvm::FoldingSetNodeID ID;
3519 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003520 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003521 SubstTemplateTypeParmType *SubstParm
3522 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3523
3524 if (!SubstParm) {
3525 SubstParm = new (*this, TypeAlignment)
3526 SubstTemplateTypeParmType(Parm, Replacement);
3527 Types.push_back(SubstParm);
3528 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3529 }
3530
3531 return QualType(SubstParm, 0);
3532}
3533
Douglas Gregorada4b792011-01-14 02:55:32 +00003534/// \brief Retrieve a
3535QualType ASTContext::getSubstTemplateTypeParmPackType(
3536 const TemplateTypeParmType *Parm,
3537 const TemplateArgument &ArgPack) {
3538#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003539 for (const auto &P : ArgPack.pack_elements()) {
3540 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3541 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003542 }
3543#endif
3544
3545 llvm::FoldingSetNodeID ID;
3546 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003547 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003548 if (SubstTemplateTypeParmPackType *SubstParm
3549 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3550 return QualType(SubstParm, 0);
3551
3552 QualType Canon;
3553 if (!Parm->isCanonicalUnqualified()) {
3554 Canon = getCanonicalType(QualType(Parm, 0));
3555 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3556 ArgPack);
3557 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3558 }
3559
3560 SubstTemplateTypeParmPackType *SubstParm
3561 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3562 ArgPack);
3563 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003564 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003565 return QualType(SubstParm, 0);
3566}
3567
Douglas Gregoreff93e02009-02-05 23:33:38 +00003568/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003569/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003570/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003571QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003572 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003573 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003574 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003575 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003576 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003577 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003578 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3579
3580 if (TypeParm)
3581 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003582
Chandler Carruth08836322011-05-01 00:51:33 +00003583 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003584 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003585 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003586
3587 TemplateTypeParmType *TypeCheck
3588 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3589 assert(!TypeCheck && "Template type parameter canonical type broken");
3590 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003591 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003592 TypeParm = new (*this, TypeAlignment)
3593 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003594
3595 Types.push_back(TypeParm);
3596 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3597
3598 return QualType(TypeParm, 0);
3599}
3600
John McCalle78aac42010-03-10 03:28:59 +00003601TypeSourceInfo *
3602ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3603 SourceLocation NameLoc,
3604 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003605 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003606 assert(!Name.getAsDependentTemplateName() &&
3607 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003608 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003609
3610 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003611 TemplateSpecializationTypeLoc TL =
3612 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003613 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003614 TL.setTemplateNameLoc(NameLoc);
3615 TL.setLAngleLoc(Args.getLAngleLoc());
3616 TL.setRAngleLoc(Args.getRAngleLoc());
3617 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3618 TL.setArgLocInfo(i, Args[i].getLocInfo());
3619 return DI;
3620}
3621
Mike Stump11289f42009-09-09 15:08:12 +00003622QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003623ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003624 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003625 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003626 assert(!Template.getAsDependentTemplateName() &&
3627 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003628
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003629 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003630 ArgVec.reserve(Args.size());
3631 for (const TemplateArgumentLoc &Arg : Args.arguments())
3632 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003633
David Majnemer6fbeee32016-07-07 04:43:07 +00003634 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003635}
3636
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003637#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003638static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3639 for (const TemplateArgument &Arg : Args)
3640 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003641 return true;
3642
3643 return true;
3644}
3645#endif
3646
John McCall0ad16662009-10-29 08:12:44 +00003647QualType
3648ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003649 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003650 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003651 assert(!Template.getAsDependentTemplateName() &&
3652 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003653 // Look through qualified template names.
3654 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3655 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003656
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003657 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003658 Template.getAsTemplateDecl() &&
3659 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003660 QualType CanonType;
3661 if (!Underlying.isNull())
3662 CanonType = getCanonicalType(Underlying);
3663 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003664 // We can get here with an alias template when the specialization contains
3665 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003666 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003667 "Caller must compute aliased type");
3668 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003669 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003670 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003671
Douglas Gregora8e02e72009-07-28 23:00:59 +00003672 // Allocate the (non-canonical) template specialization type, but don't
3673 // try to unique it: these types typically have location information that
3674 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003675 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003676 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003677 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003678 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003679 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003680 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003681 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003682
Douglas Gregor8bf42052009-02-09 18:46:07 +00003683 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003684 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003685}
3686
David Majnemer6fbeee32016-07-07 04:43:07 +00003687QualType ASTContext::getCanonicalTemplateSpecializationType(
3688 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003689 assert(!Template.getAsDependentTemplateName() &&
3690 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003691
Douglas Gregore29139c2011-03-03 17:04:51 +00003692 // Look through qualified template names.
3693 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3694 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003695
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003696 // Build the canonical template specialization type.
3697 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003698 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003699 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003700 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003701 for (const TemplateArgument &Arg : Args)
3702 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003703
3704 // Determine whether this canonical template specialization type already
3705 // exists.
3706 llvm::FoldingSetNodeID ID;
3707 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003708 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003709
Craig Topper36250ad2014-05-12 05:36:57 +00003710 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003711 TemplateSpecializationType *Spec
3712 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3713
3714 if (!Spec) {
3715 // Allocate a new canonical template specialization type.
3716 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3717 sizeof(TemplateArgument) * NumArgs),
3718 TypeAlignment);
3719 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003720 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003721 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003722 Types.push_back(Spec);
3723 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3724 }
3725
3726 assert(Spec->isDependentType() &&
3727 "Non-dependent template-id type must have a canonical type");
3728 return QualType(Spec, 0);
3729}
3730
3731QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003732ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3733 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003734 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003735 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003736 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003737
Craig Topper36250ad2014-05-12 05:36:57 +00003738 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003739 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003740 if (T)
3741 return QualType(T, 0);
3742
Douglas Gregorc42075a2010-02-04 18:10:26 +00003743 QualType Canon = NamedType;
3744 if (!Canon.isCanonical()) {
3745 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003746 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3747 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003748 (void)CheckT;
3749 }
3750
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003751 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003752 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003753 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003754 return QualType(T, 0);
3755}
3756
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003757QualType
Jay Foad39c79802011-01-12 09:06:06 +00003758ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003759 llvm::FoldingSetNodeID ID;
3760 ParenType::Profile(ID, InnerType);
3761
Craig Topper36250ad2014-05-12 05:36:57 +00003762 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003763 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3764 if (T)
3765 return QualType(T, 0);
3766
3767 QualType Canon = InnerType;
3768 if (!Canon.isCanonical()) {
3769 Canon = getCanonicalType(InnerType);
3770 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3771 assert(!CheckT && "Paren canonical type broken");
3772 (void)CheckT;
3773 }
3774
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003775 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003776 Types.push_back(T);
3777 ParenTypes.InsertNode(T, InsertPos);
3778 return QualType(T, 0);
3779}
3780
Douglas Gregor02085352010-03-31 20:19:30 +00003781QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3782 NestedNameSpecifier *NNS,
3783 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003784 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003785 if (Canon.isNull()) {
3786 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00003787 if (CanonNNS != NNS)
3788 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003789 }
3790
3791 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003792 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003793
Craig Topper36250ad2014-05-12 05:36:57 +00003794 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003795 DependentNameType *T
3796 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003797 if (T)
3798 return QualType(T, 0);
3799
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003800 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003801 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003802 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003803 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003804}
3805
Mike Stump11289f42009-09-09 15:08:12 +00003806QualType
John McCallc392f372010-06-11 00:33:02 +00003807ASTContext::getDependentTemplateSpecializationType(
3808 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003809 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003810 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003811 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003812 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003813 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003814 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3815 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003816 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003817}
3818
3819QualType
3820ASTContext::getDependentTemplateSpecializationType(
3821 ElaboratedTypeKeyword Keyword,
3822 NestedNameSpecifier *NNS,
3823 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003824 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003825 assert((!NNS || NNS->isDependent()) &&
3826 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003827
Douglas Gregorc42075a2010-02-04 18:10:26 +00003828 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003829 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003830 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003831
Craig Topper36250ad2014-05-12 05:36:57 +00003832 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003833 DependentTemplateSpecializationType *T
3834 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003835 if (T)
3836 return QualType(T, 0);
3837
John McCallc392f372010-06-11 00:33:02 +00003838 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003839
John McCallc392f372010-06-11 00:33:02 +00003840 ElaboratedTypeKeyword CanonKeyword = Keyword;
3841 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3842
3843 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003844 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003845 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003846 for (unsigned I = 0; I != NumArgs; ++I) {
3847 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3848 if (!CanonArgs[I].structurallyEquals(Args[I]))
3849 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003850 }
3851
John McCallc392f372010-06-11 00:33:02 +00003852 QualType Canon;
3853 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3854 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003855 Name,
3856 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003857
3858 // Find the insert position again.
3859 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3860 }
3861
3862 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3863 sizeof(TemplateArgument) * NumArgs),
3864 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003865 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003866 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003867 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003868 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003869 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003870}
3871
Richard Smith32918772017-02-14 00:25:28 +00003872TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3873 TemplateArgument Arg;
3874 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3875 QualType ArgType = getTypeDeclType(TTP);
3876 if (TTP->isParameterPack())
3877 ArgType = getPackExpansionType(ArgType, None);
3878
3879 Arg = TemplateArgument(ArgType);
3880 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3881 Expr *E = new (*this) DeclRefExpr(
3882 NTTP, /*enclosing*/false,
3883 NTTP->getType().getNonLValueExprType(*this),
3884 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3885
3886 if (NTTP->isParameterPack())
3887 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3888 None);
3889 Arg = TemplateArgument(E);
3890 } else {
3891 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3892 if (TTP->isParameterPack())
3893 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3894 else
3895 Arg = TemplateArgument(TemplateName(TTP));
3896 }
3897
3898 if (Param->isTemplateParameterPack())
3899 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3900
3901 return Arg;
3902}
3903
Richard Smith43e14d22016-12-23 02:10:11 +00003904void
3905ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3906 SmallVectorImpl<TemplateArgument> &Args) {
3907 Args.reserve(Args.size() + Params->size());
3908
Richard Smith32918772017-02-14 00:25:28 +00003909 for (NamedDecl *Param : *Params)
3910 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00003911}
3912
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003913QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003914 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003915 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003916 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003917
3918 assert(Pattern->containsUnexpandedParameterPack() &&
3919 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003920 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003921 PackExpansionType *T
3922 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3923 if (T)
3924 return QualType(T, 0);
3925
3926 QualType Canon;
3927 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003928 Canon = getCanonicalType(Pattern);
3929 // The canonical type might not contain an unexpanded parameter pack, if it
3930 // contains an alias template specialization which ignores one of its
3931 // parameters.
3932 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003933 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003934
Richard Smith68eea502012-07-16 00:20:35 +00003935 // Find the insert position again, in case we inserted an element into
3936 // PackExpansionTypes and invalidated our insert position.
3937 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3938 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003939 }
3940
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003941 T = new (*this, TypeAlignment)
3942 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003943 Types.push_back(T);
3944 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003945 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003946}
3947
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003948/// CmpProtocolNames - Comparison predicate for sorting protocols
3949/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003950static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3951 ObjCProtocolDecl *const *RHS) {
3952 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003953}
3954
Craig Topper1f26d5b2016-01-03 19:43:23 +00003955static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3956 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003957
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003958 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3959 return false;
3960
Craig Topper1f26d5b2016-01-03 19:43:23 +00003961 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003962 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003963 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003964 return false;
3965 return true;
3966}
3967
Craig Topper6a8c1512015-10-22 01:56:18 +00003968static void
3969SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003970 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003971 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003972
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003973 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003974 for (ObjCProtocolDecl *&P : Protocols)
3975 P = P->getCanonicalDecl();
3976
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003977 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003978 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3979 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003980}
3981
John McCall8b07ec22010-05-15 11:32:37 +00003982QualType ASTContext::getObjCObjectType(QualType BaseType,
3983 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003984 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003985 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003986 llvm::makeArrayRef(Protocols, NumProtocols),
3987 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003988}
3989
3990QualType ASTContext::getObjCObjectType(
3991 QualType baseType,
3992 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003993 ArrayRef<ObjCProtocolDecl *> protocols,
3994 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003995 // If the base type is an interface and there aren't any protocols or
3996 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003997 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3998 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003999 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004000
4001 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004002 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004003 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004004 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004005 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4006 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004007
Douglas Gregore9d95f12015-07-07 03:57:35 +00004008 // Determine the type arguments to be used for canonicalization,
4009 // which may be explicitly specified here or written on the base
4010 // type.
4011 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4012 if (effectiveTypeArgs.empty()) {
4013 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4014 effectiveTypeArgs = baseObject->getTypeArgs();
4015 }
John McCallfc93cf92009-10-22 22:37:11 +00004016
Douglas Gregore9d95f12015-07-07 03:57:35 +00004017 // Build the canonical type, which has the canonical base type and a
4018 // sorted-and-uniqued list of protocols and the type arguments
4019 // canonicalized.
4020 QualType canonical;
4021 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4022 effectiveTypeArgs.end(),
4023 [&](QualType type) {
4024 return type.isCanonical();
4025 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004026 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004027 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4028 // Determine the canonical type arguments.
4029 ArrayRef<QualType> canonTypeArgs;
4030 SmallVector<QualType, 4> canonTypeArgsVec;
4031 if (!typeArgsAreCanonical) {
4032 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4033 for (auto typeArg : effectiveTypeArgs)
4034 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4035 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004036 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004037 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004038 }
4039
Douglas Gregore9d95f12015-07-07 03:57:35 +00004040 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4041 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4042 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004043 canonProtocolsVec.append(protocols.begin(), protocols.end());
4044 SortAndUniqueProtocols(canonProtocolsVec);
4045 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004046 } else {
4047 canonProtocols = protocols;
4048 }
4049
4050 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004051 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004052
John McCallfc93cf92009-10-22 22:37:11 +00004053 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004054 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4055 }
4056
Douglas Gregore9d95f12015-07-07 03:57:35 +00004057 unsigned size = sizeof(ObjCObjectTypeImpl);
4058 size += typeArgs.size() * sizeof(QualType);
4059 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4060 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004061 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004062 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4063 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004064
4065 Types.push_back(T);
4066 ObjCObjectTypes.InsertNode(T, InsertPos);
4067 return QualType(T, 0);
4068}
4069
Manman Ren3569eb52016-09-13 17:03:12 +00004070/// Apply Objective-C protocol qualifiers to the given type.
4071/// If this is for the canonical type of a type parameter, we can apply
4072/// protocol qualifiers on the ObjCObjectPointerType.
4073QualType
4074ASTContext::applyObjCProtocolQualifiers(QualType type,
4075 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4076 bool allowOnPointerType) const {
4077 hasError = false;
4078
Manman Renc5705ba2016-09-13 17:41:05 +00004079 if (const ObjCTypeParamType *objT =
4080 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4081 return getObjCTypeParamType(objT->getDecl(), protocols);
4082 }
4083
Manman Ren3569eb52016-09-13 17:03:12 +00004084 // Apply protocol qualifiers to ObjCObjectPointerType.
4085 if (allowOnPointerType) {
4086 if (const ObjCObjectPointerType *objPtr =
4087 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4088 const ObjCObjectType *objT = objPtr->getObjectType();
4089 // Merge protocol lists and construct ObjCObjectType.
4090 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4091 protocolsVec.append(objT->qual_begin(),
4092 objT->qual_end());
4093 protocolsVec.append(protocols.begin(), protocols.end());
4094 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4095 type = getObjCObjectType(
4096 objT->getBaseType(),
4097 objT->getTypeArgsAsWritten(),
4098 protocols,
4099 objT->isKindOfTypeAsWritten());
4100 return getObjCObjectPointerType(type);
4101 }
4102 }
4103
4104 // Apply protocol qualifiers to ObjCObjectType.
4105 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4106 // FIXME: Check for protocols to which the class type is already
4107 // known to conform.
4108
4109 return getObjCObjectType(objT->getBaseType(),
4110 objT->getTypeArgsAsWritten(),
4111 protocols,
4112 objT->isKindOfTypeAsWritten());
4113 }
4114
4115 // If the canonical type is ObjCObjectType, ...
4116 if (type->isObjCObjectType()) {
4117 // Silently overwrite any existing protocol qualifiers.
4118 // TODO: determine whether that's the right thing to do.
4119
4120 // FIXME: Check for protocols to which the class type is already
4121 // known to conform.
4122 return getObjCObjectType(type, { }, protocols, false);
4123 }
4124
4125 // id<protocol-list>
4126 if (type->isObjCIdType()) {
4127 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4128 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4129 objPtr->isKindOfType());
4130 return getObjCObjectPointerType(type);
4131 }
4132
4133 // Class<protocol-list>
4134 if (type->isObjCClassType()) {
4135 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4136 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4137 objPtr->isKindOfType());
4138 return getObjCObjectPointerType(type);
4139 }
4140
4141 hasError = true;
4142 return type;
4143}
4144
Manman Rene6be26c2016-09-13 17:25:08 +00004145QualType
4146ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4147 ArrayRef<ObjCProtocolDecl *> protocols,
4148 QualType Canonical) const {
4149 // Look in the folding set for an existing type.
4150 llvm::FoldingSetNodeID ID;
4151 ObjCTypeParamType::Profile(ID, Decl, protocols);
4152 void *InsertPos = nullptr;
4153 if (ObjCTypeParamType *TypeParam =
4154 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4155 return QualType(TypeParam, 0);
4156
4157 if (Canonical.isNull()) {
4158 // We canonicalize to the underlying type.
4159 Canonical = getCanonicalType(Decl->getUnderlyingType());
4160 if (!protocols.empty()) {
4161 // Apply the protocol qualifers.
4162 bool hasError;
4163 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4164 true/*allowOnPointerType*/);
4165 assert(!hasError && "Error when apply protocol qualifier to bound type");
4166 }
4167 }
4168
4169 unsigned size = sizeof(ObjCTypeParamType);
4170 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4171 void *mem = Allocate(size, TypeAlignment);
4172 ObjCTypeParamType *newType = new (mem)
4173 ObjCTypeParamType(Decl, Canonical, protocols);
4174
4175 Types.push_back(newType);
4176 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4177 return QualType(newType, 0);
4178}
4179
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004180/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4181/// protocol list adopt all protocols in QT's qualified-id protocol
4182/// list.
4183bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4184 ObjCInterfaceDecl *IC) {
4185 if (!QT->isObjCQualifiedIdType())
4186 return false;
4187
4188 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4189 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004190 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004191 if (!IC->ClassImplementsProtocol(Proto, false))
4192 return false;
4193 }
4194 return true;
4195 }
4196 return false;
4197}
4198
4199/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4200/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4201/// of protocols.
4202bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4203 ObjCInterfaceDecl *IDecl) {
4204 if (!QT->isObjCQualifiedIdType())
4205 return false;
4206 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4207 if (!OPT)
4208 return false;
4209 if (!IDecl->hasDefinition())
4210 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004211 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4212 CollectInheritedProtocols(IDecl, InheritedProtocols);
4213 if (InheritedProtocols.empty())
4214 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004215 // Check that if every protocol in list of id<plist> conforms to a protcol
4216 // of IDecl's, then bridge casting is ok.
4217 bool Conforms = false;
4218 for (auto *Proto : OPT->quals()) {
4219 Conforms = false;
4220 for (auto *PI : InheritedProtocols) {
4221 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4222 Conforms = true;
4223 break;
4224 }
4225 }
4226 if (!Conforms)
4227 break;
4228 }
4229 if (Conforms)
4230 return true;
4231
Aaron Ballman83731462014-03-17 16:14:00 +00004232 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004233 // If both the right and left sides have qualifiers.
4234 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004235 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004236 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004237 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004238 break;
4239 }
4240 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004241 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004242 }
4243 return true;
4244}
4245
John McCall8b07ec22010-05-15 11:32:37 +00004246/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4247/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004248QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004249 llvm::FoldingSetNodeID ID;
4250 ObjCObjectPointerType::Profile(ID, ObjectT);
4251
Craig Topper36250ad2014-05-12 05:36:57 +00004252 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004253 if (ObjCObjectPointerType *QT =
4254 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4255 return QualType(QT, 0);
4256
4257 // Find the canonical object type.
4258 QualType Canonical;
4259 if (!ObjectT.isCanonical()) {
4260 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4261
4262 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004263 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4264 }
4265
Douglas Gregorf85bee62010-02-08 22:59:26 +00004266 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004267 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4268 ObjCObjectPointerType *QType =
4269 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004270
Steve Narofffb4330f2009-06-17 22:40:22 +00004271 Types.push_back(QType);
4272 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004273 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004274}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004275
Douglas Gregor1c283312010-08-11 12:19:30 +00004276/// getObjCInterfaceType - Return the unique reference to the type for the
4277/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004278QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4279 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004280 if (Decl->TypeForDecl)
4281 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004282
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004283 if (PrevDecl) {
4284 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4285 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4286 return QualType(PrevDecl->TypeForDecl, 0);
4287 }
4288
Douglas Gregor7671e532011-12-16 16:34:57 +00004289 // Prefer the definition, if there is one.
4290 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4291 Decl = Def;
4292
Douglas Gregor1c283312010-08-11 12:19:30 +00004293 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4294 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4295 Decl->TypeForDecl = T;
4296 Types.push_back(T);
4297 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004298}
4299
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004300/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4301/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004302/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004303/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004304/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004305QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004306 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004307 if (tofExpr->isTypeDependent()) {
4308 llvm::FoldingSetNodeID ID;
4309 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004310
Craig Topper36250ad2014-05-12 05:36:57 +00004311 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004312 DependentTypeOfExprType *Canon
4313 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4314 if (Canon) {
4315 // We already have a "canonical" version of an identical, dependent
4316 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004317 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004318 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004319 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004320 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004321 Canon
4322 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004323 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4324 toe = Canon;
4325 }
4326 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004327 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004328 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004329 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004330 Types.push_back(toe);
4331 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004332}
4333
Steve Naroffa773cd52007-08-01 18:02:17 +00004334/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004335/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004336/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004337/// an issue. This doesn't affect the type checker, since it operates
4338/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004339QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004340 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004341 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004342 Types.push_back(tot);
4343 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004344}
4345
Richard Smith8eb1d322014-06-05 20:13:13 +00004346/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4347/// nodes. This would never be helpful, since each such type has its own
4348/// expression, and would not give a significant memory saving, since there
4349/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004350QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004351 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004352
4353 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004354 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004355 // unique dependent type. Two such decltype-specifiers refer to the same
4356 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004357 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004358 llvm::FoldingSetNodeID ID;
4359 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004360
Craig Topper36250ad2014-05-12 05:36:57 +00004361 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004362 DependentDecltypeType *Canon
4363 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004364 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004365 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004366 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004367 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004368 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004369 dt = new (*this, TypeAlignment)
4370 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004371 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004372 dt = new (*this, TypeAlignment)
4373 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004374 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004375 Types.push_back(dt);
4376 return QualType(dt, 0);
4377}
4378
Alexis Hunte852b102011-05-24 22:41:36 +00004379/// getUnaryTransformationType - We don't unique these, since the memory
4380/// savings are minimal and these are rare.
4381QualType ASTContext::getUnaryTransformType(QualType BaseType,
4382 QualType UnderlyingType,
4383 UnaryTransformType::UTTKind Kind)
4384 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004385 UnaryTransformType *ut = nullptr;
4386
4387 if (BaseType->isDependentType()) {
4388 // Look in the folding set for an existing type.
4389 llvm::FoldingSetNodeID ID;
4390 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4391
4392 void *InsertPos = nullptr;
4393 DependentUnaryTransformType *Canon
4394 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4395
4396 if (!Canon) {
4397 // Build a new, canonical __underlying_type(type) type.
4398 Canon = new (*this, TypeAlignment)
4399 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4400 Kind);
4401 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4402 }
4403 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4404 QualType(), Kind,
4405 QualType(Canon, 0));
4406 } else {
4407 QualType CanonType = getCanonicalType(UnderlyingType);
4408 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4409 UnderlyingType, Kind,
4410 CanonType);
4411 }
4412 Types.push_back(ut);
4413 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004414}
4415
Richard Smith2a7d4812013-05-04 07:00:32 +00004416/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4417/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4418/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004419QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004420 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004421 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004422 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004423
Richard Smith2a7d4812013-05-04 07:00:32 +00004424 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004425 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004426 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004427 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004428 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4429 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004430
Richard Smith74aeef52013-04-26 16:15:35 +00004431 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004432 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004433 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004434 Types.push_back(AT);
4435 if (InsertPos)
4436 AutoTypes.InsertNode(AT, InsertPos);
4437 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004438}
4439
Richard Smith600b5262017-01-26 20:40:47 +00004440/// Return the uniqued reference to the deduced template specialization type
4441/// which has been deduced to the given type, or to the canonical undeduced
4442/// such type, or the canonical deduced-but-dependent such type.
4443QualType ASTContext::getDeducedTemplateSpecializationType(
4444 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4445 // Look in the folding set for an existing type.
4446 void *InsertPos = nullptr;
4447 llvm::FoldingSetNodeID ID;
4448 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4449 IsDependent);
4450 if (DeducedTemplateSpecializationType *DTST =
4451 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4452 return QualType(DTST, 0);
4453
4454 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4455 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4456 Types.push_back(DTST);
4457 if (InsertPos)
4458 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4459 return QualType(DTST, 0);
4460}
4461
Eli Friedman0dfb8892011-10-06 23:00:33 +00004462/// getAtomicType - Return the uniqued reference to the atomic type for
4463/// the given value type.
4464QualType ASTContext::getAtomicType(QualType T) const {
4465 // Unique pointers, to guarantee there is only one pointer of a particular
4466 // structure.
4467 llvm::FoldingSetNodeID ID;
4468 AtomicType::Profile(ID, T);
4469
Craig Topper36250ad2014-05-12 05:36:57 +00004470 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004471 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4472 return QualType(AT, 0);
4473
4474 // If the atomic value type isn't canonical, this won't be a canonical type
4475 // either, so fill in the canonical type field.
4476 QualType Canonical;
4477 if (!T.isCanonical()) {
4478 Canonical = getAtomicType(getCanonicalType(T));
4479
4480 // Get the new insert position for the node we care about.
4481 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004482 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004483 }
4484 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4485 Types.push_back(New);
4486 AtomicTypes.InsertNode(New, InsertPos);
4487 return QualType(New, 0);
4488}
4489
Richard Smith02e85f32011-04-14 22:09:26 +00004490/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4491QualType ASTContext::getAutoDeductType() const {
4492 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004493 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004494 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004495 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004496 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004497 return AutoDeductTy;
4498}
4499
4500/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4501QualType ASTContext::getAutoRRefDeductType() const {
4502 if (AutoRRefDeductTy.isNull())
4503 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4504 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4505 return AutoRRefDeductTy;
4506}
4507
Chris Lattnerfb072462007-01-23 05:45:31 +00004508/// getTagDeclType - Return the unique reference to the type for the
4509/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004510QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004511 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004512 // FIXME: What is the design on getTagDeclType when it requires casting
4513 // away const? mutable?
4514 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004515}
4516
Mike Stump11289f42009-09-09 15:08:12 +00004517/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4518/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4519/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004520CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004521 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004522}
Chris Lattnerfb072462007-01-23 05:45:31 +00004523
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004524/// Return the unique signed counterpart of the integer type
4525/// corresponding to size_t.
4526CanQualType ASTContext::getSignedSizeType() const {
4527 return getFromTargetType(Target->getSignedSizeType());
4528}
4529
Hans Wennborg27541db2011-10-27 08:29:09 +00004530/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4531CanQualType ASTContext::getIntMaxType() const {
4532 return getFromTargetType(Target->getIntMaxType());
4533}
4534
4535/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4536CanQualType ASTContext::getUIntMaxType() const {
4537 return getFromTargetType(Target->getUIntMaxType());
4538}
4539
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004540/// getSignedWCharType - Return the type of "signed wchar_t".
4541/// Used when in C++, as a GCC extension.
4542QualType ASTContext::getSignedWCharType() const {
4543 // FIXME: derive from "Target" ?
4544 return WCharTy;
4545}
4546
4547/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4548/// Used when in C++, as a GCC extension.
4549QualType ASTContext::getUnsignedWCharType() const {
4550 // FIXME: derive from "Target" ?
4551 return UnsignedIntTy;
4552}
4553
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004554QualType ASTContext::getIntPtrType() const {
4555 return getFromTargetType(Target->getIntPtrType());
4556}
4557
4558QualType ASTContext::getUIntPtrType() const {
4559 return getCorrespondingUnsignedType(getIntPtrType());
4560}
4561
Hans Wennborg27541db2011-10-27 08:29:09 +00004562/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004563/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4564QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004565 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004566}
4567
Eli Friedman4e91899e2012-11-27 02:58:24 +00004568/// \brief Return the unique type for "pid_t" defined in
4569/// <sys/types.h>. We need this to compute the correct type for vfork().
4570QualType ASTContext::getProcessIDType() const {
4571 return getFromTargetType(Target->getProcessIDType());
4572}
4573
Chris Lattnera21ad802008-04-02 05:18:44 +00004574//===----------------------------------------------------------------------===//
4575// Type Operators
4576//===----------------------------------------------------------------------===//
4577
Jay Foad39c79802011-01-12 09:06:06 +00004578CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004579 // Push qualifiers into arrays, and then discard any remaining
4580 // qualifiers.
4581 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004582 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004583 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004584 QualType Result;
4585 if (isa<ArrayType>(Ty)) {
4586 Result = getArrayDecayedType(QualType(Ty,0));
4587 } else if (isa<FunctionType>(Ty)) {
4588 Result = getPointerType(QualType(Ty, 0));
4589 } else {
4590 Result = QualType(Ty, 0);
4591 }
4592
4593 return CanQualType::CreateUnsafe(Result);
4594}
4595
John McCall6c9dd522011-01-18 07:41:22 +00004596QualType ASTContext::getUnqualifiedArrayType(QualType type,
4597 Qualifiers &quals) {
4598 SplitQualType splitType = type.getSplitUnqualifiedType();
4599
4600 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4601 // the unqualified desugared type and then drops it on the floor.
4602 // We then have to strip that sugar back off with
4603 // getUnqualifiedDesugaredType(), which is silly.
4604 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004605 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004606
4607 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004608 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004609 quals = splitType.Quals;
4610 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004611 }
4612
John McCall6c9dd522011-01-18 07:41:22 +00004613 // Otherwise, recurse on the array's element type.
4614 QualType elementType = AT->getElementType();
4615 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4616
4617 // If that didn't change the element type, AT has no qualifiers, so we
4618 // can just use the results in splitType.
4619 if (elementType == unqualElementType) {
4620 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004621 quals = splitType.Quals;
4622 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004623 }
4624
4625 // Otherwise, add in the qualifiers from the outermost type, then
4626 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004627 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004628
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004629 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004630 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004631 CAT->getSizeModifier(), 0);
4632 }
4633
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004634 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004635 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004636 }
4637
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004638 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004639 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004640 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004641 VAT->getSizeModifier(),
4642 VAT->getIndexTypeCVRQualifiers(),
4643 VAT->getBracketsRange());
4644 }
4645
4646 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004647 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004648 DSAT->getSizeModifier(), 0,
4649 SourceRange());
4650}
4651
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004652/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4653/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4654/// they point to and return true. If T1 and T2 aren't pointer types
4655/// or pointer-to-member types, or if they are not similar at this
4656/// level, returns false and leaves T1 and T2 unchanged. Top-level
4657/// qualifiers on T1 and T2 are ignored. This function will typically
4658/// be called in a loop that successively "unwraps" pointer and
4659/// pointer-to-member types to compare them at each level.
4660bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4661 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4662 *T2PtrType = T2->getAs<PointerType>();
4663 if (T1PtrType && T2PtrType) {
4664 T1 = T1PtrType->getPointeeType();
4665 T2 = T2PtrType->getPointeeType();
4666 return true;
4667 }
4668
4669 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4670 *T2MPType = T2->getAs<MemberPointerType>();
4671 if (T1MPType && T2MPType &&
4672 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4673 QualType(T2MPType->getClass(), 0))) {
4674 T1 = T1MPType->getPointeeType();
4675 T2 = T2MPType->getPointeeType();
4676 return true;
4677 }
4678
David Blaikiebbafb8a2012-03-11 07:00:24 +00004679 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004680 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4681 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4682 if (T1OPType && T2OPType) {
4683 T1 = T1OPType->getPointeeType();
4684 T2 = T2OPType->getPointeeType();
4685 return true;
4686 }
4687 }
4688
4689 // FIXME: Block pointers, too?
4690
4691 return false;
4692}
4693
Jay Foad39c79802011-01-12 09:06:06 +00004694DeclarationNameInfo
4695ASTContext::getNameForTemplate(TemplateName Name,
4696 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004697 switch (Name.getKind()) {
4698 case TemplateName::QualifiedTemplate:
4699 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004700 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004701 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4702 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004703
John McCalld9dfe3a2011-06-30 08:33:18 +00004704 case TemplateName::OverloadedTemplate: {
4705 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4706 // DNInfo work in progress: CHECKME: what about DNLoc?
4707 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4708 }
4709
4710 case TemplateName::DependentTemplate: {
4711 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004712 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004713 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004714 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4715 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004716 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004717 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4718 // DNInfo work in progress: FIXME: source locations?
4719 DeclarationNameLoc DNLoc;
4720 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4721 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4722 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004723 }
4724 }
4725
John McCalld9dfe3a2011-06-30 08:33:18 +00004726 case TemplateName::SubstTemplateTemplateParm: {
4727 SubstTemplateTemplateParmStorage *subst
4728 = Name.getAsSubstTemplateTemplateParm();
4729 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4730 NameLoc);
4731 }
4732
4733 case TemplateName::SubstTemplateTemplateParmPack: {
4734 SubstTemplateTemplateParmPackStorage *subst
4735 = Name.getAsSubstTemplateTemplateParmPack();
4736 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4737 NameLoc);
4738 }
4739 }
4740
4741 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004742}
4743
Jay Foad39c79802011-01-12 09:06:06 +00004744TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004745 switch (Name.getKind()) {
4746 case TemplateName::QualifiedTemplate:
4747 case TemplateName::Template: {
4748 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004749 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004750 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004751 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4752
4753 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004754 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004755 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004756
John McCalld9dfe3a2011-06-30 08:33:18 +00004757 case TemplateName::OverloadedTemplate:
4758 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004759
John McCalld9dfe3a2011-06-30 08:33:18 +00004760 case TemplateName::DependentTemplate: {
4761 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4762 assert(DTN && "Non-dependent template names must refer to template decls.");
4763 return DTN->CanonicalTemplateName;
4764 }
4765
4766 case TemplateName::SubstTemplateTemplateParm: {
4767 SubstTemplateTemplateParmStorage *subst
4768 = Name.getAsSubstTemplateTemplateParm();
4769 return getCanonicalTemplateName(subst->getReplacement());
4770 }
4771
4772 case TemplateName::SubstTemplateTemplateParmPack: {
4773 SubstTemplateTemplateParmPackStorage *subst
4774 = Name.getAsSubstTemplateTemplateParmPack();
4775 TemplateTemplateParmDecl *canonParameter
4776 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4777 TemplateArgument canonArgPack
4778 = getCanonicalTemplateArgument(subst->getArgumentPack());
4779 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4780 }
4781 }
4782
4783 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004784}
4785
Douglas Gregoradee3e32009-11-11 23:06:43 +00004786bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4787 X = getCanonicalTemplateName(X);
4788 Y = getCanonicalTemplateName(Y);
4789 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4790}
4791
Mike Stump11289f42009-09-09 15:08:12 +00004792TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004793ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004794 switch (Arg.getKind()) {
4795 case TemplateArgument::Null:
4796 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004797
Douglas Gregora8e02e72009-07-28 23:00:59 +00004798 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004799 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004800
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004801 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004802 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004803 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004804 }
Mike Stump11289f42009-09-09 15:08:12 +00004805
Eli Friedmanb826a002012-09-26 02:36:12 +00004806 case TemplateArgument::NullPtr:
4807 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4808 /*isNullPtr*/true);
4809
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004810 case TemplateArgument::Template:
4811 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004812
4813 case TemplateArgument::TemplateExpansion:
4814 return TemplateArgument(getCanonicalTemplateName(
4815 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004816 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004817
Douglas Gregora8e02e72009-07-28 23:00:59 +00004818 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004819 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004820
Douglas Gregora8e02e72009-07-28 23:00:59 +00004821 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004822 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004823
Douglas Gregora8e02e72009-07-28 23:00:59 +00004824 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004825 if (Arg.pack_size() == 0)
4826 return Arg;
4827
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004828 TemplateArgument *CanonArgs
4829 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004830 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004831 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004832 AEnd = Arg.pack_end();
4833 A != AEnd; (void)++A, ++Idx)
4834 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004835
Benjamin Kramercce63472015-08-05 09:40:22 +00004836 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004837 }
4838 }
4839
4840 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004841 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004842}
4843
Douglas Gregor333489b2009-03-27 23:10:48 +00004844NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004845ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004846 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004847 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004848
4849 switch (NNS->getKind()) {
4850 case NestedNameSpecifier::Identifier:
4851 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004852 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004853 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4854 NNS->getAsIdentifier());
4855
4856 case NestedNameSpecifier::Namespace:
4857 // A namespace is canonical; build a nested-name-specifier with
4858 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004859 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004860 NNS->getAsNamespace()->getOriginalNamespace());
4861
4862 case NestedNameSpecifier::NamespaceAlias:
4863 // A namespace is canonical; build a nested-name-specifier with
4864 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004865 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004866 NNS->getAsNamespaceAlias()->getNamespace()
4867 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004868
4869 case NestedNameSpecifier::TypeSpec:
4870 case NestedNameSpecifier::TypeSpecWithTemplate: {
4871 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004872
4873 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4874 // break it apart into its prefix and identifier, then reconsititute those
4875 // as the canonical nested-name-specifier. This is required to canonicalize
4876 // a dependent nested-name-specifier involving typedefs of dependent-name
4877 // types, e.g.,
4878 // typedef typename T::type T1;
4879 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004880 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4881 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004882 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004883
Eli Friedman5358a0a2012-03-03 04:09:56 +00004884 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4885 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4886 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004887 return NestedNameSpecifier::Create(*this, nullptr, false,
4888 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004889 }
4890
4891 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004892 case NestedNameSpecifier::Super:
4893 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004894 return NNS;
4895 }
4896
David Blaikie8a40f702012-01-17 06:56:22 +00004897 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004898}
4899
Jay Foad39c79802011-01-12 09:06:06 +00004900const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004901 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004902 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004903 // Handle the common positive case fast.
4904 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4905 return AT;
4906 }
Mike Stump11289f42009-09-09 15:08:12 +00004907
John McCall8ccfcb52009-09-24 19:53:00 +00004908 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004909 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004910 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004911
John McCall8ccfcb52009-09-24 19:53:00 +00004912 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004913 // implements C99 6.7.3p8: "If the specification of an array type includes
4914 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004915
Chris Lattner7adf0762008-08-04 07:31:14 +00004916 // If we get here, we either have type qualifiers on the type, or we have
4917 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004918 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004919
John McCall33ddac02011-01-19 10:06:00 +00004920 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004921 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004922
Chris Lattner7adf0762008-08-04 07:31:14 +00004923 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004924 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004925 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004926 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004927
Chris Lattner7adf0762008-08-04 07:31:14 +00004928 // Otherwise, we have an array and we have qualifiers on it. Push the
4929 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004930 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004931
Chris Lattner7adf0762008-08-04 07:31:14 +00004932 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4933 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4934 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004935 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004936 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4937 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4938 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004939 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004940
Mike Stump11289f42009-09-09 15:08:12 +00004941 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004942 = dyn_cast<DependentSizedArrayType>(ATy))
4943 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004944 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004945 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004946 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004947 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004948 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004949
Chris Lattner7adf0762008-08-04 07:31:14 +00004950 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004951 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004952 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004953 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004954 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004955 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004956}
4957
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004958QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004959 if (T->isArrayType() || T->isFunctionType())
4960 return getDecayedType(T);
4961 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004962}
4963
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004964QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004965 T = getVariableArrayDecayedType(T);
4966 T = getAdjustedParameterType(T);
4967 return T.getUnqualifiedType();
4968}
4969
David Majnemerd09a51c2015-03-03 01:50:05 +00004970QualType ASTContext::getExceptionObjectType(QualType T) const {
4971 // C++ [except.throw]p3:
4972 // A throw-expression initializes a temporary object, called the exception
4973 // object, the type of which is determined by removing any top-level
4974 // cv-qualifiers from the static type of the operand of throw and adjusting
4975 // the type from "array of T" or "function returning T" to "pointer to T"
4976 // or "pointer to function returning T", [...]
4977 T = getVariableArrayDecayedType(T);
4978 if (T->isArrayType() || T->isFunctionType())
4979 T = getDecayedType(T);
4980 return T.getUnqualifiedType();
4981}
4982
Chris Lattnera21ad802008-04-02 05:18:44 +00004983/// getArrayDecayedType - Return the properly qualified result of decaying the
4984/// specified array type to a pointer. This operation is non-trivial when
4985/// handling typedefs etc. The canonical type of "T" must be an array type,
4986/// this returns a pointer to a properly qualified element of the array.
4987///
4988/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004989QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004990 // Get the element type with 'getAsArrayType' so that we don't lose any
4991 // typedefs in the element type of the array. This also handles propagation
4992 // of type qualifiers from the array type into the element type if present
4993 // (C99 6.7.3p8).
4994 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4995 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004996
Chris Lattner7adf0762008-08-04 07:31:14 +00004997 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004998
4999 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005000 QualType Result = getQualifiedType(PtrTy,
5001 PrettyArrayType->getIndexTypeQualifiers());
5002
5003 // int x[_Nullable] -> int * _Nullable
5004 if (auto Nullability = Ty->getNullability(*this)) {
5005 Result = const_cast<ASTContext *>(this)->getAttributedType(
5006 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5007 }
5008 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005009}
5010
John McCall33ddac02011-01-19 10:06:00 +00005011QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5012 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005013}
5014
John McCall33ddac02011-01-19 10:06:00 +00005015QualType ASTContext::getBaseElementType(QualType type) const {
5016 Qualifiers qs;
5017 while (true) {
5018 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005019 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005020 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005021
John McCall33ddac02011-01-19 10:06:00 +00005022 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005023 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005024 }
Mike Stump11289f42009-09-09 15:08:12 +00005025
John McCall33ddac02011-01-19 10:06:00 +00005026 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005027}
5028
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005029/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005030uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005031ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5032 uint64_t ElementCount = 1;
5033 do {
5034 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005035 CA = dyn_cast_or_null<ConstantArrayType>(
5036 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005037 } while (CA);
5038 return ElementCount;
5039}
5040
Steve Naroff0af91202007-04-27 21:51:21 +00005041/// getFloatingRank - Return a relative rank for floating point types.
5042/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005043static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005044 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005045 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005046
John McCall9dd450b2009-09-21 23:43:11 +00005047 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5048 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005049 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005050 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005051 case BuiltinType::Float: return FloatRank;
5052 case BuiltinType::Double: return DoubleRank;
5053 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005054 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005055 }
5056}
5057
Mike Stump11289f42009-09-09 15:08:12 +00005058/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5059/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005060/// 'typeDomain' is a real floating point or complex type.
5061/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005062QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5063 QualType Domain) const {
5064 FloatingRank EltRank = getFloatingRank(Size);
5065 if (Domain->isComplexType()) {
5066 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00005067 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005068 case FloatRank: return FloatComplexTy;
5069 case DoubleRank: return DoubleComplexTy;
5070 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005071 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005072 }
Steve Naroff0af91202007-04-27 21:51:21 +00005073 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005074
5075 assert(Domain->isRealFloatingType() && "Unknown domain!");
5076 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00005077 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005078 case FloatRank: return FloatTy;
5079 case DoubleRank: return DoubleTy;
5080 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005081 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005082 }
David Blaikief47fa302012-01-17 02:30:50 +00005083 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005084}
5085
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005086/// getFloatingTypeOrder - Compare the rank of the two specified floating
5087/// point types, ignoring the domain of the type (i.e. 'double' ==
5088/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005089/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005090int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005091 FloatingRank LHSR = getFloatingRank(LHS);
5092 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005093
Chris Lattnerb90739d2008-04-06 23:38:49 +00005094 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005095 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005096 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005097 return 1;
5098 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005099}
5100
Chris Lattner76a00cf2008-04-06 22:59:24 +00005101/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5102/// routine will assert if passed a built-in type that isn't an integer or enum,
5103/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005104unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005105 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005106
Chris Lattner76a00cf2008-04-06 22:59:24 +00005107 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005108 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005109 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005110 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005111 case BuiltinType::Char_S:
5112 case BuiltinType::Char_U:
5113 case BuiltinType::SChar:
5114 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005115 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005116 case BuiltinType::Short:
5117 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005118 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005119 case BuiltinType::Int:
5120 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005121 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005122 case BuiltinType::Long:
5123 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005124 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005125 case BuiltinType::LongLong:
5126 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005127 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005128 case BuiltinType::Int128:
5129 case BuiltinType::UInt128:
5130 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005131 }
5132}
5133
Eli Friedman629ffb92009-08-20 04:21:42 +00005134/// \brief Whether this is a promotable bitfield reference according
5135/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5136///
5137/// \returns the type this bit-field will promote to, or NULL if no
5138/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005139QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005140 if (E->isTypeDependent() || E->isValueDependent())
5141 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005142
5143 // FIXME: We should not do this unless E->refersToBitField() is true. This
5144 // matters in C where getSourceBitField() will find bit-fields for various
5145 // cases where the source expression is not a bit-field designator.
5146
John McCalld25db7e2013-05-06 21:39:12 +00005147 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005148 if (!Field)
5149 return QualType();
5150
5151 QualType FT = Field->getType();
5152
Richard Smithcaf33902011-10-10 18:28:20 +00005153 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005154 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005155 // C++ [conv.prom]p5:
5156 // A prvalue for an integral bit-field can be converted to a prvalue of type
5157 // int if int can represent all the values of the bit-field; otherwise, it
5158 // can be converted to unsigned int if unsigned int can represent all the
5159 // values of the bit-field. If the bit-field is larger yet, no integral
5160 // promotion applies to it.
5161 // C11 6.3.1.1/2:
5162 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5163 // If an int can represent all values of the original type (as restricted by
5164 // the width, for a bit-field), the value is converted to an int; otherwise,
5165 // it is converted to an unsigned int.
5166 //
5167 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5168 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005169 if (BitWidth < IntSize)
5170 return IntTy;
5171
5172 if (BitWidth == IntSize)
5173 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5174
5175 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005176 // like the base type. GCC has some weird bugs in this area that we
5177 // deliberately do not follow (GCC follows a pre-standard resolution to
5178 // C's DR315 which treats bit-width as being part of the type, and this leaks
5179 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005180 return QualType();
5181}
5182
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005183/// getPromotedIntegerType - Returns the type that Promotable will
5184/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5185/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005186QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005187 assert(!Promotable.isNull());
5188 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005189 if (const EnumType *ET = Promotable->getAs<EnumType>())
5190 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005191
5192 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5193 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5194 // (3.9.1) can be converted to a prvalue of the first of the following
5195 // types that can represent all the values of its underlying type:
5196 // int, unsigned int, long int, unsigned long int, long long int, or
5197 // unsigned long long int [...]
5198 // FIXME: Is there some better way to compute this?
5199 if (BT->getKind() == BuiltinType::WChar_S ||
5200 BT->getKind() == BuiltinType::WChar_U ||
5201 BT->getKind() == BuiltinType::Char16 ||
5202 BT->getKind() == BuiltinType::Char32) {
5203 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5204 uint64_t FromSize = getTypeSize(BT);
5205 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5206 LongLongTy, UnsignedLongLongTy };
5207 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5208 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5209 if (FromSize < ToSize ||
5210 (FromSize == ToSize &&
5211 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5212 return PromoteTypes[Idx];
5213 }
5214 llvm_unreachable("char type should fit into long long");
5215 }
5216 }
5217
5218 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005219 if (Promotable->isSignedIntegerType())
5220 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005221 uint64_t PromotableSize = getIntWidth(Promotable);
5222 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005223 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5224 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5225}
5226
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005227/// \brief Recurses in pointer/array types until it finds an objc retainable
5228/// type and returns its ownership.
5229Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5230 while (!T.isNull()) {
5231 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5232 return T.getObjCLifetime();
5233 if (T->isArrayType())
5234 T = getBaseElementType(T);
5235 else if (const PointerType *PT = T->getAs<PointerType>())
5236 T = PT->getPointeeType();
5237 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005238 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005239 else
5240 break;
5241 }
5242
5243 return Qualifiers::OCL_None;
5244}
5245
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005246static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5247 // Incomplete enum types are not treated as integer types.
5248 // FIXME: In C++, enum types are never integer types.
5249 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5250 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005251 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005252}
5253
Mike Stump11289f42009-09-09 15:08:12 +00005254/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005255/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005256/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005257int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005258 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5259 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005260
5261 // Unwrap enums to their underlying type.
5262 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5263 LHSC = getIntegerTypeForEnum(ET);
5264 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5265 RHSC = getIntegerTypeForEnum(ET);
5266
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005267 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005268
Chris Lattner76a00cf2008-04-06 22:59:24 +00005269 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5270 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005271
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005272 unsigned LHSRank = getIntegerRank(LHSC);
5273 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005274
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005275 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5276 if (LHSRank == RHSRank) return 0;
5277 return LHSRank > RHSRank ? 1 : -1;
5278 }
Mike Stump11289f42009-09-09 15:08:12 +00005279
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005280 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5281 if (LHSUnsigned) {
5282 // If the unsigned [LHS] type is larger, return it.
5283 if (LHSRank >= RHSRank)
5284 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005285
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005286 // If the signed type can represent all values of the unsigned type, it
5287 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005288 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005289 return -1;
5290 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005291
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005292 // If the unsigned [RHS] type is larger, return it.
5293 if (RHSRank >= LHSRank)
5294 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005295
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005296 // If the signed type can represent all values of the unsigned type, it
5297 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005298 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005299 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005300}
Anders Carlsson98f07902007-08-17 05:31:46 +00005301
Ben Langmuirf5416742016-02-04 00:55:24 +00005302TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005303 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005304 assert(!CFConstantStringTagDecl &&
5305 "tag and typedef should be initialized together");
5306 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5307 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005308
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005309 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005310 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005311
Anders Carlsson98f07902007-08-17 05:31:46 +00005312 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005313 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005314 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005315 // int flags;
5316 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005317 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005318 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005319 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005320 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005321 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005322 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005323 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005324
Anders Carlsson98f07902007-08-17 05:31:46 +00005325 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005326 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005327 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005328 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005329 SourceLocation(),
5330 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005331 FieldTypes[i], /*TInfo=*/nullptr,
5332 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005333 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005334 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005335 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005336 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005337 }
5338
Ben Langmuirf5416742016-02-04 00:55:24 +00005339 CFConstantStringTagDecl->completeDefinition();
5340 // This type is designed to be compatible with NSConstantString, but cannot
5341 // use the same name, since NSConstantString is an interface.
5342 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5343 CFConstantStringTypeDecl =
5344 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005345 }
Mike Stump11289f42009-09-09 15:08:12 +00005346
Quentin Colombet043406b2016-02-03 22:41:00 +00005347 return CFConstantStringTypeDecl;
5348}
5349
Ben Langmuirf5416742016-02-04 00:55:24 +00005350RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5351 if (!CFConstantStringTagDecl)
5352 getCFConstantStringDecl(); // Build the tag and the typedef.
5353 return CFConstantStringTagDecl;
5354}
5355
Quentin Colombet043406b2016-02-03 22:41:00 +00005356// getCFConstantStringType - Return the type used for constant CFStrings.
5357QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005358 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005359}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005360
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005361QualType ASTContext::getObjCSuperType() const {
5362 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005363 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005364 TUDecl->addDecl(ObjCSuperTypeDecl);
5365 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5366 }
5367 return ObjCSuperType;
5368}
5369
Douglas Gregor512b0772009-04-23 22:29:11 +00005370void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005371 const TypedefType *TD = T->getAs<TypedefType>();
5372 assert(TD && "Invalid CFConstantStringType");
5373 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5374 auto TagType =
5375 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5376 assert(TagType && "Invalid CFConstantStringType");
5377 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005378}
5379
Jay Foad39c79802011-01-12 09:06:06 +00005380QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005381 if (BlockDescriptorType)
5382 return getTagDeclType(BlockDescriptorType);
5383
Alp Toker2dea15b2013-12-17 01:22:38 +00005384 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005385 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005386 RD = buildImplicitRecord("__block_descriptor");
5387 RD->startDefinition();
5388
Mike Stumpd0153282009-10-20 02:12:22 +00005389 QualType FieldTypes[] = {
5390 UnsignedLongTy,
5391 UnsignedLongTy,
5392 };
5393
Craig Topperd6d31ac2013-07-15 08:24:27 +00005394 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005395 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005396 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005397 };
5398
5399 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005400 FieldDecl *Field = FieldDecl::Create(
5401 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005402 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5403 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005404 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005405 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005406 }
5407
Alp Toker2dea15b2013-12-17 01:22:38 +00005408 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005409
Alp Toker2dea15b2013-12-17 01:22:38 +00005410 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005411
5412 return getTagDeclType(BlockDescriptorType);
5413}
5414
Jay Foad39c79802011-01-12 09:06:06 +00005415QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005416 if (BlockDescriptorExtendedType)
5417 return getTagDeclType(BlockDescriptorExtendedType);
5418
Alp Toker2dea15b2013-12-17 01:22:38 +00005419 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005420 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005421 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5422 RD->startDefinition();
5423
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005424 QualType FieldTypes[] = {
5425 UnsignedLongTy,
5426 UnsignedLongTy,
5427 getPointerType(VoidPtrTy),
5428 getPointerType(VoidPtrTy)
5429 };
5430
Craig Topperd6d31ac2013-07-15 08:24:27 +00005431 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005432 "reserved",
5433 "Size",
5434 "CopyFuncPtr",
5435 "DestroyFuncPtr"
5436 };
5437
5438 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005439 FieldDecl *Field = FieldDecl::Create(
5440 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005441 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5442 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005443 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005444 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005445 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005446 }
5447
Alp Toker2dea15b2013-12-17 01:22:38 +00005448 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005449
Alp Toker2dea15b2013-12-17 01:22:38 +00005450 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005451 return getTagDeclType(BlockDescriptorExtendedType);
5452}
5453
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005454/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5455/// requires copy/dispose. Note that this must match the logic
5456/// in buildByrefHelpers.
5457bool ASTContext::BlockRequiresCopying(QualType Ty,
5458 const VarDecl *D) {
5459 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5460 const Expr *copyExpr = getBlockVarCopyInits(D);
5461 if (!copyExpr && record->hasTrivialDestructor()) return false;
5462
Mike Stump94967902009-10-21 18:16:27 +00005463 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005464 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005465
5466 if (!Ty->isObjCRetainableType()) return false;
5467
5468 Qualifiers qs = Ty.getQualifiers();
5469
5470 // If we have lifetime, that dominates.
5471 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005472 switch (lifetime) {
5473 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5474
5475 // These are just bits as far as the runtime is concerned.
5476 case Qualifiers::OCL_ExplicitNone:
5477 case Qualifiers::OCL_Autoreleasing:
5478 return false;
5479
5480 // Tell the runtime that this is ARC __weak, called by the
5481 // byref routines.
5482 case Qualifiers::OCL_Weak:
5483 // ARC __strong __block variables need to be retained.
5484 case Qualifiers::OCL_Strong:
5485 return true;
5486 }
5487 llvm_unreachable("fell out of lifetime switch!");
5488 }
5489 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5490 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005491}
5492
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005493bool ASTContext::getByrefLifetime(QualType Ty,
5494 Qualifiers::ObjCLifetime &LifeTime,
5495 bool &HasByrefExtendedLayout) const {
5496
5497 if (!getLangOpts().ObjC1 ||
5498 getLangOpts().getGC() != LangOptions::NonGC)
5499 return false;
5500
5501 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005502 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005503 HasByrefExtendedLayout = true;
5504 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005505 } else if ((LifeTime = Ty.getObjCLifetime())) {
5506 // Honor the ARC qualifiers.
5507 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5508 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005509 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005510 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005511 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005512 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005513 return true;
5514}
5515
Douglas Gregorbab8a962011-09-08 01:46:34 +00005516TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5517 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005518 ObjCInstanceTypeDecl =
5519 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005520 return ObjCInstanceTypeDecl;
5521}
5522
Anders Carlsson18acd442007-10-29 06:33:42 +00005523// This returns true if a type has been typedefed to BOOL:
5524// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005525static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005526 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005527 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5528 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005529
Anders Carlssond8499822007-10-29 05:01:08 +00005530 return false;
5531}
5532
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005533/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005534/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005535CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005536 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5537 return CharUnits::Zero();
5538
Ken Dyck40775002010-01-11 17:06:35 +00005539 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005540
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005541 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005542 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005543 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005544 // Treat arrays as pointers, since that's how they're passed in.
5545 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005546 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005547 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005548}
5549
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005550bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005551 return getTargetInfo().getCXXABI().isMicrosoft() &&
5552 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005553 VD->getType()->isIntegralOrEnumerationType() &&
5554 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005555}
5556
Richard Smithd9b90092016-07-02 01:32:16 +00005557ASTContext::InlineVariableDefinitionKind
5558ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5559 if (!VD->isInline())
5560 return InlineVariableDefinitionKind::None;
5561
5562 // In almost all cases, it's a weak definition.
5563 auto *First = VD->getFirstDecl();
5564 if (!First->isConstexpr() || First->isInlineSpecified() ||
5565 !VD->isStaticDataMember())
5566 return InlineVariableDefinitionKind::Weak;
5567
5568 // If there's a file-context declaration in this translation unit, it's a
5569 // non-discardable definition.
5570 for (auto *D : VD->redecls())
5571 if (D->getLexicalDeclContext()->isFileContext())
5572 return InlineVariableDefinitionKind::Strong;
5573
5574 // If we've not seen one yet, we don't know.
5575 return InlineVariableDefinitionKind::WeakUnknown;
5576}
5577
Ken Dyck40775002010-01-11 17:06:35 +00005578static inline
5579std::string charUnitsToString(const CharUnits &CU) {
5580 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005581}
5582
John McCall351762c2011-02-07 10:33:21 +00005583/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005584/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005585std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5586 std::string S;
5587
David Chisnall950a9512009-11-17 19:33:30 +00005588 const BlockDecl *Decl = Expr->getBlockDecl();
5589 QualType BlockTy =
5590 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5591 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005592 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005593 getObjCEncodingForMethodParameter(
5594 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5595 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005596 else
Alp Toker314cc812014-01-25 16:55:45 +00005597 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005598 // Compute size of all parameters.
5599 // Start with computing size of a pointer in number of bytes.
5600 // FIXME: There might(should) be a better way of doing this computation!
5601 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005602 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5603 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005604 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005605 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005606 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005607 if (sz.isZero())
5608 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005609 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005610 ParmOffset += sz;
5611 }
5612 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005613 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005614 // Block pointer and offset.
5615 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005616
5617 // Argument types.
5618 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005619 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005620 QualType PType = PVDecl->getOriginalType();
5621 if (const ArrayType *AT =
5622 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5623 // Use array's original type only if it has known number of
5624 // elements.
5625 if (!isa<ConstantArrayType>(AT))
5626 PType = PVDecl->getType();
5627 } else if (PType->isFunctionType())
5628 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005629 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005630 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5631 S, true /*Extended*/);
5632 else
5633 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005634 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005635 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005636 }
John McCall351762c2011-02-07 10:33:21 +00005637
5638 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005639}
5640
John McCall843dfcc2016-11-29 21:57:00 +00005641std::string
5642ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5643 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005644 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005645 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005646 CharUnits ParmOffset;
5647 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005648 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005649 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005650 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005651 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005652 continue;
5653
John McCall843dfcc2016-11-29 21:57:00 +00005654 assert(sz.isPositive() &&
5655 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005656 ParmOffset += sz;
5657 }
5658 S += charUnitsToString(ParmOffset);
5659 ParmOffset = CharUnits::Zero();
5660
5661 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005662 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005663 QualType PType = PVDecl->getOriginalType();
5664 if (const ArrayType *AT =
5665 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5666 // Use array's original type only if it has known number of
5667 // elements.
5668 if (!isa<ConstantArrayType>(AT))
5669 PType = PVDecl->getType();
5670 } else if (PType->isFunctionType())
5671 PType = PVDecl->getType();
5672 getObjCEncodingForType(PType, S);
5673 S += charUnitsToString(ParmOffset);
5674 ParmOffset += getObjCEncodingTypeSize(PType);
5675 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005676
John McCall843dfcc2016-11-29 21:57:00 +00005677 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005678}
5679
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005680/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5681/// method parameter or return type. If Extended, include class names and
5682/// block object types.
5683void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5684 QualType T, std::string& S,
5685 bool Extended) const {
5686 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5687 getObjCEncodingForTypeQualifier(QT, S);
5688 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005689 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005690 true /*OutermostType*/,
5691 false /*EncodingProperty*/,
5692 false /*StructField*/,
5693 Extended /*EncodeBlockParameters*/,
5694 Extended /*EncodeClassNames*/);
5695}
5696
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005697/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005698/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005699std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5700 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005701 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005702 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005703 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005704 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5705 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005706 // Compute size of all parameters.
5707 // Start with computing size of a pointer in number of bytes.
5708 // FIXME: There might(should) be a better way of doing this computation!
5709 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005710 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005711 // The first two arguments (self and _cmd) are pointers; account for
5712 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005713 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005714 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005715 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005716 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005717 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005718 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005719 continue;
5720
Ken Dyck40775002010-01-11 17:06:35 +00005721 assert (sz.isPositive() &&
5722 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005723 ParmOffset += sz;
5724 }
Ken Dyck40775002010-01-11 17:06:35 +00005725 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005726 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005727 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005728
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005729 // Argument types.
5730 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005731 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005732 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005733 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005734 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005735 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005736 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5737 // Use array's original type only if it has known number of
5738 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005739 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005740 PType = PVDecl->getType();
5741 } else if (PType->isFunctionType())
5742 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005743 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5744 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005745 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005746 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005747 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005748
John McCall843dfcc2016-11-29 21:57:00 +00005749 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005750}
5751
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005752ObjCPropertyImplDecl *
5753ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5754 const ObjCPropertyDecl *PD,
5755 const Decl *Container) const {
5756 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005757 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005758 if (const ObjCCategoryImplDecl *CID =
5759 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005760 for (auto *PID : CID->property_impls())
5761 if (PID->getPropertyDecl() == PD)
5762 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005763 } else {
5764 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5765 for (auto *PID : OID->property_impls())
5766 if (PID->getPropertyDecl() == PD)
5767 return PID;
5768 }
5769 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005770}
5771
Daniel Dunbar4932b362008-08-28 04:38:10 +00005772/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005773/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005774/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5775/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005776/// Property attributes are stored as a comma-delimited C string. The simple
5777/// attributes readonly and bycopy are encoded as single characters. The
5778/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5779/// encoded as single characters, followed by an identifier. Property types
5780/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005781/// these attributes are defined by the following enumeration:
5782/// @code
5783/// enum PropertyAttributes {
5784/// kPropertyReadOnly = 'R', // property is read-only.
5785/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5786/// kPropertyByref = '&', // property is a reference to the value last assigned
5787/// kPropertyDynamic = 'D', // property is dynamic
5788/// kPropertyGetter = 'G', // followed by getter selector name
5789/// kPropertySetter = 'S', // followed by setter selector name
5790/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005791/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005792/// kPropertyWeak = 'W' // 'weak' property
5793/// kPropertyStrong = 'P' // property GC'able
5794/// kPropertyNonAtomic = 'N' // property non-atomic
5795/// };
5796/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005797std::string
5798ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5799 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005800 // Collect information from the property implementation decl(s).
5801 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005802 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005803
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005804 if (ObjCPropertyImplDecl *PropertyImpDecl =
5805 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5806 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5807 Dynamic = true;
5808 else
5809 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005810 }
5811
5812 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005813 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005814
5815 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005816 // GCC has some special rules regarding encoding of properties which
5817 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005818 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005819
5820 if (PD->isReadOnly()) {
5821 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005822 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5823 S += ",C";
5824 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5825 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005826 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5827 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005828 } else {
5829 switch (PD->getSetterKind()) {
5830 case ObjCPropertyDecl::Assign: break;
5831 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005832 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005833 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005834 }
5835 }
5836
5837 // It really isn't clear at all what this means, since properties
5838 // are "dynamic by default".
5839 if (Dynamic)
5840 S += ",D";
5841
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005842 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5843 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005844
Daniel Dunbar4932b362008-08-28 04:38:10 +00005845 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5846 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005847 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005848 }
5849
5850 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5851 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005852 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005853 }
5854
5855 if (SynthesizePID) {
5856 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5857 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005858 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005859 }
5860
5861 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005862 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005863}
5864
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005865/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005866/// Another legacy compatibility encoding: 32-bit longs are encoded as
5867/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005868/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5869///
5870void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005871 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005872 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005873 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005874 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005875 else
Jay Foad39c79802011-01-12 09:06:06 +00005876 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005877 PointeeTy = IntTy;
5878 }
5879 }
5880}
5881
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005882void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005883 const FieldDecl *Field,
5884 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005885 // We follow the behavior of gcc, expanding structures which are
5886 // directly pointed to, and expanding embedded structures. Note that
5887 // these rules are sufficient to prevent recursive encoding of the
5888 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005889 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005890 true /* outermost type */, false, false,
5891 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005892}
5893
Joe Groff98ac7d22014-07-07 22:25:15 +00005894void ASTContext::getObjCEncodingForPropertyType(QualType T,
5895 std::string& S) const {
5896 // Encode result type.
5897 // GCC has some special rules regarding encoding of properties which
5898 // closely resembles encoding of ivars.
5899 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5900 true /* outermost type */,
5901 true /* encoding property */);
5902}
5903
John McCall393a78d2012-12-20 02:45:14 +00005904static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5905 BuiltinType::Kind kind) {
5906 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005907 case BuiltinType::Void: return 'v';
5908 case BuiltinType::Bool: return 'B';
5909 case BuiltinType::Char_U:
5910 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005911 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005912 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005913 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005914 case BuiltinType::UInt: return 'I';
5915 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005916 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005917 case BuiltinType::UInt128: return 'T';
5918 case BuiltinType::ULongLong: return 'Q';
5919 case BuiltinType::Char_S:
5920 case BuiltinType::SChar: return 'c';
5921 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005922 case BuiltinType::WChar_S:
5923 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005924 case BuiltinType::Int: return 'i';
5925 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005926 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005927 case BuiltinType::LongLong: return 'q';
5928 case BuiltinType::Int128: return 't';
5929 case BuiltinType::Float: return 'f';
5930 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005931 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005932 case BuiltinType::NullPtr: return '*'; // like char*
5933
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005934 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005935 case BuiltinType::Half:
5936 // FIXME: potentially need @encodes for these!
5937 return ' ';
5938
5939 case BuiltinType::ObjCId:
5940 case BuiltinType::ObjCClass:
5941 case BuiltinType::ObjCSel:
5942 llvm_unreachable("@encoding ObjC primitive type");
5943
5944 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005945#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5946 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005947#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005948 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005949 case BuiltinType::OCLClkEvent:
5950 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005951 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005952 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005953 case BuiltinType::Dependent:
5954#define BUILTIN_TYPE(KIND, ID)
5955#define PLACEHOLDER_TYPE(KIND, ID) \
5956 case BuiltinType::KIND:
5957#include "clang/AST/BuiltinTypes.def"
5958 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005959 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005960 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005961}
5962
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005963static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5964 EnumDecl *Enum = ET->getDecl();
5965
5966 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5967 if (!Enum->isFixed())
5968 return 'i';
5969
5970 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005971 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5972 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005973}
5974
Jay Foad39c79802011-01-12 09:06:06 +00005975static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005976 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005977 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005978 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005979 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5980 // The GNU runtime requires more information; bitfields are encoded as b,
5981 // then the offset (in bits) of the first element, then the type of the
5982 // bitfield, then the size in bits. For example, in this structure:
5983 //
5984 // struct
5985 // {
5986 // int integer;
5987 // int flags:2;
5988 // };
5989 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5990 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5991 // information is not especially sensible, but we're stuck with it for
5992 // compatibility with GCC, although providing it breaks anything that
5993 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005994 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00005995 uint64_t Offset;
5996
5997 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
5998 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
5999 IVD);
6000 } else {
6001 const RecordDecl *RD = FD->getParent();
6002 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6003 Offset = RL.getFieldOffset(FD->getFieldIndex());
6004 }
6005
6006 S += llvm::utostr(Offset);
6007
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006008 if (const EnumType *ET = T->getAs<EnumType>())
6009 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006010 else {
6011 const BuiltinType *BT = T->castAs<BuiltinType>();
6012 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6013 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006014 }
Richard Smithcaf33902011-10-10 18:28:20 +00006015 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006016}
6017
Daniel Dunbar07d07852009-10-18 21:17:35 +00006018// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006019void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6020 bool ExpandPointedToStructures,
6021 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006022 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006023 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006024 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006025 bool StructField,
6026 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006027 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006028 bool EncodePointerToObjCTypedef,
6029 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006030 CanQualType CT = getCanonicalType(T);
6031 switch (CT->getTypeClass()) {
6032 case Type::Builtin:
6033 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006034 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006035 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006036 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6037 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6038 else
6039 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006040 return;
Mike Stump11289f42009-09-09 15:08:12 +00006041
John McCall393a78d2012-12-20 02:45:14 +00006042 case Type::Complex: {
6043 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006044 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006045 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006046 return;
6047 }
John McCall393a78d2012-12-20 02:45:14 +00006048
6049 case Type::Atomic: {
6050 const AtomicType *AT = T->castAs<AtomicType>();
6051 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006052 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006053 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006054 }
John McCall393a78d2012-12-20 02:45:14 +00006055
6056 // encoding for pointer or reference types.
6057 case Type::Pointer:
6058 case Type::LValueReference:
6059 case Type::RValueReference: {
6060 QualType PointeeTy;
6061 if (isa<PointerType>(CT)) {
6062 const PointerType *PT = T->castAs<PointerType>();
6063 if (PT->isObjCSelType()) {
6064 S += ':';
6065 return;
6066 }
6067 PointeeTy = PT->getPointeeType();
6068 } else {
6069 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6070 }
6071
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006072 bool isReadOnly = false;
6073 // For historical/compatibility reasons, the read-only qualifier of the
6074 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6075 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006076 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006077 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006078 if (OutermostType && T.isConstQualified()) {
6079 isReadOnly = true;
6080 S += 'r';
6081 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006082 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006083 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006084 while (P->getAs<PointerType>())
6085 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006086 if (P.isConstQualified()) {
6087 isReadOnly = true;
6088 S += 'r';
6089 }
6090 }
6091 if (isReadOnly) {
6092 // Another legacy compatibility encoding. Some ObjC qualifier and type
6093 // combinations need to be rearranged.
6094 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006095 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006096 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006097 }
Mike Stump11289f42009-09-09 15:08:12 +00006098
Anders Carlssond8499822007-10-29 05:01:08 +00006099 if (PointeeTy->isCharType()) {
6100 // char pointer types should be encoded as '*' unless it is a
6101 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006102 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006103 S += '*';
6104 return;
6105 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006106 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006107 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6108 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6109 S += '#';
6110 return;
6111 }
6112 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6113 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6114 S += '@';
6115 return;
6116 }
6117 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006118 }
Anders Carlssond8499822007-10-29 05:01:08 +00006119 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006120 getLegacyIntegralTypeEncoding(PointeeTy);
6121
Mike Stump11289f42009-09-09 15:08:12 +00006122 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006123 nullptr, false, false, false, false, false, false,
6124 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006125 return;
6126 }
John McCall393a78d2012-12-20 02:45:14 +00006127
6128 case Type::ConstantArray:
6129 case Type::IncompleteArray:
6130 case Type::VariableArray: {
6131 const ArrayType *AT = cast<ArrayType>(CT);
6132
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006133 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006134 // Incomplete arrays are encoded as a pointer to the array element.
6135 S += '^';
6136
Mike Stump11289f42009-09-09 15:08:12 +00006137 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006138 false, ExpandStructures, FD);
6139 } else {
6140 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006141
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006142 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6143 S += llvm::utostr(CAT->getSize().getZExtValue());
6144 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006145 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006146 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6147 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006148 S += '0';
6149 }
Mike Stump11289f42009-09-09 15:08:12 +00006150
6151 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006152 false, ExpandStructures, FD,
6153 false, false, false, false, false, false,
6154 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006155 S += ']';
6156 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006157 return;
6158 }
Mike Stump11289f42009-09-09 15:08:12 +00006159
John McCall393a78d2012-12-20 02:45:14 +00006160 case Type::FunctionNoProto:
6161 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006162 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006163 return;
Mike Stump11289f42009-09-09 15:08:12 +00006164
John McCall393a78d2012-12-20 02:45:14 +00006165 case Type::Record: {
6166 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006167 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006168 // Anonymous structures print as '?'
6169 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6170 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006171 if (ClassTemplateSpecializationDecl *Spec
6172 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6173 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006174 llvm::raw_string_ostream OS(S);
6175 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006176 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006177 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006178 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006179 } else {
6180 S += '?';
6181 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006182 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006183 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006184 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006185 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006186 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006187 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006188 if (FD) {
6189 S += '"';
6190 S += Field->getNameAsString();
6191 S += '"';
6192 }
Mike Stump11289f42009-09-09 15:08:12 +00006193
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006194 // Special case bit-fields.
6195 if (Field->isBitField()) {
6196 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006197 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006198 } else {
6199 QualType qt = Field->getType();
6200 getLegacyIntegralTypeEncoding(qt);
6201 getObjCEncodingForTypeImpl(qt, S, false, true,
6202 FD, /*OutermostType*/false,
6203 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006204 /*StructField*/true,
6205 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006206 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006207 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006208 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006209 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006210 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006211 return;
6212 }
Mike Stump11289f42009-09-09 15:08:12 +00006213
John McCall393a78d2012-12-20 02:45:14 +00006214 case Type::BlockPointer: {
6215 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006216 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006217 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006218 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006219
6220 S += '<';
6221 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006222 getObjCEncodingForTypeImpl(
6223 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6224 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006225 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6226 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006227 // Block self
6228 S += "@?";
6229 // Block parameters
6230 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006231 for (const auto &I : FPT->param_types())
6232 getObjCEncodingForTypeImpl(
6233 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6234 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006235 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6236 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006237 }
6238 S += '>';
6239 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006240 return;
6241 }
Mike Stump11289f42009-09-09 15:08:12 +00006242
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006243 case Type::ObjCObject: {
6244 // hack to match legacy encoding of *id and *Class
6245 QualType Ty = getObjCObjectPointerType(CT);
6246 if (Ty->isObjCIdType()) {
6247 S += "{objc_object=}";
6248 return;
6249 }
6250 else if (Ty->isObjCClassType()) {
6251 S += "{objc_class=}";
6252 return;
6253 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006254 // TODO: Double check to make sure this intentially falls through.
6255 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006256 }
6257
John McCall393a78d2012-12-20 02:45:14 +00006258 case Type::ObjCInterface: {
6259 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006260 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006261 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006262 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006263 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006264 if (ExpandStructures) {
6265 S += '=';
6266 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6267 DeepCollectObjCIvars(OI, true, Ivars);
6268 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6269 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6270 if (Field->isBitField())
6271 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6272 else
6273 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6274 false, false, false, false, false,
6275 EncodePointerToObjCTypedef,
6276 NotEncodedT);
6277 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006278 }
6279 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006280 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006281 }
Mike Stump11289f42009-09-09 15:08:12 +00006282
John McCall393a78d2012-12-20 02:45:14 +00006283 case Type::ObjCObjectPointer: {
6284 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006285 if (OPT->isObjCIdType()) {
6286 S += '@';
6287 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006288 }
Mike Stump11289f42009-09-09 15:08:12 +00006289
Steve Narofff0c86112009-10-28 22:03:49 +00006290 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6291 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6292 // Since this is a binary compatibility issue, need to consult with runtime
6293 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006294 S += '#';
6295 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006296 }
Mike Stump11289f42009-09-09 15:08:12 +00006297
Chris Lattnere7cabb92009-07-13 00:10:46 +00006298 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006299 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006300 ExpandPointedToStructures,
6301 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006302 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006303 // Note that we do extended encoding of protocol qualifer list
6304 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006305 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006306 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006307 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006308 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006309 S += '>';
6310 }
6311 S += '"';
6312 }
6313 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006314 }
Mike Stump11289f42009-09-09 15:08:12 +00006315
Chris Lattnere7cabb92009-07-13 00:10:46 +00006316 QualType PointeeTy = OPT->getPointeeType();
6317 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006318 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6319 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006320 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006321 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006322 // {...};
6323 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006324 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006325 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006326 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6327 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6328 DeepCollectObjCIvars(OI, true, Ivars);
6329 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6330 if (cast<FieldDecl>(Ivars[i]) == FD) {
6331 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006332 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006333 S += '}';
6334 return;
6335 }
6336 }
6337 }
Mike Stump11289f42009-09-09 15:08:12 +00006338 getObjCEncodingForTypeImpl(PointeeTy, S,
6339 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006340 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006341 false, false, false, false, false,
6342 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006343 return;
6344 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006345
6346 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006347 if (OPT->getInterfaceDecl() &&
6348 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006349 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006350 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006351 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006352 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006353 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006354 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006355 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006356 S += '"';
6357 }
6358 return;
6359 }
Mike Stump11289f42009-09-09 15:08:12 +00006360
John McCalla9e6e8d2010-05-17 23:56:34 +00006361 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006362 // FIXME: we shoul do better than that. 'M' is available.
6363 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006364 // This matches gcc's encoding, even though technically it is insufficient.
6365 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006366 case Type::Vector:
6367 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006368 // Until we have a coherent encoding of these three types, issue warning.
6369 { if (NotEncodedT)
6370 *NotEncodedT = T;
6371 return;
6372 }
6373
6374 // We could see an undeduced auto type here during error recovery.
6375 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006376 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006377 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006378 return;
6379
Xiuli Pan9c14e282016-01-09 12:53:17 +00006380 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006381#define ABSTRACT_TYPE(KIND, BASE)
6382#define TYPE(KIND, BASE)
6383#define DEPENDENT_TYPE(KIND, BASE) \
6384 case Type::KIND:
6385#define NON_CANONICAL_TYPE(KIND, BASE) \
6386 case Type::KIND:
6387#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6388 case Type::KIND:
6389#include "clang/AST/TypeNodes.def"
6390 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006391 }
John McCall393a78d2012-12-20 02:45:14 +00006392 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006393}
6394
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006395void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6396 std::string &S,
6397 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006398 bool includeVBases,
6399 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006400 assert(RDecl && "Expected non-null RecordDecl");
6401 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006402 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006403 return;
6404
6405 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6406 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6407 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6408
6409 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006410 for (const auto &BI : CXXRec->bases()) {
6411 if (!BI.isVirtual()) {
6412 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006413 if (base->isEmpty())
6414 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006415 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006416 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6417 std::make_pair(offs, base));
6418 }
6419 }
6420 }
6421
6422 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006423 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006424 uint64_t offs = layout.getFieldOffset(i);
6425 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006426 std::make_pair(offs, Field));
6427 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006428 }
6429
6430 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006431 for (const auto &BI : CXXRec->vbases()) {
6432 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006433 if (base->isEmpty())
6434 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006435 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006436 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6437 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006438 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6439 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006440 }
6441 }
6442
6443 CharUnits size;
6444 if (CXXRec) {
6445 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6446 } else {
6447 size = layout.getSize();
6448 }
6449
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006450#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006451 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006452#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006453 std::multimap<uint64_t, NamedDecl *>::iterator
6454 CurLayObj = FieldOrBaseOffsets.begin();
6455
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006456 if (CXXRec && CXXRec->isDynamicClass() &&
6457 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006458 if (FD) {
6459 S += "\"_vptr$";
6460 std::string recname = CXXRec->getNameAsString();
6461 if (recname.empty()) recname = "?";
6462 S += recname;
6463 S += '"';
6464 }
6465 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006466#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006467 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006468#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006469 }
6470
6471 if (!RDecl->hasFlexibleArrayMember()) {
6472 // Mark the end of the structure.
6473 uint64_t offs = toBits(size);
6474 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006475 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006476 }
6477
6478 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006479#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006480 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006481 if (CurOffs < CurLayObj->first) {
6482 uint64_t padding = CurLayObj->first - CurOffs;
6483 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6484 // packing/alignment of members is different that normal, in which case
6485 // the encoding will be out-of-sync with the real layout.
6486 // If the runtime switches to just consider the size of types without
6487 // taking into account alignment, we could make padding explicit in the
6488 // encoding (e.g. using arrays of chars). The encoding strings would be
6489 // longer then though.
6490 CurOffs += padding;
6491 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006492#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006493
6494 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006495 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006496 break; // reached end of structure.
6497
6498 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6499 // We expand the bases without their virtual bases since those are going
6500 // in the initial structure. Note that this differs from gcc which
6501 // expands virtual bases each time one is encountered in the hierarchy,
6502 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006503 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6504 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006505 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006506#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006507 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006508#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006509 } else {
6510 FieldDecl *field = cast<FieldDecl>(dcl);
6511 if (FD) {
6512 S += '"';
6513 S += field->getNameAsString();
6514 S += '"';
6515 }
6516
6517 if (field->isBitField()) {
6518 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006519#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006520 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006521#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006522 } else {
6523 QualType qt = field->getType();
6524 getLegacyIntegralTypeEncoding(qt);
6525 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6526 /*OutermostType*/false,
6527 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006528 /*StructField*/true,
6529 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006530#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006531 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006532#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006533 }
6534 }
6535 }
6536}
6537
Mike Stump11289f42009-09-09 15:08:12 +00006538void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006539 std::string& S) const {
6540 if (QT & Decl::OBJC_TQ_In)
6541 S += 'n';
6542 if (QT & Decl::OBJC_TQ_Inout)
6543 S += 'N';
6544 if (QT & Decl::OBJC_TQ_Out)
6545 S += 'o';
6546 if (QT & Decl::OBJC_TQ_Bycopy)
6547 S += 'O';
6548 if (QT & Decl::OBJC_TQ_Byref)
6549 S += 'R';
6550 if (QT & Decl::OBJC_TQ_Oneway)
6551 S += 'V';
6552}
6553
Douglas Gregor3ea72692011-08-12 05:46:01 +00006554TypedefDecl *ASTContext::getObjCIdDecl() const {
6555 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006556 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006557 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006558 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006559 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006560 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006561}
6562
Douglas Gregor52e02802011-08-12 06:17:30 +00006563TypedefDecl *ASTContext::getObjCSelDecl() const {
6564 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006565 QualType T = getPointerType(ObjCBuiltinSelTy);
6566 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006567 }
6568 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006569}
6570
Douglas Gregor0a586182011-08-12 05:59:41 +00006571TypedefDecl *ASTContext::getObjCClassDecl() const {
6572 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006573 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006574 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006575 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006576 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006577 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006578}
6579
Douglas Gregord53ae832012-01-17 18:09:05 +00006580ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6581 if (!ObjCProtocolClassDecl) {
6582 ObjCProtocolClassDecl
6583 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6584 SourceLocation(),
6585 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006586 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006587 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006588 SourceLocation(), true);
6589 }
6590
6591 return ObjCProtocolClassDecl;
6592}
6593
Meador Inge5d3fb222012-06-16 03:34:49 +00006594//===----------------------------------------------------------------------===//
6595// __builtin_va_list Construction Functions
6596//===----------------------------------------------------------------------===//
6597
Charles Davisc7d5c942015-09-17 20:55:33 +00006598static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6599 StringRef Name) {
6600 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006601 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006602 return Context->buildImplicitTypedef(T, Name);
6603}
6604
6605static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6606 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6607}
6608
6609static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6610 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006611}
6612
6613static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6614 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006615 QualType T = Context->getPointerType(Context->VoidTy);
6616 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006617}
6618
Tim Northover9bb857a2013-01-31 12:13:10 +00006619static TypedefDecl *
6620CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006621 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006622 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006623 if (Context->getLangOpts().CPlusPlus) {
6624 // namespace std { struct __va_list {
6625 NamespaceDecl *NS;
6626 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6627 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006628 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006629 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006630 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006631 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006632 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006633 }
6634
6635 VaListTagDecl->startDefinition();
6636
6637 const size_t NumFields = 5;
6638 QualType FieldTypes[NumFields];
6639 const char *FieldNames[NumFields];
6640
6641 // void *__stack;
6642 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6643 FieldNames[0] = "__stack";
6644
6645 // void *__gr_top;
6646 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6647 FieldNames[1] = "__gr_top";
6648
6649 // void *__vr_top;
6650 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6651 FieldNames[2] = "__vr_top";
6652
6653 // int __gr_offs;
6654 FieldTypes[3] = Context->IntTy;
6655 FieldNames[3] = "__gr_offs";
6656
6657 // int __vr_offs;
6658 FieldTypes[4] = Context->IntTy;
6659 FieldNames[4] = "__vr_offs";
6660
6661 // Create fields
6662 for (unsigned i = 0; i < NumFields; ++i) {
6663 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6664 VaListTagDecl,
6665 SourceLocation(),
6666 SourceLocation(),
6667 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006668 FieldTypes[i], /*TInfo=*/nullptr,
6669 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006670 /*Mutable=*/false,
6671 ICIS_NoInit);
6672 Field->setAccess(AS_public);
6673 VaListTagDecl->addDecl(Field);
6674 }
6675 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006676 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006677 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006678
6679 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006680 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006681}
6682
Meador Inge5d3fb222012-06-16 03:34:49 +00006683static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6684 // typedef struct __va_list_tag {
6685 RecordDecl *VaListTagDecl;
6686
Alp Toker2dea15b2013-12-17 01:22:38 +00006687 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006688 VaListTagDecl->startDefinition();
6689
6690 const size_t NumFields = 5;
6691 QualType FieldTypes[NumFields];
6692 const char *FieldNames[NumFields];
6693
6694 // unsigned char gpr;
6695 FieldTypes[0] = Context->UnsignedCharTy;
6696 FieldNames[0] = "gpr";
6697
6698 // unsigned char fpr;
6699 FieldTypes[1] = Context->UnsignedCharTy;
6700 FieldNames[1] = "fpr";
6701
6702 // unsigned short reserved;
6703 FieldTypes[2] = Context->UnsignedShortTy;
6704 FieldNames[2] = "reserved";
6705
6706 // void* overflow_arg_area;
6707 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6708 FieldNames[3] = "overflow_arg_area";
6709
6710 // void* reg_save_area;
6711 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6712 FieldNames[4] = "reg_save_area";
6713
6714 // Create fields
6715 for (unsigned i = 0; i < NumFields; ++i) {
6716 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6717 SourceLocation(),
6718 SourceLocation(),
6719 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006720 FieldTypes[i], /*TInfo=*/nullptr,
6721 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006722 /*Mutable=*/false,
6723 ICIS_NoInit);
6724 Field->setAccess(AS_public);
6725 VaListTagDecl->addDecl(Field);
6726 }
6727 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006728 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006729 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6730
6731 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006732 TypedefDecl *VaListTagTypedefDecl =
6733 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6734
Meador Inge5d3fb222012-06-16 03:34:49 +00006735 QualType VaListTagTypedefType =
6736 Context->getTypedefType(VaListTagTypedefDecl);
6737
6738 // typedef __va_list_tag __builtin_va_list[1];
6739 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6740 QualType VaListTagArrayType
6741 = Context->getConstantArrayType(VaListTagTypedefType,
6742 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006743 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006744}
6745
6746static TypedefDecl *
6747CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006748 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006749 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006750 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006751 VaListTagDecl->startDefinition();
6752
6753 const size_t NumFields = 4;
6754 QualType FieldTypes[NumFields];
6755 const char *FieldNames[NumFields];
6756
6757 // unsigned gp_offset;
6758 FieldTypes[0] = Context->UnsignedIntTy;
6759 FieldNames[0] = "gp_offset";
6760
6761 // unsigned fp_offset;
6762 FieldTypes[1] = Context->UnsignedIntTy;
6763 FieldNames[1] = "fp_offset";
6764
6765 // void* overflow_arg_area;
6766 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6767 FieldNames[2] = "overflow_arg_area";
6768
6769 // void* reg_save_area;
6770 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6771 FieldNames[3] = "reg_save_area";
6772
6773 // Create fields
6774 for (unsigned i = 0; i < NumFields; ++i) {
6775 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6776 VaListTagDecl,
6777 SourceLocation(),
6778 SourceLocation(),
6779 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006780 FieldTypes[i], /*TInfo=*/nullptr,
6781 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006782 /*Mutable=*/false,
6783 ICIS_NoInit);
6784 Field->setAccess(AS_public);
6785 VaListTagDecl->addDecl(Field);
6786 }
6787 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006788 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006789 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6790
Richard Smith9b88a4c2015-07-27 05:40:23 +00006791 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006792
Richard Smith9b88a4c2015-07-27 05:40:23 +00006793 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006794 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006795 QualType VaListTagArrayType =
6796 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006797 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006798}
6799
6800static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6801 // typedef int __builtin_va_list[4];
6802 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006803 QualType IntArrayType =
6804 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006805 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006806}
6807
Logan Chien57086ce2012-10-10 06:56:20 +00006808static TypedefDecl *
6809CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006810 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006811 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006812 if (Context->getLangOpts().CPlusPlus) {
6813 // namespace std { struct __va_list {
6814 NamespaceDecl *NS;
6815 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6816 Context->getTranslationUnitDecl(),
6817 /*Inline*/false, SourceLocation(),
6818 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006819 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006820 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006821 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006822 }
6823
6824 VaListDecl->startDefinition();
6825
6826 // void * __ap;
6827 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6828 VaListDecl,
6829 SourceLocation(),
6830 SourceLocation(),
6831 &Context->Idents.get("__ap"),
6832 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006833 /*TInfo=*/nullptr,
6834 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006835 /*Mutable=*/false,
6836 ICIS_NoInit);
6837 Field->setAccess(AS_public);
6838 VaListDecl->addDecl(Field);
6839
6840 // };
6841 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006842 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006843
6844 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006845 QualType T = Context->getRecordType(VaListDecl);
6846 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006847}
6848
Ulrich Weigand47445072013-05-06 16:26:41 +00006849static TypedefDecl *
6850CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006851 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006852 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006853 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006854 VaListTagDecl->startDefinition();
6855
6856 const size_t NumFields = 4;
6857 QualType FieldTypes[NumFields];
6858 const char *FieldNames[NumFields];
6859
6860 // long __gpr;
6861 FieldTypes[0] = Context->LongTy;
6862 FieldNames[0] = "__gpr";
6863
6864 // long __fpr;
6865 FieldTypes[1] = Context->LongTy;
6866 FieldNames[1] = "__fpr";
6867
6868 // void *__overflow_arg_area;
6869 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6870 FieldNames[2] = "__overflow_arg_area";
6871
6872 // void *__reg_save_area;
6873 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6874 FieldNames[3] = "__reg_save_area";
6875
6876 // Create fields
6877 for (unsigned i = 0; i < NumFields; ++i) {
6878 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6879 VaListTagDecl,
6880 SourceLocation(),
6881 SourceLocation(),
6882 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006883 FieldTypes[i], /*TInfo=*/nullptr,
6884 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006885 /*Mutable=*/false,
6886 ICIS_NoInit);
6887 Field->setAccess(AS_public);
6888 VaListTagDecl->addDecl(Field);
6889 }
6890 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006891 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006892 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006893
Richard Smith9b88a4c2015-07-27 05:40:23 +00006894 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006895
6896 // typedef __va_list_tag __builtin_va_list[1];
6897 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006898 QualType VaListTagArrayType =
6899 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006900
Alp Toker56b5cc92013-12-15 10:36:26 +00006901 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006902}
6903
Meador Inge5d3fb222012-06-16 03:34:49 +00006904static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6905 TargetInfo::BuiltinVaListKind Kind) {
6906 switch (Kind) {
6907 case TargetInfo::CharPtrBuiltinVaList:
6908 return CreateCharPtrBuiltinVaListDecl(Context);
6909 case TargetInfo::VoidPtrBuiltinVaList:
6910 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006911 case TargetInfo::AArch64ABIBuiltinVaList:
6912 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006913 case TargetInfo::PowerABIBuiltinVaList:
6914 return CreatePowerABIBuiltinVaListDecl(Context);
6915 case TargetInfo::X86_64ABIBuiltinVaList:
6916 return CreateX86_64ABIBuiltinVaListDecl(Context);
6917 case TargetInfo::PNaClABIBuiltinVaList:
6918 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006919 case TargetInfo::AAPCSABIBuiltinVaList:
6920 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006921 case TargetInfo::SystemZBuiltinVaList:
6922 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006923 }
6924
6925 llvm_unreachable("Unhandled __builtin_va_list type kind");
6926}
6927
6928TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006929 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006930 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006931 assert(BuiltinVaListDecl->isImplicit());
6932 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006933
6934 return BuiltinVaListDecl;
6935}
6936
Richard Smith9b88a4c2015-07-27 05:40:23 +00006937Decl *ASTContext::getVaListTagDecl() const {
6938 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006939 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006940 if (!VaListTagDecl)
6941 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006942
Richard Smith9b88a4c2015-07-27 05:40:23 +00006943 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006944}
6945
Charles Davisc7d5c942015-09-17 20:55:33 +00006946TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6947 if (!BuiltinMSVaListDecl)
6948 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6949
6950 return BuiltinMSVaListDecl;
6951}
6952
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006953void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006954 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006955 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006956
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006957 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006958}
6959
John McCalld28ae272009-12-02 08:04:21 +00006960/// \brief Retrieve the template name that corresponds to a non-empty
6961/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006962TemplateName
6963ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6964 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006965 unsigned size = End - Begin;
6966 assert(size > 1 && "set is not overloaded!");
6967
6968 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6969 size * sizeof(FunctionTemplateDecl*));
6970 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6971
6972 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006973 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006974 NamedDecl *D = *I;
6975 assert(isa<FunctionTemplateDecl>(D) ||
6976 (isa<UsingShadowDecl>(D) &&
6977 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6978 *Storage++ = D;
6979 }
6980
6981 return TemplateName(OT);
6982}
6983
Douglas Gregordc572a32009-03-30 22:58:21 +00006984/// \brief Retrieve the template name that represents a qualified
6985/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006986TemplateName
6987ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6988 bool TemplateKeyword,
6989 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006990 assert(NNS && "Missing nested-name-specifier in qualified template name");
6991
Douglas Gregorc42075a2010-02-04 18:10:26 +00006992 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006993 llvm::FoldingSetNodeID ID;
6994 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6995
Craig Topper36250ad2014-05-12 05:36:57 +00006996 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006997 QualifiedTemplateName *QTN =
6998 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6999 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007000 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007001 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007002 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7003 }
7004
7005 return TemplateName(QTN);
7006}
7007
7008/// \brief Retrieve the template name that represents a dependent
7009/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007010TemplateName
7011ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7012 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007013 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007014 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007015
7016 llvm::FoldingSetNodeID ID;
7017 DependentTemplateName::Profile(ID, NNS, Name);
7018
Craig Topper36250ad2014-05-12 05:36:57 +00007019 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007020 DependentTemplateName *QTN =
7021 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7022
7023 if (QTN)
7024 return TemplateName(QTN);
7025
7026 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7027 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007028 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007029 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007030 } else {
7031 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007032 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007033 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007034 DependentTemplateName *CheckQTN =
7035 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7036 assert(!CheckQTN && "Dependent type name canonicalization broken");
7037 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007038 }
7039
7040 DependentTemplateNames.InsertNode(QTN, InsertPos);
7041 return TemplateName(QTN);
7042}
7043
Douglas Gregor71395fa2009-11-04 00:56:37 +00007044/// \brief Retrieve the template name that represents a dependent
7045/// template name such as \c MetaFun::template operator+.
7046TemplateName
7047ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007048 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007049 assert((!NNS || NNS->isDependent()) &&
7050 "Nested name specifier must be dependent");
7051
7052 llvm::FoldingSetNodeID ID;
7053 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007054
7055 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007056 DependentTemplateName *QTN
7057 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007058
7059 if (QTN)
7060 return TemplateName(QTN);
7061
7062 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7063 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007064 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007065 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007066 } else {
7067 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007068 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007069 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007070
Douglas Gregorc42075a2010-02-04 18:10:26 +00007071 DependentTemplateName *CheckQTN
7072 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7073 assert(!CheckQTN && "Dependent template name canonicalization broken");
7074 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007075 }
7076
7077 DependentTemplateNames.InsertNode(QTN, InsertPos);
7078 return TemplateName(QTN);
7079}
7080
Douglas Gregor5590be02011-01-15 06:45:20 +00007081TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007082ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7083 TemplateName replacement) const {
7084 llvm::FoldingSetNodeID ID;
7085 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007086
7087 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007088 SubstTemplateTemplateParmStorage *subst
7089 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7090
7091 if (!subst) {
7092 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7093 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7094 }
7095
7096 return TemplateName(subst);
7097}
7098
7099TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007100ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7101 const TemplateArgument &ArgPack) const {
7102 ASTContext &Self = const_cast<ASTContext &>(*this);
7103 llvm::FoldingSetNodeID ID;
7104 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007105
7106 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007107 SubstTemplateTemplateParmPackStorage *Subst
7108 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7109
7110 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007111 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007112 ArgPack.pack_size(),
7113 ArgPack.pack_begin());
7114 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7115 }
7116
7117 return TemplateName(Subst);
7118}
7119
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007120/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007121/// TargetInfo, produce the corresponding type. The unsigned @p Type
7122/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007123CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007124 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007125 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007126 case TargetInfo::SignedChar: return SignedCharTy;
7127 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007128 case TargetInfo::SignedShort: return ShortTy;
7129 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7130 case TargetInfo::SignedInt: return IntTy;
7131 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7132 case TargetInfo::SignedLong: return LongTy;
7133 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7134 case TargetInfo::SignedLongLong: return LongLongTy;
7135 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7136 }
7137
David Blaikie83d382b2011-09-23 05:06:16 +00007138 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007139}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007140
7141//===----------------------------------------------------------------------===//
7142// Type Predicates.
7143//===----------------------------------------------------------------------===//
7144
Fariborz Jahanian96207692009-02-18 21:49:28 +00007145/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7146/// garbage collection attribute.
7147///
John McCall553d45a2011-01-12 00:34:59 +00007148Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007149 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007150 return Qualifiers::GCNone;
7151
David Blaikiebbafb8a2012-03-11 07:00:24 +00007152 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007153 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7154
7155 // Default behaviour under objective-C's gc is for ObjC pointers
7156 // (or pointers to them) be treated as though they were declared
7157 // as __strong.
7158 if (GCAttrs == Qualifiers::GCNone) {
7159 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7160 return Qualifiers::Strong;
7161 else if (Ty->isPointerType())
7162 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7163 } else {
7164 // It's not valid to set GC attributes on anything that isn't a
7165 // pointer.
7166#ifndef NDEBUG
7167 QualType CT = Ty->getCanonicalTypeInternal();
7168 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7169 CT = AT->getElementType();
7170 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7171#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007172 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007173 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007174}
7175
Chris Lattner49af6a42008-04-07 06:51:04 +00007176//===----------------------------------------------------------------------===//
7177// Type Compatibility Testing
7178//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007179
Mike Stump11289f42009-09-09 15:08:12 +00007180/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007181/// compatible.
7182static bool areCompatVectorTypes(const VectorType *LHS,
7183 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007184 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007185 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007186 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007187}
7188
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007189bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7190 QualType SecondVec) {
7191 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7192 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7193
7194 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7195 return true;
7196
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007197 // Treat Neon vector types and most AltiVec vector types as if they are the
7198 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007199 const VectorType *First = FirstVec->getAs<VectorType>();
7200 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007201 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007202 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007203 First->getVectorKind() != VectorType::AltiVecPixel &&
7204 First->getVectorKind() != VectorType::AltiVecBool &&
7205 Second->getVectorKind() != VectorType::AltiVecPixel &&
7206 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007207 return true;
7208
7209 return false;
7210}
7211
Steve Naroff8e6aee52009-07-23 01:01:38 +00007212//===----------------------------------------------------------------------===//
7213// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7214//===----------------------------------------------------------------------===//
7215
7216/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7217/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007218bool
7219ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7220 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007221 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007222 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007223 for (auto *PI : rProto->protocols())
7224 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007225 return true;
7226 return false;
7227}
7228
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007229/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7230/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007231bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7232 QualType rhs) {
7233 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7234 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7235 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7236
Aaron Ballman83731462014-03-17 16:14:00 +00007237 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007238 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007239 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007240 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7241 match = true;
7242 break;
7243 }
7244 }
7245 if (!match)
7246 return false;
7247 }
7248 return true;
7249}
7250
Steve Naroff8e6aee52009-07-23 01:01:38 +00007251/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7252/// ObjCQualifiedIDType.
7253bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7254 bool compare) {
7255 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007256 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007257 lhs->isObjCIdType() || lhs->isObjCClassType())
7258 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007259 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007260 rhs->isObjCIdType() || rhs->isObjCClassType())
7261 return true;
7262
7263 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007264 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007265
Steve Naroff8e6aee52009-07-23 01:01:38 +00007266 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007267
Steve Naroff8e6aee52009-07-23 01:01:38 +00007268 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007269 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007270 // make sure we check the class hierarchy.
7271 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007272 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007273 // when comparing an id<P> on lhs with a static type on rhs,
7274 // see if static class implements all of id's protocols, directly or
7275 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007276 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007277 return false;
7278 }
7279 }
7280 // If there are no qualifiers and no interface, we have an 'id'.
7281 return true;
7282 }
Mike Stump11289f42009-09-09 15:08:12 +00007283 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007284 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007285 bool match = false;
7286
7287 // when comparing an id<P> on lhs with a static type on rhs,
7288 // see if static class implements all of id's protocols, directly or
7289 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007290 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007291 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7292 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7293 match = true;
7294 break;
7295 }
7296 }
Mike Stump11289f42009-09-09 15:08:12 +00007297 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007298 // make sure we check the class hierarchy.
7299 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007300 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007301 // when comparing an id<P> on lhs with a static type on rhs,
7302 // see if static class implements all of id's protocols, directly or
7303 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007304 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007305 match = true;
7306 break;
7307 }
7308 }
7309 }
7310 if (!match)
7311 return false;
7312 }
Mike Stump11289f42009-09-09 15:08:12 +00007313
Steve Naroff8e6aee52009-07-23 01:01:38 +00007314 return true;
7315 }
Mike Stump11289f42009-09-09 15:08:12 +00007316
Steve Naroff8e6aee52009-07-23 01:01:38 +00007317 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7318 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7319
Mike Stump11289f42009-09-09 15:08:12 +00007320 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007321 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007322 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007323 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007324 bool match = false;
7325
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007326 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007327 // see if static class implements all of id's protocols, directly or
7328 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007329 // First, lhs protocols in the qualifier list must be found, direct
7330 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007331 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007332 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7333 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7334 match = true;
7335 break;
7336 }
7337 }
7338 if (!match)
7339 return false;
7340 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007341
7342 // Static class's protocols, or its super class or category protocols
7343 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7344 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7345 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7346 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7347 // This is rather dubious but matches gcc's behavior. If lhs has
7348 // no type qualifier and its class has no static protocol(s)
7349 // assume that it is mismatch.
7350 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7351 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007352 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007353 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007354 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007355 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7356 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7357 match = true;
7358 break;
7359 }
7360 }
7361 if (!match)
7362 return false;
7363 }
7364 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007365 return true;
7366 }
7367 return false;
7368}
7369
Eli Friedman47f77112008-08-22 00:56:42 +00007370/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007371/// compatible for assignment from RHS to LHS. This handles validation of any
7372/// protocol qualifiers on the LHS or RHS.
7373///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007374bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7375 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007376 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7377 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7378
Steve Naroff1329fa02009-07-15 18:40:39 +00007379 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007380 if (LHS->isObjCUnqualifiedIdOrClass() ||
7381 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007382 return true;
7383
Douglas Gregorab209d82015-07-07 03:58:42 +00007384 // Function object that propagates a successful result or handles
7385 // __kindof types.
7386 auto finish = [&](bool succeeded) -> bool {
7387 if (succeeded)
7388 return true;
7389
7390 if (!RHS->isKindOfType())
7391 return false;
7392
7393 // Strip off __kindof and protocol qualifiers, then check whether
7394 // we can assign the other way.
7395 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7396 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7397 };
7398
7399 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7400 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7401 QualType(RHSOPT,0),
7402 false));
7403 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007404
Douglas Gregorab209d82015-07-07 03:58:42 +00007405 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7406 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7407 QualType(RHSOPT,0)));
7408 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007409
John McCall8b07ec22010-05-15 11:32:37 +00007410 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007411 if (LHS->getInterface() && RHS->getInterface()) {
7412 return finish(canAssignObjCInterfaces(LHS, RHS));
7413 }
Mike Stump11289f42009-09-09 15:08:12 +00007414
Steve Naroff8e6aee52009-07-23 01:01:38 +00007415 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007416}
7417
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007418/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007419/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007420/// arguments in block literals. When passed as arguments, passing 'A*' where
7421/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7422/// not OK. For the return type, the opposite is not OK.
7423bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7424 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007425 const ObjCObjectPointerType *RHSOPT,
7426 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007427
7428 // Function object that propagates a successful result or handles
7429 // __kindof types.
7430 auto finish = [&](bool succeeded) -> bool {
7431 if (succeeded)
7432 return true;
7433
7434 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7435 if (!Expected->isKindOfType())
7436 return false;
7437
7438 // Strip off __kindof and protocol qualifiers, then check whether
7439 // we can assign the other way.
7440 return canAssignObjCInterfacesInBlockPointer(
7441 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7442 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7443 BlockReturnType);
7444 };
7445
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007446 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007447 return true;
7448
7449 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007450 return finish(RHSOPT->isObjCBuiltinType() ||
7451 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007452 }
7453
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007454 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007455 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7456 QualType(RHSOPT,0),
7457 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007458
7459 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7460 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7461 if (LHS && RHS) { // We have 2 user-defined types.
7462 if (LHS != RHS) {
7463 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007464 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007465 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007466 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007467 }
7468 else
7469 return true;
7470 }
7471 return false;
7472}
7473
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007474/// Comparison routine for Objective-C protocols to be used with
7475/// llvm::array_pod_sort.
7476static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7477 ObjCProtocolDecl * const *rhs) {
7478 return (*lhs)->getName().compare((*rhs)->getName());
7479
7480}
7481
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007482/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007483/// of protocols inherited from two distinct objective-c pointer objects with
7484/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007485/// It is used to build composite qualifier list of the composite type of
7486/// the conditional expression involving two objective-c pointer objects.
7487static
7488void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007489 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007490 const ObjCObjectPointerType *LHSOPT,
7491 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007492 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007493
John McCall8b07ec22010-05-15 11:32:37 +00007494 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7495 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7496 assert(LHS->getInterface() && "LHS must have an interface base");
7497 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007498
7499 // Add all of the protocols for the LHS.
7500 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7501
7502 // Start with the protocol qualifiers.
7503 for (auto proto : LHS->quals()) {
7504 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007505 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007506
7507 // Also add the protocols associated with the LHS interface.
7508 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7509
7510 // Add all of the protocls for the RHS.
7511 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7512
7513 // Start with the protocol qualifiers.
7514 for (auto proto : RHS->quals()) {
7515 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007516 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007517
7518 // Also add the protocols associated with the RHS interface.
7519 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7520
7521 // Compute the intersection of the collected protocol sets.
7522 for (auto proto : LHSProtocolSet) {
7523 if (RHSProtocolSet.count(proto))
7524 IntersectionSet.push_back(proto);
7525 }
7526
7527 // Compute the set of protocols that is implied by either the common type or
7528 // the protocols within the intersection.
7529 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7530 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7531
7532 // Remove any implied protocols from the list of inherited protocols.
7533 if (!ImpliedProtocols.empty()) {
7534 IntersectionSet.erase(
7535 std::remove_if(IntersectionSet.begin(),
7536 IntersectionSet.end(),
7537 [&](ObjCProtocolDecl *proto) -> bool {
7538 return ImpliedProtocols.count(proto) > 0;
7539 }),
7540 IntersectionSet.end());
7541 }
7542
7543 // Sort the remaining protocols by name.
7544 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7545 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007546}
7547
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007548/// Determine whether the first type is a subtype of the second.
7549static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7550 QualType rhs) {
7551 // Common case: two object pointers.
7552 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7553 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7554 if (lhsOPT && rhsOPT)
7555 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7556
7557 // Two block pointers.
7558 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7559 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7560 if (lhsBlock && rhsBlock)
7561 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7562
7563 // If either is an unqualified 'id' and the other is a block, it's
7564 // acceptable.
7565 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7566 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7567 return true;
7568
7569 return false;
7570}
7571
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007572// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007573static bool sameObjCTypeArgs(ASTContext &ctx,
7574 const ObjCInterfaceDecl *iface,
7575 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007576 ArrayRef<QualType> rhsArgs,
7577 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007578 if (lhsArgs.size() != rhsArgs.size())
7579 return false;
7580
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007581 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007582 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007583 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7584 continue;
7585
7586 switch (typeParams->begin()[i]->getVariance()) {
7587 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007588 if (!stripKindOf ||
7589 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7590 rhsArgs[i].stripObjCKindOfType(ctx))) {
7591 return false;
7592 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007593 break;
7594
7595 case ObjCTypeParamVariance::Covariant:
7596 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7597 return false;
7598 break;
7599
7600 case ObjCTypeParamVariance::Contravariant:
7601 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7602 return false;
7603 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007604 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007605 }
7606
7607 return true;
7608}
7609
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007610QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007611 const ObjCObjectPointerType *Lptr,
7612 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007613 const ObjCObjectType *LHS = Lptr->getObjectType();
7614 const ObjCObjectType *RHS = Rptr->getObjectType();
7615 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7616 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007617
7618 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007619 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007620
Manman Renc46f7d12016-05-06 19:35:02 +00007621 // When either LHS or RHS is a kindof type, we should return a kindof type.
7622 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7623 // kindof(A).
7624 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7625
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007626 // Follow the left-hand side up the class hierarchy until we either hit a
7627 // root or find the RHS. Record the ancestors in case we don't find it.
7628 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7629 LHSAncestors;
7630 while (true) {
7631 // Record this ancestor. We'll need this if the common type isn't in the
7632 // path from the LHS to the root.
7633 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007634
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007635 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7636 // Get the type arguments.
7637 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7638 bool anyChanges = false;
7639 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7640 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007641 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7642 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007643 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007644 return QualType();
7645 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7646 // If only one has type arguments, the result will not have type
7647 // arguments.
7648 LHSTypeArgs = { };
7649 anyChanges = true;
7650 }
7651
7652 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007653 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007654 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7655 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007656 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007657 anyChanges = true;
7658
7659 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007660 // If we need to return a kindof type but LHS is not a kindof type, we
7661 // build a new result type.
7662 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007663 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007664 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007665 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007666 return getObjCObjectPointerType(Result);
7667 }
7668
7669 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007670 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007671
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007672 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007673 QualType LHSSuperType = LHS->getSuperClassType();
7674 if (LHSSuperType.isNull())
7675 break;
7676
7677 LHS = LHSSuperType->castAs<ObjCObjectType>();
7678 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007679
7680 // We didn't find anything by following the LHS to its root; now check
7681 // the RHS against the cached set of ancestors.
7682 while (true) {
7683 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7684 if (KnownLHS != LHSAncestors.end()) {
7685 LHS = KnownLHS->second;
7686
7687 // Get the type arguments.
7688 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7689 bool anyChanges = false;
7690 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7691 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007692 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7693 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007694 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007695 return QualType();
7696 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7697 // If only one has type arguments, the result will not have type
7698 // arguments.
7699 RHSTypeArgs = { };
7700 anyChanges = true;
7701 }
7702
7703 // Compute the intersection of protocols.
7704 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7705 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7706 Protocols);
7707 if (!Protocols.empty())
7708 anyChanges = true;
7709
Manman Renc46f7d12016-05-06 19:35:02 +00007710 // If we need to return a kindof type but RHS is not a kindof type, we
7711 // build a new result type.
7712 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007713 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007714 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007715 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007716 return getObjCObjectPointerType(Result);
7717 }
7718
7719 return getObjCObjectPointerType(QualType(RHS, 0));
7720 }
7721
7722 // Find the superclass of the RHS.
7723 QualType RHSSuperType = RHS->getSuperClassType();
7724 if (RHSSuperType.isNull())
7725 break;
7726
7727 RHS = RHSSuperType->castAs<ObjCObjectType>();
7728 }
7729
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007730 return QualType();
7731}
7732
John McCall8b07ec22010-05-15 11:32:37 +00007733bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7734 const ObjCObjectType *RHS) {
7735 assert(LHS->getInterface() && "LHS is not an interface type");
7736 assert(RHS->getInterface() && "RHS is not an interface type");
7737
Chris Lattner49af6a42008-04-07 06:51:04 +00007738 // Verify that the base decls are compatible: the RHS must be a subclass of
7739 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007740 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7741 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7742 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007743 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007744
Douglas Gregore83b9562015-07-07 03:57:53 +00007745 // If the LHS has protocol qualifiers, determine whether all of them are
7746 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7747 // LHS).
7748 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007749 // OK if conversion of LHS to SuperClass results in narrowing of types
7750 // ; i.e., SuperClass may implement at least one of the protocols
7751 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7752 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7753 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7754 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7755 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7756 // qualifiers.
7757 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007758 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007759 // If there is no protocols associated with RHS, it is not a match.
7760 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007761 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007762
7763 for (const auto *LHSProto : LHS->quals()) {
7764 bool SuperImplementsProtocol = false;
7765 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7766 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7767 SuperImplementsProtocol = true;
7768 break;
7769 }
7770 if (!SuperImplementsProtocol)
7771 return false;
7772 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007773 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007774
7775 // If the LHS is specialized, we may need to check type arguments.
7776 if (LHS->isSpecialized()) {
7777 // Follow the superclass chain until we've matched the LHS class in the
7778 // hierarchy. This substitutes type arguments through.
7779 const ObjCObjectType *RHSSuper = RHS;
7780 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7781 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7782
7783 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007784 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007785 !sameObjCTypeArgs(*this, LHS->getInterface(),
7786 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007787 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007788 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007789 }
7790 }
7791
7792 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007793}
7794
Steve Naroffb7605152009-02-12 17:52:19 +00007795bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7796 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007797 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7798 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007799
Steve Naroff7cae42b2009-07-10 23:34:53 +00007800 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007801 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007802
7803 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7804 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007805}
7806
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007807bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7808 return canAssignObjCInterfaces(
7809 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7810 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7811}
7812
Mike Stump11289f42009-09-09 15:08:12 +00007813/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007814/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007815/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007816/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007817bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7818 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007819 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007820 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007821
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007822 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007823}
7824
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007825bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007826 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007827}
7828
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007829bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7830 return !mergeTypes(LHS, RHS, true).isNull();
7831}
7832
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007833/// mergeTransparentUnionType - if T is a transparent union type and a member
7834/// of T is compatible with SubType, return the merged type, else return
7835/// QualType()
7836QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7837 bool OfBlockPointer,
7838 bool Unqualified) {
7839 if (const RecordType *UT = T->getAsUnionType()) {
7840 RecordDecl *UD = UT->getDecl();
7841 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007842 for (const auto *I : UD->fields()) {
7843 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007844 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7845 if (!MT.isNull())
7846 return MT;
7847 }
7848 }
7849 }
7850
7851 return QualType();
7852}
7853
Alp Toker9cacbab2014-01-20 20:26:09 +00007854/// mergeFunctionParameterTypes - merge two types which appear as function
7855/// parameter types
7856QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7857 bool OfBlockPointer,
7858 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007859 // GNU extension: two types are compatible if they appear as a function
7860 // argument, one of the types is a transparent union type and the other
7861 // type is compatible with a union member
7862 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7863 Unqualified);
7864 if (!lmerge.isNull())
7865 return lmerge;
7866
7867 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7868 Unqualified);
7869 if (!rmerge.isNull())
7870 return rmerge;
7871
7872 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7873}
7874
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007875QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007876 bool OfBlockPointer,
7877 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007878 const FunctionType *lbase = lhs->getAs<FunctionType>();
7879 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007880 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7881 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007882 bool allLTypes = true;
7883 bool allRTypes = true;
7884
7885 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007886 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007887 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007888 QualType RHS = rbase->getReturnType();
7889 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007890 bool UnqualifiedResult = Unqualified;
7891 if (!UnqualifiedResult)
7892 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007893 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007894 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007895 else
Alp Toker314cc812014-01-25 16:55:45 +00007896 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007897 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007898 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007899
7900 if (Unqualified)
7901 retType = retType.getUnqualifiedType();
7902
Alp Toker314cc812014-01-25 16:55:45 +00007903 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7904 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007905 if (Unqualified) {
7906 LRetType = LRetType.getUnqualifiedType();
7907 RRetType = RRetType.getUnqualifiedType();
7908 }
7909
7910 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007911 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007912 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007913 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007914
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007915 // FIXME: double check this
7916 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7917 // rbase->getRegParmAttr() != 0 &&
7918 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007919 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7920 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007921
Douglas Gregor8c940862010-01-18 17:14:39 +00007922 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007923 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007924 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007925
John McCall8c6b56f2010-12-15 01:06:38 +00007926 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007927 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7928 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007929 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7930 return QualType();
7931
John McCall31168b02011-06-15 23:02:42 +00007932 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7933 return QualType();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00007934 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
7935 return QualType();
John McCall31168b02011-06-15 23:02:42 +00007936
John McCall8c6b56f2010-12-15 01:06:38 +00007937 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7938 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007939
Rafael Espindola8778c282012-11-29 16:09:03 +00007940 if (lbaseInfo.getNoReturn() != NoReturn)
7941 allLTypes = false;
7942 if (rbaseInfo.getNoReturn() != NoReturn)
7943 allRTypes = false;
7944
John McCall31168b02011-06-15 23:02:42 +00007945 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007946
Eli Friedman47f77112008-08-22 00:56:42 +00007947 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007948 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7949 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007950 // Compatible functions must have the same number of parameters
7951 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007952 return QualType();
7953
7954 // Variadic and non-variadic functions aren't compatible
7955 if (lproto->isVariadic() != rproto->isVariadic())
7956 return QualType();
7957
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007958 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7959 return QualType();
7960
John McCall18afab72016-03-01 00:49:02 +00007961 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007962 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007963
7964 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007965 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007966 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7967 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7968 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7969 QualType paramType = mergeFunctionParameterTypes(
7970 lParamType, rParamType, OfBlockPointer, Unqualified);
7971 if (paramType.isNull())
7972 return QualType();
7973
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007974 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007975 paramType = paramType.getUnqualifiedType();
7976
7977 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007978 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007979 lParamType = lParamType.getUnqualifiedType();
7980 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007981 }
Alp Toker601b22c2014-01-21 23:35:24 +00007982
7983 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007984 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007985 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007986 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007987 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007988
Eli Friedman47f77112008-08-22 00:56:42 +00007989 if (allLTypes) return lhs;
7990 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007991
7992 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7993 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007994 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007995 }
7996
7997 if (lproto) allRTypes = false;
7998 if (rproto) allLTypes = false;
7999
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008000 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008001 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008002 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00008003 if (proto->isVariadic()) return QualType();
8004 // Check that the types are compatible with the types that
8005 // would result from default argument promotions (C99 6.7.5.3p15).
8006 // The only types actually affected are promotable integer
8007 // types and floats, which would be passed as a different
8008 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008009 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8010 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008011
Eli Friedman448ce402012-08-30 00:44:15 +00008012 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008013 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00008014 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8015 paramTy = Enum->getDecl()->getIntegerType();
8016 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008017 return QualType();
8018 }
Alp Toker601b22c2014-01-21 23:35:24 +00008019
8020 if (paramTy->isPromotableIntegerType() ||
8021 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008022 return QualType();
8023 }
8024
8025 if (allLTypes) return lhs;
8026 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008027
8028 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8029 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008030 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008031 }
8032
8033 if (allLTypes) return lhs;
8034 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008035 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008036}
8037
John McCall433c2e62013-03-21 00:10:07 +00008038/// Given that we have an enum type and a non-enum type, try to merge them.
8039static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8040 QualType other, bool isBlockReturnType) {
8041 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8042 // a signed integer type, or an unsigned integer type.
8043 // Compatibility is based on the underlying type, not the promotion
8044 // type.
8045 QualType underlyingType = ET->getDecl()->getIntegerType();
8046 if (underlyingType.isNull()) return QualType();
8047 if (Context.hasSameType(underlyingType, other))
8048 return other;
8049
8050 // In block return types, we're more permissive and accept any
8051 // integral type of the same size.
8052 if (isBlockReturnType && other->isIntegerType() &&
8053 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8054 return other;
8055
8056 return QualType();
8057}
8058
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008059QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008060 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008061 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008062 // C++ [expr]: If an expression initially has the type "reference to T", the
8063 // type is adjusted to "T" prior to any further analysis, the expression
8064 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008065 // expression is an lvalue unless the reference is an rvalue reference and
8066 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008067 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8068 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008069
8070 if (Unqualified) {
8071 LHS = LHS.getUnqualifiedType();
8072 RHS = RHS.getUnqualifiedType();
8073 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008074
Eli Friedman47f77112008-08-22 00:56:42 +00008075 QualType LHSCan = getCanonicalType(LHS),
8076 RHSCan = getCanonicalType(RHS);
8077
8078 // If two types are identical, they are compatible.
8079 if (LHSCan == RHSCan)
8080 return LHS;
8081
John McCall8ccfcb52009-09-24 19:53:00 +00008082 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008083 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8084 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008085 if (LQuals != RQuals) {
8086 // If any of these qualifiers are different, we have a type
8087 // mismatch.
8088 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008089 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008090 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8091 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008092 return QualType();
8093
8094 // Exactly one GC qualifier difference is allowed: __strong is
8095 // okay if the other type has no GC qualifier but is an Objective
8096 // C object pointer (i.e. implicitly strong by default). We fix
8097 // this by pretending that the unqualified type was actually
8098 // qualified __strong.
8099 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8100 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8101 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8102
8103 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8104 return QualType();
8105
8106 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8107 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8108 }
8109 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8110 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8111 }
Eli Friedman47f77112008-08-22 00:56:42 +00008112 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008113 }
8114
8115 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008116
Eli Friedmandcca6332009-06-01 01:22:52 +00008117 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8118 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008119
Chris Lattnerfd652912008-01-14 05:45:46 +00008120 // We want to consider the two function types to be the same for these
8121 // comparisons, just force one to the other.
8122 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8123 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008124
8125 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008126 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8127 LHSClass = Type::ConstantArray;
8128 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8129 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008130
John McCall8b07ec22010-05-15 11:32:37 +00008131 // ObjCInterfaces are just specialized ObjCObjects.
8132 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8133 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8134
Nate Begemance4d7fc2008-04-18 23:10:10 +00008135 // Canonicalize ExtVector -> Vector.
8136 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8137 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008138
Chris Lattner95554662008-04-07 05:43:21 +00008139 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008140 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008141 // Note that we only have special rules for turning block enum
8142 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008143 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008144 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008145 }
John McCall9dd450b2009-09-21 23:43:11 +00008146 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008147 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008148 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008149 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008150 if (OfBlockPointer && !BlockReturnType) {
8151 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8152 return LHS;
8153 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8154 return RHS;
8155 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008156
Eli Friedman47f77112008-08-22 00:56:42 +00008157 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008158 }
Eli Friedman47f77112008-08-22 00:56:42 +00008159
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008160 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008161 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008162#define TYPE(Class, Base)
8163#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008164#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008165#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8166#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8167#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008168 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008169
Richard Smith27d807c2013-04-30 13:56:41 +00008170 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008171 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008172 case Type::LValueReference:
8173 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008174 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008175 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008176
John McCall8b07ec22010-05-15 11:32:37 +00008177 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008178 case Type::IncompleteArray:
8179 case Type::VariableArray:
8180 case Type::FunctionProto:
8181 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008182 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008183
Chris Lattnerfd652912008-01-14 05:45:46 +00008184 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008185 {
8186 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008187 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8188 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008189 if (Unqualified) {
8190 LHSPointee = LHSPointee.getUnqualifiedType();
8191 RHSPointee = RHSPointee.getUnqualifiedType();
8192 }
8193 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8194 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008195 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008196 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008197 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008198 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008199 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008200 return getPointerType(ResultType);
8201 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008202 case Type::BlockPointer:
8203 {
8204 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008205 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8206 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008207 if (Unqualified) {
8208 LHSPointee = LHSPointee.getUnqualifiedType();
8209 RHSPointee = RHSPointee.getUnqualifiedType();
8210 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008211 if (getLangOpts().OpenCL) {
8212 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8213 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8214 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8215 // 6.12.5) thus the following check is asymmetric.
8216 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8217 return QualType();
8218 LHSPteeQual.removeAddressSpace();
8219 RHSPteeQual.removeAddressSpace();
8220 LHSPointee =
8221 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8222 RHSPointee =
8223 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8224 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008225 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8226 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008227 if (ResultType.isNull()) return QualType();
8228 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8229 return LHS;
8230 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8231 return RHS;
8232 return getBlockPointerType(ResultType);
8233 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008234 case Type::Atomic:
8235 {
8236 // Merge two pointer types, while trying to preserve typedef info
8237 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8238 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8239 if (Unqualified) {
8240 LHSValue = LHSValue.getUnqualifiedType();
8241 RHSValue = RHSValue.getUnqualifiedType();
8242 }
8243 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8244 Unqualified);
8245 if (ResultType.isNull()) return QualType();
8246 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8247 return LHS;
8248 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8249 return RHS;
8250 return getAtomicType(ResultType);
8251 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008252 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008253 {
8254 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8255 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8256 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8257 return QualType();
8258
8259 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8260 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008261 if (Unqualified) {
8262 LHSElem = LHSElem.getUnqualifiedType();
8263 RHSElem = RHSElem.getUnqualifiedType();
8264 }
8265
8266 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008267 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008268 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8269 return LHS;
8270 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8271 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008272 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8273 ArrayType::ArraySizeModifier(), 0);
8274 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8275 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008276 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8277 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008278 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8279 return LHS;
8280 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8281 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008282 if (LVAT) {
8283 // FIXME: This isn't correct! But tricky to implement because
8284 // the array's size has to be the size of LHS, but the type
8285 // has to be different.
8286 return LHS;
8287 }
8288 if (RVAT) {
8289 // FIXME: This isn't correct! But tricky to implement because
8290 // the array's size has to be the size of RHS, but the type
8291 // has to be different.
8292 return RHS;
8293 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008294 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8295 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008296 return getIncompleteArrayType(ResultType,
8297 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008298 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008299 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008300 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008301 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008302 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008303 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008304 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008305 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008306 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008307 case Type::Complex:
8308 // Distinct complex types are incompatible.
8309 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008310 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008311 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008312 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8313 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008314 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008315 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008316 case Type::ObjCObject: {
8317 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008318 // FIXME: This should be type compatibility, e.g. whether
8319 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008320 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8321 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8322 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008323 return LHS;
8324
Eli Friedman47f77112008-08-22 00:56:42 +00008325 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008326 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008327 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008328 if (OfBlockPointer) {
8329 if (canAssignObjCInterfacesInBlockPointer(
8330 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008331 RHS->getAs<ObjCObjectPointerType>(),
8332 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008333 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008334 return QualType();
8335 }
John McCall9dd450b2009-09-21 23:43:11 +00008336 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8337 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008338 return LHS;
8339
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008340 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008341 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008342 case Type::Pipe:
8343 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008344 assert(LHS != RHS &&
8345 "Equivalent pipe types should have already been handled!");
8346 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008347 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008348 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008349
David Blaikie8a40f702012-01-17 06:56:22 +00008350 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008351}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008352
John McCall18afab72016-03-01 00:49:02 +00008353bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8354 const FunctionProtoType *firstFnType,
8355 const FunctionProtoType *secondFnType) {
8356 // Fast path: if the first type doesn't have ext parameter infos,
8357 // we match if and only if they second type also doesn't have them.
8358 if (!firstFnType->hasExtParameterInfos())
8359 return !secondFnType->hasExtParameterInfos();
8360
8361 // Otherwise, we can only match if the second type has them.
8362 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008363 return false;
John McCall18afab72016-03-01 00:49:02 +00008364
8365 auto firstEPI = firstFnType->getExtParameterInfos();
8366 auto secondEPI = secondFnType->getExtParameterInfos();
8367 assert(firstEPI.size() == secondEPI.size());
8368
8369 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8370 if (firstEPI[i] != secondEPI[i])
8371 return false;
8372 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008373 return true;
8374}
8375
Chandler Carruth21c90602015-12-30 03:24:14 +00008376void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8377 ObjCLayouts[CD] = nullptr;
8378}
8379
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008380/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8381/// 'RHS' attributes and returns the merged version; including for function
8382/// return types.
8383QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8384 QualType LHSCan = getCanonicalType(LHS),
8385 RHSCan = getCanonicalType(RHS);
8386 // If two types are identical, they are compatible.
8387 if (LHSCan == RHSCan)
8388 return LHS;
8389 if (RHSCan->isFunctionType()) {
8390 if (!LHSCan->isFunctionType())
8391 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008392 QualType OldReturnType =
8393 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008394 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008395 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008396 QualType ResReturnType =
8397 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8398 if (ResReturnType.isNull())
8399 return QualType();
8400 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8401 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8402 // In either case, use OldReturnType to build the new function type.
8403 const FunctionType *F = LHS->getAs<FunctionType>();
8404 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008405 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8406 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008407 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008408 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008409 return ResultType;
8410 }
8411 }
8412 return QualType();
8413 }
8414
8415 // If the qualifiers are different, the types can still be merged.
8416 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8417 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8418 if (LQuals != RQuals) {
8419 // If any of these qualifiers are different, we have a type mismatch.
8420 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8421 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8422 return QualType();
8423
8424 // Exactly one GC qualifier difference is allowed: __strong is
8425 // okay if the other type has no GC qualifier but is an Objective
8426 // C object pointer (i.e. implicitly strong by default). We fix
8427 // this by pretending that the unqualified type was actually
8428 // qualified __strong.
8429 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8430 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8431 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8432
8433 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8434 return QualType();
8435
8436 if (GC_L == Qualifiers::Strong)
8437 return LHS;
8438 if (GC_R == Qualifiers::Strong)
8439 return RHS;
8440 return QualType();
8441 }
8442
8443 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8444 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8445 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8446 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8447 if (ResQT == LHSBaseQT)
8448 return LHS;
8449 if (ResQT == RHSBaseQT)
8450 return RHS;
8451 }
8452 return QualType();
8453}
8454
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008455//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008456// Integer Predicates
8457//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008458
Jay Foad39c79802011-01-12 09:06:06 +00008459unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008460 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008461 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008462 if (T->isBooleanType())
8463 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008464 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008465 return (unsigned)getTypeSize(T);
8466}
8467
Abramo Bagnara13640492012-09-09 10:21:24 +00008468QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008469 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008470
8471 // Turn <4 x signed int> -> <4 x unsigned int>
8472 if (const VectorType *VTy = T->getAs<VectorType>())
8473 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008474 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008475
8476 // For enums, we return the unsigned version of the base type.
8477 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008478 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008479
8480 const BuiltinType *BTy = T->getAs<BuiltinType>();
8481 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008482 switch (BTy->getKind()) {
8483 case BuiltinType::Char_S:
8484 case BuiltinType::SChar:
8485 return UnsignedCharTy;
8486 case BuiltinType::Short:
8487 return UnsignedShortTy;
8488 case BuiltinType::Int:
8489 return UnsignedIntTy;
8490 case BuiltinType::Long:
8491 return UnsignedLongTy;
8492 case BuiltinType::LongLong:
8493 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008494 case BuiltinType::Int128:
8495 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008496 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008497 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008498 }
8499}
8500
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008501ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008502
Richard Smith1fa5d642013-05-11 05:45:24 +00008503void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8504 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008505
8506//===----------------------------------------------------------------------===//
8507// Builtin Type Computation
8508//===----------------------------------------------------------------------===//
8509
8510/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008511/// pointer over the consumed characters. This returns the resultant type. If
8512/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8513/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8514/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008515///
8516/// RequiresICE is filled in on return to indicate whether the value is required
8517/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008518static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008519 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008520 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008521 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008522 // Modifiers.
8523 int HowLong = 0;
8524 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008525 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008526
Chris Lattnerdc226c22010-10-01 22:42:38 +00008527 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008528 bool Done = false;
8529 #ifndef NDEBUG
8530 bool IsSpecialLong = false;
8531 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008532 while (!Done) {
8533 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008534 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008535 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008536 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008537 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008538 case 'S':
8539 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8540 assert(!Signed && "Can't use 'S' modifier multiple times!");
8541 Signed = true;
8542 break;
8543 case 'U':
8544 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008545 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008546 Unsigned = true;
8547 break;
8548 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008549 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008550 assert(HowLong <= 2 && "Can't have LLLL modifier");
8551 ++HowLong;
8552 break;
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008553 case 'N': {
8554 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8555 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8556 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008557 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008558 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008559 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008560 if (Context.getTargetInfo().getLongWidth() == 32)
8561 ++HowLong;
8562 break;
8563 }
Kevin Qinad64f6d2014-02-24 02:45:03 +00008564 case 'W':
8565 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008566 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008567 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008568 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008569 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008570 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008571 switch (Context.getTargetInfo().getInt64Type()) {
8572 default:
8573 llvm_unreachable("Unexpected integer type");
8574 case TargetInfo::SignedLong:
8575 HowLong = 1;
8576 break;
8577 case TargetInfo::SignedLongLong:
8578 HowLong = 2;
8579 break;
8580 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008581 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008582 }
8583 }
8584
8585 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008586
Chris Lattnerecd79c62009-06-14 00:45:47 +00008587 // Read the base type.
8588 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008589 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008590 case 'v':
8591 assert(HowLong == 0 && !Signed && !Unsigned &&
8592 "Bad modifiers used with 'v'!");
8593 Type = Context.VoidTy;
8594 break;
Jack Carter24bef982013-08-15 15:16:57 +00008595 case 'h':
8596 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008597 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008598 Type = Context.HalfTy;
8599 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008600 case 'f':
8601 assert(HowLong == 0 && !Signed && !Unsigned &&
8602 "Bad modifiers used with 'f'!");
8603 Type = Context.FloatTy;
8604 break;
8605 case 'd':
8606 assert(HowLong < 2 && !Signed && !Unsigned &&
8607 "Bad modifiers used with 'd'!");
8608 if (HowLong)
8609 Type = Context.LongDoubleTy;
8610 else
8611 Type = Context.DoubleTy;
8612 break;
8613 case 's':
8614 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8615 if (Unsigned)
8616 Type = Context.UnsignedShortTy;
8617 else
8618 Type = Context.ShortTy;
8619 break;
8620 case 'i':
8621 if (HowLong == 3)
8622 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8623 else if (HowLong == 2)
8624 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8625 else if (HowLong == 1)
8626 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8627 else
8628 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8629 break;
8630 case 'c':
8631 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8632 if (Signed)
8633 Type = Context.SignedCharTy;
8634 else if (Unsigned)
8635 Type = Context.UnsignedCharTy;
8636 else
8637 Type = Context.CharTy;
8638 break;
8639 case 'b': // boolean
8640 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8641 Type = Context.BoolTy;
8642 break;
8643 case 'z': // size_t.
8644 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8645 Type = Context.getSizeType();
8646 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008647 case 'w': // wchar_t.
8648 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8649 Type = Context.getWideCharType();
8650 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008651 case 'F':
8652 Type = Context.getCFConstantStringType();
8653 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008654 case 'G':
8655 Type = Context.getObjCIdType();
8656 break;
8657 case 'H':
8658 Type = Context.getObjCSelType();
8659 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008660 case 'M':
8661 Type = Context.getObjCSuperType();
8662 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008663 case 'a':
8664 Type = Context.getBuiltinVaListType();
8665 assert(!Type.isNull() && "builtin va list type not initialized!");
8666 break;
8667 case 'A':
8668 // This is a "reference" to a va_list; however, what exactly
8669 // this means depends on how va_list is defined. There are two
8670 // different kinds of va_list: ones passed by value, and ones
8671 // passed by reference. An example of a by-value va_list is
8672 // x86, where va_list is a char*. An example of by-ref va_list
8673 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8674 // we want this argument to be a char*&; for x86-64, we want
8675 // it to be a __va_list_tag*.
8676 Type = Context.getBuiltinVaListType();
8677 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008678 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008679 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008680 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008681 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008682 break;
8683 case 'V': {
8684 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008685 unsigned NumElements = strtoul(Str, &End, 10);
8686 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008687 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008688
Chandler Carruth45bbe012017-03-24 09:11:57 +00008689 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8690 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008691 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008692
8693 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008694 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008695 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008696 break;
8697 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008698 case 'E': {
8699 char *End;
8700
8701 unsigned NumElements = strtoul(Str, &End, 10);
8702 assert(End != Str && "Missing vector size");
8703
8704 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008705
Douglas Gregorfed66992012-06-07 18:08:25 +00008706 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008707 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00008708 Type = Context.getExtVectorType(ElementType, NumElements);
8709 break;
8710 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008711 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008712 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008713 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008714 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008715 Type = Context.getComplexType(ElementType);
8716 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008717 }
8718 case 'Y' : {
8719 Type = Context.getPointerDiffType();
8720 break;
8721 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008722 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008723 Type = Context.getFILEType();
8724 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008725 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008726 return QualType();
8727 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008728 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008729 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008730 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008731 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008732 else
8733 Type = Context.getjmp_bufType();
8734
Mike Stump2adb4da2009-07-28 23:47:15 +00008735 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008736 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008737 return QualType();
8738 }
8739 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008740 case 'K':
8741 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8742 Type = Context.getucontext_tType();
8743
8744 if (Type.isNull()) {
8745 Error = ASTContext::GE_Missing_ucontext;
8746 return QualType();
8747 }
8748 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008749 case 'p':
8750 Type = Context.getProcessIDType();
8751 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008752 }
Mike Stump11289f42009-09-09 15:08:12 +00008753
Chris Lattnerdc226c22010-10-01 22:42:38 +00008754 // If there are modifiers and if we're allowed to parse them, go for it.
8755 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008756 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008757 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008758 default: Done = true; --Str; break;
8759 case '*':
8760 case '&': {
8761 // Both pointers and references can have their pointee types
8762 // qualified with an address space.
8763 char *End;
8764 unsigned AddrSpace = strtoul(Str, &End, 10);
8765 if (End != Str && AddrSpace != 0) {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00008766 Type = Context.getAddrSpaceQualType(
8767 Type, AddrSpace + LangAS::FirstTargetAddressSpace);
Chris Lattnerdc226c22010-10-01 22:42:38 +00008768 Str = End;
8769 }
8770 if (c == '*')
8771 Type = Context.getPointerType(Type);
8772 else
8773 Type = Context.getLValueReferenceType(Type);
8774 break;
8775 }
8776 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8777 case 'C':
8778 Type = Type.withConst();
8779 break;
8780 case 'D':
8781 Type = Context.getVolatileType(Type);
8782 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008783 case 'R':
8784 Type = Type.withRestrict();
8785 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008786 }
8787 }
Chris Lattner84733392010-10-01 07:13:18 +00008788
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008789 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008790 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008791
Chris Lattnerecd79c62009-06-14 00:45:47 +00008792 return Type;
8793}
8794
8795/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00008796QualType ASTContext::GetBuiltinType(unsigned Id,
8797 GetBuiltinTypeError &Error,
8798 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008799 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008800
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008801 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008802
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008803 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008804 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008805 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8806 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008807 if (Error != GE_None)
8808 return QualType();
Chandler Carruth45bbe012017-03-24 09:11:57 +00008809
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008810 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00008811
Chris Lattnerecd79c62009-06-14 00:45:47 +00008812 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00008813 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008814 if (Error != GE_None)
8815 return QualType();
8816
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008817 // If this argument is required to be an IntegerConstantExpression and the
8818 // caller cares, fill in the bitmask we return.
8819 if (RequiresICE && IntegerConstantArgs)
8820 *IntegerConstantArgs |= 1 << ArgTypes.size();
8821
Chris Lattnerecd79c62009-06-14 00:45:47 +00008822 // Do array -> pointer decay. The builtin should use the decayed type.
8823 if (Ty->isArrayType())
8824 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008825
Chris Lattnerecd79c62009-06-14 00:45:47 +00008826 ArgTypes.push_back(Ty);
8827 }
8828
David Majnemerba3e5ec2015-03-13 18:26:17 +00008829 if (Id == Builtin::BI__GetExceptionInfo)
8830 return QualType();
8831
Chris Lattnerecd79c62009-06-14 00:45:47 +00008832 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8833 "'.' should only occur at end of builtin type list!");
8834
Reid Kleckner78af0702013-08-27 23:08:25 +00008835 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008836 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8837
8838 bool Variadic = (TypeStr[0] == '.');
8839
Richard Smith836de6b2016-12-19 23:59:34 +00008840 // We really shouldn't be making a no-proto type here.
8841 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008842 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008843
John McCalldb40c7f2010-12-14 08:05:40 +00008844 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008845 EPI.ExtInfo = EI;
8846 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008847 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8848 EPI.ExceptionSpec.Type =
8849 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008850
Jordan Rose5c382722013-03-08 21:51:21 +00008851 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008852}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008853
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008854static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8855 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008856 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008857 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008858
Yaron Keren4cd211b2017-02-22 14:32:39 +00008859 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008860 switch (FD->getTemplateSpecializationKind()) {
8861 case TSK_Undeclared:
8862 case TSK_ExplicitSpecialization:
8863 External = GVA_StrongExternal;
8864 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008865
Rafael Espindola3ae00052013-05-13 00:12:11 +00008866 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008867 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008868
David Majnemerc3d07332014-05-15 06:25:57 +00008869 // C++11 [temp.explicit]p10:
8870 // [ Note: The intent is that an inline function that is the subject of
8871 // an explicit instantiation declaration will still be implicitly
8872 // instantiated when used so that the body can be considered for
8873 // inlining, but that no out-of-line copy of the inline function would be
8874 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008875 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008876 return GVA_AvailableExternally;
8877
Rafael Espindola3ae00052013-05-13 00:12:11 +00008878 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008879 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008880 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008881 }
8882
8883 if (!FD->isInlined())
8884 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008885
David Majnemer3f021502015-10-08 04:53:31 +00008886 if ((!Context.getLangOpts().CPlusPlus &&
8887 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008888 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008889 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008890 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8891
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008892 // GNU or C99 inline semantics. Determine whether this symbol should be
8893 // externally visible.
8894 if (FD->isInlineDefinitionExternallyVisible())
8895 return External;
8896
8897 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008898 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008899 }
8900
David Majnemer54e3ba52014-04-02 23:17:29 +00008901 // Functions specified with extern and inline in -fms-compatibility mode
8902 // forcibly get emitted. While the body of the function cannot be later
8903 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008904 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008905 return GVA_StrongODR;
8906
David Majnemer27d69db2014-04-28 22:17:59 +00008907 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008908}
8909
Artem Belevichca2b9512016-05-02 20:30:03 +00008910static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00008911 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008912 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8913 // dllexport/dllimport on inline functions.
8914 if (D->hasAttr<DLLImportAttr>()) {
8915 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8916 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008917 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008918 if (L == GVA_DiscardableODR)
8919 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008920 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8921 D->hasAttr<CUDAGlobalAttr>()) {
8922 // Device-side functions with __global__ attribute must always be
8923 // visible externally so they can be launched from host.
8924 if (L == GVA_DiscardableODR || L == GVA_Internal)
8925 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008926 }
8927 return L;
8928}
8929
Richard Smitha4653622017-09-06 20:01:14 +00008930/// Adjust the GVALinkage for a declaration based on what an external AST source
8931/// knows about whether there can be other definitions of this declaration.
8932static GVALinkage
8933adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
8934 GVALinkage L) {
8935 ExternalASTSource *Source = Ctx.getExternalSource();
8936 if (!Source)
8937 return L;
8938
8939 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00008940 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00008941 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00008942 if (L == GVA_DiscardableODR)
8943 return GVA_StrongODR;
8944 break;
Richard Smitha4653622017-09-06 20:01:14 +00008945
David Blaikie9ffe5a32017-01-30 05:00:26 +00008946 case ExternalASTSource::EK_Always:
8947 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00008948
David Blaikie9ffe5a32017-01-30 05:00:26 +00008949 case ExternalASTSource::EK_ReplyHazy:
8950 break;
8951 }
8952 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008953}
8954
Richard Smitha4653622017-09-06 20:01:14 +00008955GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8956 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
8957 adjustGVALinkageForAttributes(*this, FD,
8958 basicGVALinkageForFunction(*this, FD)));
8959}
8960
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008961static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8962 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008963 if (!VD->isExternallyVisible())
8964 return GVA_Internal;
8965
David Majnemer27d69db2014-04-28 22:17:59 +00008966 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00008967 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8968 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8969 LexicalContext = LexicalContext->getLexicalParent();
8970
David Blaikieeb210012017-01-27 23:11:10 +00008971 // ObjC Blocks can create local variables that don't have a FunctionDecl
8972 // LexicalContext.
8973 if (!LexicalContext)
8974 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00008975
David Blaikieeb210012017-01-27 23:11:10 +00008976 // Otherwise, let the static local variable inherit its linkage from the
8977 // nearest enclosing function.
8978 auto StaticLocalLinkage =
8979 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8980
8981 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8982 // be emitted in any object with references to the symbol for the object it
8983 // contains, whether inline or out-of-line."
8984 // Similar behavior is observed with MSVC. An alternative ABI could use
8985 // StrongODR/AvailableExternally to match the function, but none are
8986 // known/supported currently.
8987 if (StaticLocalLinkage == GVA_StrongODR ||
8988 StaticLocalLinkage == GVA_AvailableExternally)
8989 return GVA_DiscardableODR;
8990 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00008991 }
8992
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008993 // MSVC treats in-class initialized static data members as definitions.
8994 // By giving them non-strong linkage, out-of-line definitions won't
8995 // cause link errors.
8996 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8997 return GVA_DiscardableODR;
8998
Richard Smithd9b90092016-07-02 01:32:16 +00008999 // Most non-template variables have strong linkage; inline variables are
9000 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9001 GVALinkage StrongLinkage;
9002 switch (Context.getInlineVariableDefinitionKind(VD)) {
9003 case ASTContext::InlineVariableDefinitionKind::None:
9004 StrongLinkage = GVA_StrongExternal;
9005 break;
9006 case ASTContext::InlineVariableDefinitionKind::Weak:
9007 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009008 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009009 break;
9010 case ASTContext::InlineVariableDefinitionKind::Strong:
9011 StrongLinkage = GVA_StrongODR;
9012 break;
9013 }
Richard Smith62f19e72016-06-25 00:15:56 +00009014
Richard Smith8809a0c2013-09-27 20:14:12 +00009015 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009016 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009017 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009018
David Majnemer6d1780c2015-07-17 23:36:49 +00009019 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009020 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9021 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009022 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009023 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009024
Rafael Espindola3ae00052013-05-13 00:12:11 +00009025 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009026 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009027
David Majnemer27d69db2014-04-28 22:17:59 +00009028 case TSK_ExplicitInstantiationDeclaration:
9029 return GVA_AvailableExternally;
9030
Rafael Espindola3ae00052013-05-13 00:12:11 +00009031 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009032 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009033 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009034
9035 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009036}
9037
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009038GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009039 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9040 adjustGVALinkageForAttributes(*this, VD,
9041 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009042}
9043
David Blaikiee6b7c282017-04-11 20:46:34 +00009044bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009045 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9046 if (!VD->isFileVarDecl())
9047 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009048 // Global named register variables (GNU extension) are never emitted.
9049 if (VD->getStorageClass() == SC_Register)
9050 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009051 if (VD->getDescribedVarTemplate() ||
9052 isa<VarTemplatePartialSpecializationDecl>(VD))
9053 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009054 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9055 // We never need to emit an uninstantiated function template.
9056 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9057 return false;
Nico Weber66220292016-03-02 17:28:48 +00009058 } else if (isa<PragmaCommentDecl>(D))
9059 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009060 else if (isa<OMPThreadPrivateDecl>(D) ||
9061 D->hasAttr<OMPDeclareTargetDeclAttr>())
9062 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009063 else if (isa<PragmaDetectMismatchDecl>(D))
9064 return true;
Nico Weber66220292016-03-02 17:28:48 +00009065 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009066 return !D->getDeclContext()->isDependentContext();
9067 else if (isa<OMPDeclareReductionDecl>(D))
9068 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009069 else if (isa<ImportDecl>(D))
9070 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009071 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009072 return false;
9073
9074 // If this is a member of a class template, we do not need to emit it.
9075 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009076 return false;
9077
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009078 // Weak references don't produce any output by themselves.
9079 if (D->hasAttr<WeakRefAttr>())
9080 return false;
9081
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009082 // Aliases and used decls are required.
9083 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9084 return true;
9085
9086 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9087 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009088 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009089 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009090
9091 // Constructors and destructors are required.
9092 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9093 return true;
9094
John McCall6bd2a892013-01-25 22:31:03 +00009095 // The key function for a class is required. This rule only comes
9096 // into play when inline functions can be key functions, though.
9097 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9098 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9099 const CXXRecordDecl *RD = MD->getParent();
9100 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9101 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9102 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9103 return true;
9104 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009105 }
9106 }
9107
David Blaikie9ffe5a32017-01-30 05:00:26 +00009108 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9109
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009110 // static, static inline, always_inline, and extern inline functions can
9111 // always be deferred. Normal inline functions can be deferred in C99/C++.
9112 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009113 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009114 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009115
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009116 const VarDecl *VD = cast<VarDecl>(D);
9117 assert(VD->isFileVarDecl() && "Expected file scoped var");
9118
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009119 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9120 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009121 return false;
9122
Richard Smitha0e5e542012-11-12 21:38:00 +00009123 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009124 auto Linkage = GetGVALinkageForVariable(VD);
9125 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009126 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009127
Richard Smitha4653622017-09-06 20:01:14 +00009128 // We never need to emit a variable that is available in another TU.
9129 if (Linkage == GVA_AvailableExternally)
9130 return false;
9131
Richard Smitha0e5e542012-11-12 21:38:00 +00009132 // Variables that have destruction with side-effects are required.
9133 if (VD->getType().isDestructedType())
9134 return true;
9135
9136 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009137 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009138 // We can get a value-dependent initializer during error recovery.
9139 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009140 return true;
9141
Richard Smithda383632016-08-15 01:33:41 +00009142 // Likewise, variables with tuple-like bindings are required if their
9143 // bindings have side-effects.
9144 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9145 for (auto *BD : DD->bindings())
9146 if (auto *BindingVD = BD->getHoldingVar())
9147 if (DeclMustBeEmitted(BindingVD))
9148 return true;
9149
Richard Smitha0e5e542012-11-12 21:38:00 +00009150 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009151}
Charles Davis53c59df2010-08-16 03:33:14 +00009152
Reid Kleckner78af0702013-08-27 23:08:25 +00009153CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9154 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009155 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009156 if (IsCXXMethod)
9157 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009158
Alexey Bataeva7547182016-05-18 09:06:38 +00009159 switch (LangOpts.getDefaultCallingConv()) {
9160 case LangOptions::DCC_None:
9161 break;
9162 case LangOptions::DCC_CDecl:
9163 return CC_C;
9164 case LangOptions::DCC_FastCall:
9165 if (getTargetInfo().hasFeature("sse2"))
9166 return CC_X86FastCall;
9167 break;
9168 case LangOptions::DCC_StdCall:
9169 if (!IsVariadic)
9170 return CC_X86StdCall;
9171 break;
9172 case LangOptions::DCC_VectorCall:
9173 // __vectorcall cannot be applied to variadic functions.
9174 if (!IsVariadic)
9175 return CC_X86VectorCall;
9176 break;
9177 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009178 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009179}
9180
Jay Foad39c79802011-01-12 09:06:06 +00009181bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009182 // Pass through to the C++ ABI object
9183 return ABI->isNearlyEmpty(RD);
9184}
9185
Reid Kleckner96f8f932014-02-05 17:27:08 +00009186VTableContextBase *ASTContext::getVTableContext() {
9187 if (!VTContext.get()) {
9188 if (Target->getCXXABI().isMicrosoft())
9189 VTContext.reset(new MicrosoftVTableContext(*this));
9190 else
9191 VTContext.reset(new ItaniumVTableContext(*this));
9192 }
9193 return VTContext.get();
9194}
9195
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009196MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009197 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009198 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009199 case TargetCXXABI::GenericItanium:
9200 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009201 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009202 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009203 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009204 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009205 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009206 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009207 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009208 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009209 }
David Blaikie83d382b2011-09-23 05:06:16 +00009210 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009211}
9212
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009213CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009214
9215size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009216 return ASTRecordLayouts.getMemorySize() +
9217 llvm::capacity_in_bytes(ObjCLayouts) +
9218 llvm::capacity_in_bytes(KeyFunctions) +
9219 llvm::capacity_in_bytes(ObjCImpls) +
9220 llvm::capacity_in_bytes(BlockVarCopyInits) +
9221 llvm::capacity_in_bytes(DeclAttrs) +
9222 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9223 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9224 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9225 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9226 llvm::capacity_in_bytes(OverriddenMethods) +
9227 llvm::capacity_in_bytes(Types) +
9228 llvm::capacity_in_bytes(VariableArrayTypes) +
9229 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009230}
Ted Kremenek540017e2011-10-06 05:00:56 +00009231
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009232/// getIntTypeForBitwidth -
9233/// sets integer QualTy according to specified details:
9234/// bitwidth, signed/unsigned.
9235/// Returns empty type if there is no appropriate target types.
9236QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9237 unsigned Signed) const {
9238 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9239 CanQualType QualTy = getFromTargetType(Ty);
9240 if (!QualTy && DestWidth == 128)
9241 return Signed ? Int128Ty : UnsignedInt128Ty;
9242 return QualTy;
9243}
9244
9245/// getRealTypeForBitwidth -
9246/// sets floating point QualTy according to specified bitwidth.
9247/// Returns empty type if there is no appropriate target types.
9248QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9249 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9250 switch (Ty) {
9251 case TargetInfo::Float:
9252 return FloatTy;
9253 case TargetInfo::Double:
9254 return DoubleTy;
9255 case TargetInfo::LongDouble:
9256 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009257 case TargetInfo::Float128:
9258 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009259 case TargetInfo::NoFloat:
9260 return QualType();
9261 }
9262
9263 llvm_unreachable("Unhandled TargetInfo::RealType value");
9264}
9265
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009266void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9267 if (Number > 1)
9268 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009269}
9270
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009271unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009272 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009273 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009274}
9275
David Majnemer2206bf52014-03-05 08:57:59 +00009276void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9277 if (Number > 1)
9278 StaticLocalNumbers[VD] = Number;
9279}
9280
9281unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009282 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009283 return I != StaticLocalNumbers.end() ? I->second : 1;
9284}
9285
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009286MangleNumberingContext &
9287ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009288 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009289 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009290 if (!MCtx)
9291 MCtx = createMangleNumberingContext();
9292 return *MCtx;
9293}
9294
Justin Lebar20ebffc2016-10-10 16:26:19 +00009295std::unique_ptr<MangleNumberingContext>
9296ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009297 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009298}
9299
David Majnemere7a818f2015-03-06 18:53:55 +00009300const CXXConstructorDecl *
9301ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9302 return ABI->getCopyConstructorForExceptionObject(
9303 cast<CXXRecordDecl>(RD->getFirstDecl()));
9304}
9305
9306void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9307 CXXConstructorDecl *CD) {
9308 return ABI->addCopyConstructorForExceptionObject(
9309 cast<CXXRecordDecl>(RD->getFirstDecl()),
9310 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9311}
9312
David Majnemer00350522015-08-31 18:48:39 +00009313void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9314 TypedefNameDecl *DD) {
9315 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9316}
9317
9318TypedefNameDecl *
9319ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9320 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9321}
9322
9323void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9324 DeclaratorDecl *DD) {
9325 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9326}
9327
9328DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9329 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9330}
9331
Ted Kremenek540017e2011-10-06 05:00:56 +00009332void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9333 ParamIndices[D] = index;
9334}
9335
9336unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9337 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9338 assert(I != ParamIndices.end() &&
9339 "ParmIndices lacks entry set by ParmVarDecl");
9340 return I->second;
9341}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009342
Richard Smithe6c01442013-06-05 00:46:14 +00009343APValue *
9344ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9345 bool MayCreate) {
9346 assert(E && E->getStorageDuration() == SD_Static &&
9347 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009348 if (MayCreate) {
9349 APValue *&MTVI = MaterializedTemporaryValues[E];
9350 if (!MTVI)
9351 MTVI = new (*this) APValue;
9352 return MTVI;
9353 }
Richard Smithe6c01442013-06-05 00:46:14 +00009354
David Majnemer2dcef9e2015-08-13 23:50:15 +00009355 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009356}
9357
Fariborz Jahanian615de762013-05-28 17:37:39 +00009358bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9359 const llvm::Triple &T = getTargetInfo().getTriple();
9360 if (!T.isOSDarwin())
9361 return false;
9362
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009363 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9364 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9365 return false;
9366
Fariborz Jahanian615de762013-05-28 17:37:39 +00009367 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9368 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9369 uint64_t Size = sizeChars.getQuantity();
9370 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9371 unsigned Align = alignChars.getQuantity();
9372 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9373 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9374}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009375
9376namespace {
9377
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009378ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9379 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009380 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009381 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009382 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009383 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009384 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009385}
9386
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009387/// Template specializations to abstract away from pointers and TypeLocs.
9388/// @{
9389template <typename T>
9390ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9391 return ast_type_traits::DynTypedNode::create(*Node);
9392}
9393template <>
9394ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9395 return ast_type_traits::DynTypedNode::create(Node);
9396}
9397template <>
9398ast_type_traits::DynTypedNode
9399createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9400 return ast_type_traits::DynTypedNode::create(Node);
9401}
9402/// @}
9403
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009404 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9405 /// parents as defined by the \c RecursiveASTVisitor.
9406 ///
9407 /// Note that the relationship described here is purely in terms of AST
9408 /// traversal - there are other relationships (for example declaration context)
9409 /// in the AST that are better modeled by special matchers.
9410 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009411 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009412 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009413 public:
9414 /// \brief Builds and returns the translation unit's parent map.
9415 ///
9416 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009417 static std::pair<ASTContext::ParentMapPointers *,
9418 ASTContext::ParentMapOtherNodes *>
9419 buildMap(TranslationUnitDecl &TU) {
9420 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9421 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009422 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009423 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009424 }
9425
9426 private:
9427 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9428
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009429 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9430 ASTContext::ParentMapOtherNodes *OtherParents)
9431 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009432
9433 bool shouldVisitTemplateInstantiations() const {
9434 return true;
9435 }
9436 bool shouldVisitImplicitCode() const {
9437 return true;
9438 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009439
Richard Smith85838722015-11-24 03:09:01 +00009440 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9441 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009442 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009443 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009444 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009445 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009446 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009447 // FIXME: Currently we add the same parent multiple times, but only
9448 // when no memoization data is available for the type.
9449 // For example when we visit all subexpressions of template
9450 // instantiations; this is suboptimal, but benign: the only way to
9451 // visit those is with hasAncestor / hasParent, and those do not create
9452 // new matches.
9453 // The plan is to enable DynTypedNode to be storable in a map or hash
9454 // map. The main problem there is to implement hash functions /
9455 // comparison operators for all types that DynTypedNode supports that
9456 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009457 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009458 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009459 if (const auto *D = ParentStack.back().get<Decl>())
9460 NodeOrVector = D;
9461 else if (const auto *S = ParentStack.back().get<Stmt>())
9462 NodeOrVector = S;
9463 else
9464 NodeOrVector =
9465 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009466 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009467 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9468 auto *Vector = new ASTContext::ParentVector(
9469 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009470 delete NodeOrVector
9471 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009472 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009473 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009474
9475 auto *Vector =
9476 NodeOrVector.template get<ASTContext::ParentVector *>();
9477 // Skip duplicates for types that have memoization data.
9478 // We must check that the type has memoization data before calling
9479 // std::find() because DynTypedNode::operator== can't compare all
9480 // types.
9481 bool Found = ParentStack.back().getMemoizationData() &&
9482 std::find(Vector->begin(), Vector->end(),
9483 ParentStack.back()) != Vector->end();
9484 if (!Found)
9485 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009486 }
9487 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009488 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009489 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009490 ParentStack.pop_back();
9491 return Result;
9492 }
9493
9494 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009495 return TraverseNode(DeclNode, DeclNode,
9496 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009497 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009498 }
9499
9500 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009501 return TraverseNode(StmtNode, StmtNode,
9502 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009503 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009504 }
9505
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009506 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009507 return TraverseNode(
9508 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9509 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9510 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009511 }
9512
9513 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9514 return TraverseNode(
9515 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009516 [&] {
9517 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9518 },
9519 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009520 }
9521
9522 ASTContext::ParentMapPointers *Parents;
9523 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009524 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9525
9526 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9527 };
9528
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009529} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009530
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009531template <typename NodeTy, typename MapTy>
9532static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9533 const MapTy &Map) {
9534 auto I = Map.find(Node);
9535 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009536 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009537 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009538 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009539 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009540 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009541 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009542}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009543
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009544ASTContext::DynTypedNodeList
9545ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9546 if (!PointerParents) {
9547 // We always need to run over the whole translation unit, as
9548 // hasAncestor can escape any subtree.
9549 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9550 PointerParents.reset(Maps.first);
9551 OtherParents.reset(Maps.second);
9552 }
9553 if (Node.getNodeKind().hasPointerIdentity())
9554 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9555 return getDynNodeFromMap(Node, *OtherParents);
9556}
9557
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009558bool
9559ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9560 const ObjCMethodDecl *MethodImpl) {
9561 // No point trying to match an unavailable/deprecated mothod.
9562 if (MethodDecl->hasAttr<UnavailableAttr>()
9563 || MethodDecl->hasAttr<DeprecatedAttr>())
9564 return false;
9565 if (MethodDecl->getObjCDeclQualifier() !=
9566 MethodImpl->getObjCDeclQualifier())
9567 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009568 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009569 return false;
9570
9571 if (MethodDecl->param_size() != MethodImpl->param_size())
9572 return false;
9573
9574 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9575 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9576 EF = MethodDecl->param_end();
9577 IM != EM && IF != EF; ++IM, ++IF) {
9578 const ParmVarDecl *DeclVar = (*IF);
9579 const ParmVarDecl *ImplVar = (*IM);
9580 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9581 return false;
9582 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9583 return false;
9584 }
9585 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9586
9587}
Richard Smith053f6c62014-05-16 23:01:30 +00009588
Yaxun Liu402804b2016-12-15 08:09:08 +00009589uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9590 unsigned AS;
9591 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9592 AS = 0;
9593 else
9594 AS = QT->getPointeeType().getAddressSpace();
9595
9596 return getTargetInfo().getNullPointerValue(AS);
9597}
9598
Yaxun Liub34ec822017-04-11 17:24:23 +00009599unsigned ASTContext::getTargetAddressSpace(unsigned AS) const {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00009600 if (AS >= LangAS::FirstTargetAddressSpace)
9601 return AS - LangAS::FirstTargetAddressSpace;
Yaxun Liub34ec822017-04-11 17:24:23 +00009602 else
9603 return (*AddrSpaceMap)[AS];
9604}
9605
Richard Smith053f6c62014-05-16 23:01:30 +00009606// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9607// doesn't include ASTContext.h
9608template
9609clang::LazyGenerationalUpdatePtr<
9610 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9611clang::LazyGenerationalUpdatePtr<
9612 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9613 const clang::ASTContext &Ctx, Decl *Value);