blob: 62b19685c677ff7bdc837a678f7f940acb4319f9 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000635 ExpandedTypes,
636 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000656 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000657
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000661 TTP->getPosition(),
662 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000663 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000666 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000667 SourceLocation(),
668 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000672 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
Charles Davis53c59df2010-08-16 03:33:14 +0000681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000682 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000687 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000688 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000689 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000690 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000693 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000694 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000695 return CreateMicrosoftCXXABI(*this);
696 }
David Blaikie8a40f702012-01-17 06:56:22 +0000697 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000698}
699
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
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 Smith42413142015-05-15 20:05:43 +0000897 ND->setHidden(false);
898}
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
1185 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001186
1187 // nullptr type (C++0x 2.14.7)
1188 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001189
1190 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1191 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001192
1193 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001194 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001195}
1196
David Blaikie9c902b52011-09-25 23:23:43 +00001197DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001198 return SourceMgr.getDiagnostics();
1199}
1200
Douglas Gregor561eceb2010-08-30 16:49:28 +00001201AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1202 AttrVec *&Result = DeclAttrs[D];
1203 if (!Result) {
1204 void *Mem = Allocate(sizeof(AttrVec));
1205 Result = new (Mem) AttrVec;
1206 }
1207
1208 return *Result;
1209}
1210
1211/// \brief Erase the attributes corresponding to the given declaration.
1212void ASTContext::eraseDeclAttrs(const Decl *D) {
1213 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1214 if (Pos != DeclAttrs.end()) {
1215 Pos->second->~AttrVec();
1216 DeclAttrs.erase(Pos);
1217 }
1218}
1219
Larisse Voufo39a1e502013-08-06 01:03:05 +00001220// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001221MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001222ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001223 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001224 return getTemplateOrSpecializationInfo(Var)
1225 .dyn_cast<MemberSpecializationInfo *>();
1226}
1227
1228ASTContext::TemplateOrSpecializationInfo
1229ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1230 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1231 TemplateOrInstantiation.find(Var);
1232 if (Pos == TemplateOrInstantiation.end())
1233 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001235 return Pos->second;
1236}
1237
Mike Stump11289f42009-09-09 15:08:12 +00001238void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001239ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001240 TemplateSpecializationKind TSK,
1241 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001242 assert(Inst->isStaticDataMember() && "Not a static data member");
1243 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001244 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1245 Tmpl, TSK, PointOfInstantiation));
1246}
1247
1248void
1249ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1250 TemplateOrSpecializationInfo TSI) {
1251 assert(!TemplateOrInstantiation[Inst] &&
1252 "Already noted what the variable was instantiated from");
1253 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001254}
1255
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001256FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1257 const FunctionDecl *FD){
1258 assert(FD && "Specialization is 0");
1259 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001260 = ClassScopeSpecializationPattern.find(FD);
1261 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001262 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001263
1264 return Pos->second;
1265}
1266
1267void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1268 FunctionDecl *Pattern) {
1269 assert(FD && "Specialization is 0");
1270 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001271 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001272}
1273
John McCalle61f2ba2009-11-18 02:36:19 +00001274NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001275ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1276 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001277 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001278 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001279
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001280 return Pos->second;
1281}
1282
1283void
Richard Smithd8a9e372016-12-18 21:39:37 +00001284ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001285 assert((isa<UsingDecl>(Pattern) ||
1286 isa<UnresolvedUsingValueDecl>(Pattern) ||
1287 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1288 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001289 assert((isa<UsingDecl>(Inst) ||
1290 isa<UnresolvedUsingValueDecl>(Inst) ||
1291 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1292 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001293 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1294 InstantiatedFromUsingDecl[Inst] = Pattern;
1295}
1296
1297UsingShadowDecl *
1298ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1299 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1300 = InstantiatedFromUsingShadowDecl.find(Inst);
1301 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001302 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001303
1304 return Pos->second;
1305}
1306
1307void
1308ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1309 UsingShadowDecl *Pattern) {
1310 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1311 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001312}
1313
Anders Carlsson5da84842009-09-01 04:26:58 +00001314FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1315 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1316 = InstantiatedFromUnnamedFieldDecl.find(Field);
1317 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001318 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001319
Anders Carlsson5da84842009-09-01 04:26:58 +00001320 return Pos->second;
1321}
1322
1323void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1324 FieldDecl *Tmpl) {
1325 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1326 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1327 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1328 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001329
Anders Carlsson5da84842009-09-01 04:26:58 +00001330 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1331}
1332
Douglas Gregor832940b2010-03-02 23:58:15 +00001333ASTContext::overridden_cxx_method_iterator
1334ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001335 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1336 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001337 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001338 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001339 return Pos->second.begin();
1340}
1341
1342ASTContext::overridden_cxx_method_iterator
1343ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001344 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1345 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001346 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001347 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001348 return Pos->second.end();
1349}
1350
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001351unsigned
1352ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001353 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1354 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001355 if (Pos == OverriddenMethods.end())
1356 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001357 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001358}
1359
Clement Courbet6ecaec82016-07-05 07:49:31 +00001360ASTContext::overridden_method_range
1361ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1362 return overridden_method_range(overridden_methods_begin(Method),
1363 overridden_methods_end(Method));
1364}
1365
Douglas Gregor832940b2010-03-02 23:58:15 +00001366void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1367 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001368 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001369 OverriddenMethods[Method].push_back(Overridden);
1370}
1371
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001372void ASTContext::getOverriddenMethods(
1373 const NamedDecl *D,
1374 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001375 assert(D);
1376
1377 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001378 Overridden.append(overridden_methods_begin(CXXMethod),
1379 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001380 return;
1381 }
1382
1383 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1384 if (!Method)
1385 return;
1386
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001387 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1388 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001389 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001390}
1391
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001392void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1393 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1394 assert(!Import->isFromASTFile() && "Non-local import declaration");
1395 if (!FirstLocalImport) {
1396 FirstLocalImport = Import;
1397 LastLocalImport = Import;
1398 return;
1399 }
1400
1401 LastLocalImport->NextLocalImport = Import;
1402 LastLocalImport = Import;
1403}
1404
Chris Lattner53cfe802007-07-18 17:52:12 +00001405//===----------------------------------------------------------------------===//
1406// Type Sizing and Analysis
1407//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001408
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001409/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1410/// scalar floating point type.
1411const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001412 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001413 assert(BT && "Not a floating point type!");
1414 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001415 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001416 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001417 case BuiltinType::Float: return Target->getFloatFormat();
1418 case BuiltinType::Double: return Target->getDoubleFormat();
1419 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001420 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001421 }
1422}
1423
Rafael Espindola71eccb32013-08-08 19:53:46 +00001424CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001425 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001426
John McCall94268702010-10-08 18:24:19 +00001427 bool UseAlignAttrOnly = false;
1428 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1429 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001430
John McCall94268702010-10-08 18:24:19 +00001431 // __attribute__((aligned)) can increase or decrease alignment
1432 // *except* on a struct or struct member, where it only increases
1433 // alignment unless 'packed' is also specified.
1434 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001435 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001436 // ignore that possibility; Sema should diagnose it.
1437 if (isa<FieldDecl>(D)) {
1438 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1439 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1440 } else {
1441 UseAlignAttrOnly = true;
1442 }
1443 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001444 else if (isa<FieldDecl>(D))
1445 UseAlignAttrOnly =
1446 D->hasAttr<PackedAttr>() ||
1447 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001448
John McCall4e819612011-01-20 07:57:12 +00001449 // If we're using the align attribute only, just ignore everything
1450 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001451 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001452 // do nothing
1453
John McCall94268702010-10-08 18:24:19 +00001454 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001455 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001456 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001457 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001458 T = RT->getPointeeType();
1459 else
1460 T = getPointerType(RT->getPointeeType());
1461 }
Richard Smithf6d70302014-06-10 23:34:28 +00001462 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001463 if (T->isFunctionType())
1464 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1465 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001466 // Adjust alignments of declarations with array type by the
1467 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001468 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001469 unsigned MinWidth = Target->getLargeArrayMinWidth();
1470 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001471 if (isa<VariableArrayType>(arrayType))
1472 Align = std::max(Align, Target->getLargeArrayAlign());
1473 else if (isa<ConstantArrayType>(arrayType) &&
1474 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1475 Align = std::max(Align, Target->getLargeArrayAlign());
1476 }
John McCall33ddac02011-01-19 10:06:00 +00001477 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001478 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001479 if (BaseT.getQualifiers().hasUnaligned())
1480 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001481 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001482 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001483 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1484 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001485 }
John McCall4e819612011-01-20 07:57:12 +00001486
1487 // Fields can be subject to extra alignment constraints, like if
1488 // the field is packed, the struct is packed, or the struct has a
1489 // a max-field-alignment constraint (#pragma pack). So calculate
1490 // the actual alignment of the field within the struct, and then
1491 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001492 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1493 const RecordDecl *Parent = Field->getParent();
1494 // We can only produce a sensible answer if the record is valid.
1495 if (!Parent->isInvalidDecl()) {
1496 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001497
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001498 // Start with the record's overall alignment.
1499 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001500
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001501 // Use the GCD of that and the offset within the record.
1502 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1503 if (Offset > 0) {
1504 // Alignment is always a power of 2, so the GCD will be a power of 2,
1505 // which means we get to do this crazy thing instead of Euclid's.
1506 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1507 if (LowBitOfOffset < FieldAlign)
1508 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1509 }
1510
1511 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001512 }
Charles Davis3fc51072010-02-23 04:52:00 +00001513 }
Chris Lattner68061312009-01-24 21:53:27 +00001514 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001515
Ken Dyckcc56c542011-01-15 18:38:59 +00001516 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001517}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001518
John McCallf1249922012-08-21 04:10:00 +00001519// getTypeInfoDataSizeInChars - Return the size of a type, in
1520// chars. If the type is a record, its data size is returned. This is
1521// the size of the memcpy that's performed when assigning this type
1522// using a trivial copy/move assignment operator.
1523std::pair<CharUnits, CharUnits>
1524ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1525 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1526
1527 // In C++, objects can sometimes be allocated into the tail padding
1528 // of a base-class subobject. We decide whether that's possible
1529 // during class layout, so here we can just trust the layout results.
1530 if (getLangOpts().CPlusPlus) {
1531 if (const RecordType *RT = T->getAs<RecordType>()) {
1532 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1533 sizeAndAlign.first = layout.getDataSize();
1534 }
1535 }
1536
1537 return sizeAndAlign;
1538}
1539
Richard Trieu04d2d942013-05-14 21:59:17 +00001540/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1541/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1542std::pair<CharUnits, CharUnits>
1543static getConstantArrayInfoInChars(const ASTContext &Context,
1544 const ConstantArrayType *CAT) {
1545 std::pair<CharUnits, CharUnits> EltInfo =
1546 Context.getTypeInfoInChars(CAT->getElementType());
1547 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001548 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1549 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001550 "Overflow in array type char size evaluation");
1551 uint64_t Width = EltInfo.first.getQuantity() * Size;
1552 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001553 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1554 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001555 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001556 return std::make_pair(CharUnits::fromQuantity(Width),
1557 CharUnits::fromQuantity(Align));
1558}
1559
John McCall87fe5d52010-05-20 01:18:31 +00001560std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001561ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001562 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1563 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001564 TypeInfo Info = getTypeInfo(T);
1565 return std::make_pair(toCharUnitsFromBits(Info.Width),
1566 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001567}
1568
1569std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001570ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001571 return getTypeInfoInChars(T.getTypePtr());
1572}
1573
David Majnemer34b57492014-07-30 01:30:47 +00001574bool ASTContext::isAlignmentRequired(const Type *T) const {
1575 return getTypeInfo(T).AlignIsRequired;
1576}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001577
David Majnemer34b57492014-07-30 01:30:47 +00001578bool ASTContext::isAlignmentRequired(QualType T) const {
1579 return isAlignmentRequired(T.getTypePtr());
1580}
1581
Richard Smithb2f0f052016-10-10 18:54:32 +00001582unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1583 // An alignment on a typedef overrides anything else.
1584 if (auto *TT = T->getAs<TypedefType>())
1585 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1586 return Align;
1587
1588 // If we have an (array of) complete type, we're done.
1589 T = getBaseElementType(T);
1590 if (!T->isIncompleteType())
1591 return getTypeAlign(T);
1592
1593 // If we had an array type, its element type might be a typedef
1594 // type with an alignment attribute.
1595 if (auto *TT = T->getAs<TypedefType>())
1596 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1597 return Align;
1598
1599 // Otherwise, see if the declaration of the type had an attribute.
1600 if (auto *TT = T->getAs<TagType>())
1601 return TT->getDecl()->getMaxAlignment();
1602
1603 return 0;
1604}
1605
David Majnemer34b57492014-07-30 01:30:47 +00001606TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001607 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1608 if (I != MemoizedTypeInfo.end())
1609 return I->second;
1610
1611 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1612 TypeInfo TI = getTypeInfoImpl(T);
1613 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001614 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001615}
1616
1617/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1618/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001619///
1620/// FIXME: Pointers into different addr spaces could have different sizes and
1621/// alignment requirements: getPointerInfo should take an AddrSpace, this
1622/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001623TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1624 uint64_t Width = 0;
1625 unsigned Align = 8;
1626 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001627 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001628#define TYPE(Class, Base)
1629#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001630#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001631#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001632#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1633 case Type::Class: \
1634 assert(!T->isDependentType() && "should not see dependent types here"); \
1635 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001636#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001637 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001638
Chris Lattner355332d2007-07-13 22:27:08 +00001639 case Type::FunctionNoProto:
1640 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001641 // GCC extension: alignof(function) = 32 bits
1642 Width = 0;
1643 Align = 32;
1644 break;
1645
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001646 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001647 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001648 Width = 0;
1649 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1650 break;
1651
Steve Naroff5c131802007-08-30 01:06:46 +00001652 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001653 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001654
David Majnemer34b57492014-07-30 01:30:47 +00001655 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001656 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001657 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001658 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001659 Width = EltInfo.Width * Size;
1660 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001661 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1662 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001663 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001664 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001665 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001666 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001667 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001668 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001669 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1670 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001671 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001672 // If the alignment is not a power of 2, round up to the next power of 2.
1673 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001674 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001675 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001676 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001677 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001678 // Adjust the alignment based on the target max.
1679 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1680 if (TargetVectorAlign && TargetVectorAlign < Align)
1681 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001682 break;
1683 }
Chris Lattner647fb222007-07-18 18:26:58 +00001684
Chris Lattner7570e9c2008-03-08 08:52:55 +00001685 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001686 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001687 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001688 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001689 // GCC extension: alignof(void) = 8 bits.
1690 Width = 0;
1691 Align = 8;
1692 break;
1693
Chris Lattner6a4f7452007-12-19 19:23:28 +00001694 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001695 Width = Target->getBoolWidth();
1696 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001697 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001698 case BuiltinType::Char_S:
1699 case BuiltinType::Char_U:
1700 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001701 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001702 Width = Target->getCharWidth();
1703 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001704 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001705 case BuiltinType::WChar_S:
1706 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Width = Target->getWCharWidth();
1708 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001709 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001710 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001711 Width = Target->getChar16Width();
1712 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001713 break;
1714 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001715 Width = Target->getChar32Width();
1716 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001717 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001718 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001719 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001720 Width = Target->getShortWidth();
1721 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001722 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001723 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001724 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001725 Width = Target->getIntWidth();
1726 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001727 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001728 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001729 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001730 Width = Target->getLongWidth();
1731 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001732 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001733 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001734 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001735 Width = Target->getLongLongWidth();
1736 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001737 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001738 case BuiltinType::Int128:
1739 case BuiltinType::UInt128:
1740 Width = 128;
1741 Align = 128; // int128_t is 128-bit aligned on all targets.
1742 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001743 case BuiltinType::Half:
1744 Width = Target->getHalfWidth();
1745 Align = Target->getHalfAlign();
1746 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001747 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001748 Width = Target->getFloatWidth();
1749 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001750 break;
1751 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001752 Width = Target->getDoubleWidth();
1753 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001754 break;
1755 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001756 Width = Target->getLongDoubleWidth();
1757 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001758 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001759 case BuiltinType::Float128:
1760 Width = Target->getFloat128Width();
1761 Align = Target->getFloat128Align();
1762 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001763 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001764 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1765 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001766 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001767 case BuiltinType::ObjCId:
1768 case BuiltinType::ObjCClass:
1769 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001770 Width = Target->getPointerWidth(0);
1771 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001772 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001773 case BuiltinType::OCLSampler: {
1774 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1775 Width = Target->getPointerWidth(AS);
1776 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001777 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001778 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001779 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001780 case BuiltinType::OCLClkEvent:
1781 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001782 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001783 // Currently these types are pointers to opaque types.
1784 Width = Target->getPointerWidth(0);
1785 Align = Target->getPointerAlign(0);
1786 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001787#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1788 case BuiltinType::Id:
1789#include "clang/Basic/OpenCLImageTypes.def"
1790 {
1791 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1792 Width = Target->getPointerWidth(AS);
1793 Align = Target->getPointerAlign(AS);
1794 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001795 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001796 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001797 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001798 Width = Target->getPointerWidth(0);
1799 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001800 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001801 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001802 unsigned AS = getTargetAddressSpace(
1803 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001804 Width = Target->getPointerWidth(AS);
1805 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001806 break;
1807 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001808 case Type::LValueReference:
1809 case Type::RValueReference: {
1810 // alignof and sizeof should never enter this code path here, so we go
1811 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001812 unsigned AS = getTargetAddressSpace(
1813 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001814 Width = Target->getPointerWidth(AS);
1815 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001816 break;
1817 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001818 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001819 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001820 Width = Target->getPointerWidth(AS);
1821 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001822 break;
1823 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001824 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001825 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001826 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001827 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001828 }
Chris Lattner647fb222007-07-18 18:26:58 +00001829 case Type::Complex: {
1830 // Complex types have the same alignment as their elements, but twice the
1831 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001832 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1833 Width = EltInfo.Width * 2;
1834 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001835 break;
1836 }
John McCall8b07ec22010-05-15 11:32:37 +00001837 case Type::ObjCObject:
1838 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001839 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001840 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001841 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001842 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001843 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001844 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001845 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001846 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001847 break;
1848 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001849 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001850 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001851 const TagType *TT = cast<TagType>(T);
1852
1853 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001854 Width = 8;
1855 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001856 break;
1857 }
Mike Stump11289f42009-09-09 15:08:12 +00001858
David Majnemer475b25e2015-01-21 10:54:38 +00001859 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1860 const EnumDecl *ED = ET->getDecl();
1861 TypeInfo Info =
1862 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1863 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1864 Info.Align = AttrAlign;
1865 Info.AlignIsRequired = true;
1866 }
1867 return Info;
1868 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001869
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001870 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001871 const RecordDecl *RD = RT->getDecl();
1872 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001873 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001874 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001875 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001876 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001877 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001878
Chris Lattner63d2b362009-10-22 05:17:15 +00001879 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001880 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1881 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001882
Richard Smith600b5262017-01-26 20:40:47 +00001883 case Type::Auto:
1884 case Type::DeducedTemplateSpecialization: {
1885 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001886 assert(!A->getDeducedType().isNull() &&
1887 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001888 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001889 }
1890
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001891 case Type::Paren:
1892 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1893
Manman Rene6be26c2016-09-13 17:25:08 +00001894 case Type::ObjCTypeParam:
1895 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1896
Douglas Gregoref462e62009-04-30 17:32:17 +00001897 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001898 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001899 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001900 // If the typedef has an aligned attribute on it, it overrides any computed
1901 // alignment we have. This violates the GCC documentation (which says that
1902 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001903 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001904 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001905 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001906 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001907 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001908 AlignIsRequired = Info.AlignIsRequired;
1909 }
David Majnemer34b57492014-07-30 01:30:47 +00001910 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001911 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001912 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001913
Abramo Bagnara6150c882010-05-11 21:36:43 +00001914 case Type::Elaborated:
1915 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001916
John McCall81904512011-01-06 01:58:22 +00001917 case Type::Attributed:
1918 return getTypeInfo(
1919 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1920
Eli Friedman0dfb8892011-10-06 23:00:33 +00001921 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001922 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001923 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1924 Width = Info.Width;
1925 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001926
1927 // If the size of the type doesn't exceed the platform's max
1928 // atomic promotion width, make the size and alignment more
1929 // favorable to atomic operations:
1930 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1931 // Round the size up to a power of 2.
1932 if (!llvm::isPowerOf2_64(Width))
1933 Width = llvm::NextPowerOf2(Width);
1934
1935 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001936 Align = static_cast<unsigned>(Width);
1937 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001938 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001939 break;
1940
1941 case Type::Pipe: {
Anastasia Stulovab3398932017-06-05 11:27:03 +00001942 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1943 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Xiuli Pan9c14e282016-01-09 12:53:17 +00001944 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001945
Douglas Gregoref462e62009-04-30 17:32:17 +00001946 }
Mike Stump11289f42009-09-09 15:08:12 +00001947
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001948 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001949 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001950}
1951
Alexey Bataev00396512015-07-02 03:40:19 +00001952unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1953 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1954 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1955 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1956 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1957 getTargetInfo().getABI() == "elfv1-qpx" &&
1958 T->isSpecificBuiltinType(BuiltinType::Double))
1959 SimdAlign = 256;
1960 return SimdAlign;
1961}
1962
Ken Dyckcc56c542011-01-15 18:38:59 +00001963/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1964CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1965 return CharUnits::fromQuantity(BitSize / getCharWidth());
1966}
1967
Ken Dyckb0fcc592011-02-11 01:54:29 +00001968/// toBits - Convert a size in characters to a size in characters.
1969int64_t ASTContext::toBits(CharUnits CharSize) const {
1970 return CharSize.getQuantity() * getCharWidth();
1971}
1972
Ken Dyck8c89d592009-12-22 14:23:30 +00001973/// getTypeSizeInChars - Return the size of the specified type, in characters.
1974/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001975CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001976 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001977}
Jay Foad39c79802011-01-12 09:06:06 +00001978CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001979 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001980}
1981
Ken Dycka6046ab2010-01-26 17:25:18 +00001982/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001983/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001984CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001985 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001986}
Jay Foad39c79802011-01-12 09:06:06 +00001987CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001988 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001989}
1990
Chris Lattnera3402cd2009-01-27 18:08:34 +00001991/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1992/// type for the current target in bits. This can be different than the ABI
1993/// alignment in cases where it is beneficial for performance to overalign
1994/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001995unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001996 TypeInfo TI = getTypeInfo(T);
1997 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001998
David Majnemere1544562015-04-24 01:25:05 +00001999 T = T->getBaseElementTypeUnsafe();
2000
2001 // The preferred alignment of member pointers is that of a pointer.
2002 if (T->isMemberPointerType())
2003 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2004
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002005 if (!Target->allowsLargerPreferedTypeAlignment())
2006 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002007
Eli Friedman7ab09572009-05-25 21:27:19 +00002008 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002009 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002010 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002011 if (const EnumType *ET = T->getAs<EnumType>())
2012 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002013 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002014 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2015 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002016 // Don't increase the alignment if an alignment attribute was specified on a
2017 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002018 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002019 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002020
Chris Lattnera3402cd2009-01-27 18:08:34 +00002021 return ABIAlign;
2022}
2023
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002024/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2025/// for __attribute__((aligned)) on this target, to be used if no alignment
2026/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002027unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002028 return getTargetInfo().getDefaultAlignForAttributeAligned();
2029}
2030
Ulrich Weigandfa806422013-05-06 16:23:57 +00002031/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2032/// to a global variable of the specified type.
2033unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2034 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2035}
2036
2037/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2038/// should be given to a global variable of the specified type.
2039CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2040 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2041}
2042
David Majnemer08ef2ba2015-06-23 20:34:18 +00002043CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2044 CharUnits Offset = CharUnits::Zero();
2045 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2046 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2047 Offset += Layout->getBaseClassOffset(Base);
2048 Layout = &getASTRecordLayout(Base);
2049 }
2050 return Offset;
2051}
2052
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002053/// DeepCollectObjCIvars -
2054/// This routine first collects all declared, but not synthesized, ivars in
2055/// super class and then collects all ivars, including those synthesized for
2056/// current class. This routine is used for implementation of current class
2057/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002058///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002059void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2060 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002061 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002062 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2063 DeepCollectObjCIvars(SuperClass, false, Ivars);
2064 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002065 for (const auto *I : OI->ivars())
2066 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002067 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002068 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002069 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002070 Iv= Iv->getNextIvar())
2071 Ivars.push_back(Iv);
2072 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002073}
2074
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002075/// CollectInheritedProtocols - Collect all protocols in current class and
2076/// those inherited by it.
2077void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002078 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002079 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002080 // We can use protocol_iterator here instead of
2081 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002082 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002083 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002084 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002085
2086 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002087 for (const auto *Cat : OI->visible_categories())
2088 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002089
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002090 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2091 while (SD) {
2092 CollectInheritedProtocols(SD, Protocols);
2093 SD = SD->getSuperClass();
2094 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002095 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002096 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002097 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002098 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002099 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002100 // Insert the protocol.
2101 if (!Protocols.insert(
2102 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2103 return;
2104
2105 for (auto *Proto : OP->protocols())
2106 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002107 }
2108}
2109
Jay Foad39c79802011-01-12 09:06:06 +00002110unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002111 unsigned count = 0;
2112 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002113 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002114 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002115
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002116 // Count ivar defined in this class's implementation. This
2117 // includes synthesized ivars.
2118 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002119 count += ImplDecl->ivar_size();
2120
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002121 return count;
2122}
2123
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002124bool ASTContext::isSentinelNullExpr(const Expr *E) {
2125 if (!E)
2126 return false;
2127
2128 // nullptr_t is always treated as null.
2129 if (E->getType()->isNullPtrType()) return true;
2130
2131 if (E->getType()->isAnyPointerType() &&
2132 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2133 Expr::NPC_ValueDependentIsNull))
2134 return true;
2135
2136 // Unfortunately, __null has type 'int'.
2137 if (isa<GNUNullExpr>(E)) return true;
2138
2139 return false;
2140}
2141
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002142/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2143ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2144 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2145 I = ObjCImpls.find(D);
2146 if (I != ObjCImpls.end())
2147 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002148 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002149}
2150/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2151ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2152 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2153 I = ObjCImpls.find(D);
2154 if (I != ObjCImpls.end())
2155 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002156 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002157}
2158
2159/// \brief Set the implementation of ObjCInterfaceDecl.
2160void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2161 ObjCImplementationDecl *ImplD) {
2162 assert(IFaceD && ImplD && "Passed null params");
2163 ObjCImpls[IFaceD] = ImplD;
2164}
2165/// \brief Set the implementation of ObjCCategoryDecl.
2166void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2167 ObjCCategoryImplDecl *ImplD) {
2168 assert(CatD && ImplD && "Passed null params");
2169 ObjCImpls[CatD] = ImplD;
2170}
2171
Chandler Carruth21c90602015-12-30 03:24:14 +00002172const ObjCMethodDecl *
2173ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2174 return ObjCMethodRedecls.lookup(MD);
2175}
2176
2177void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2178 const ObjCMethodDecl *Redecl) {
2179 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2180 ObjCMethodRedecls[MD] = Redecl;
2181}
2182
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002183const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2184 const NamedDecl *ND) const {
2185 if (const ObjCInterfaceDecl *ID =
2186 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002187 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002188 if (const ObjCCategoryDecl *CD =
2189 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002190 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002191 if (const ObjCImplDecl *IMD =
2192 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002193 return IMD->getClassInterface();
2194
Craig Topper36250ad2014-05-12 05:36:57 +00002195 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002196}
2197
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002198/// \brief Get the copy initialization expression of VarDecl,or NULL if
2199/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002200Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002201 assert(VD && "Passed null params");
2202 assert(VD->hasAttr<BlocksAttr>() &&
2203 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002204 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002205 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002206 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002207}
2208
2209/// \brief Set the copy inialization expression of a block var decl.
2210void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2211 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002212 assert(VD->hasAttr<BlocksAttr>() &&
2213 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002214 BlockVarCopyInits[VD] = Init;
2215}
2216
John McCallbcd03502009-12-07 02:54:59 +00002217TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002218 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002219 if (!DataSize)
2220 DataSize = TypeLoc::getFullDataSizeForType(T);
2221 else
2222 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002223 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002224
John McCallbcd03502009-12-07 02:54:59 +00002225 TypeSourceInfo *TInfo =
2226 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2227 new (TInfo) TypeSourceInfo(T);
2228 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002229}
2230
John McCallbcd03502009-12-07 02:54:59 +00002231TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002232 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002233 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002234 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002235 return DI;
2236}
2237
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002238const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002239ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002240 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002241}
2242
2243const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002244ASTContext::getASTObjCImplementationLayout(
2245 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002246 return getObjCLayout(D->getClassInterface(), D);
2247}
2248
Chris Lattner983a8bb2007-07-13 22:13:22 +00002249//===----------------------------------------------------------------------===//
2250// Type creation/memoization methods
2251//===----------------------------------------------------------------------===//
2252
Jay Foad39c79802011-01-12 09:06:06 +00002253QualType
John McCall33ddac02011-01-19 10:06:00 +00002254ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2255 unsigned fastQuals = quals.getFastQualifiers();
2256 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002257
2258 // Check if we've already instantiated this type.
2259 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002260 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002261 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002262 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2263 assert(eq->getQualifiers() == quals);
2264 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002265 }
2266
John McCall33ddac02011-01-19 10:06:00 +00002267 // If the base type is not canonical, make the appropriate canonical type.
2268 QualType canon;
2269 if (!baseType->isCanonicalUnqualified()) {
2270 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002271 canonSplit.Quals.addConsistentQualifiers(quals);
2272 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002273
2274 // Re-find the insert position.
2275 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2276 }
2277
2278 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2279 ExtQualNodes.InsertNode(eq, insertPos);
2280 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002281}
2282
Jay Foad39c79802011-01-12 09:06:06 +00002283QualType
2284ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002285 QualType CanT = getCanonicalType(T);
2286 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002287 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002288
John McCall8ccfcb52009-09-24 19:53:00 +00002289 // If we are composing extended qualifiers together, merge together
2290 // into one ExtQuals node.
2291 QualifierCollector Quals;
2292 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002293
John McCall8ccfcb52009-09-24 19:53:00 +00002294 // If this type already has an address space specified, it cannot get
2295 // another one.
2296 assert(!Quals.hasAddressSpace() &&
2297 "Type cannot be in multiple addr spaces!");
2298 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002299
John McCall8ccfcb52009-09-24 19:53:00 +00002300 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002301}
2302
Chris Lattnerd60183d2009-02-18 22:53:11 +00002303QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002304 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002305 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002306 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002307 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002308
John McCall53fa7142010-12-24 02:08:15 +00002309 if (const PointerType *ptr = T->getAs<PointerType>()) {
2310 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002311 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002312 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2313 return getPointerType(ResultType);
2314 }
2315 }
Mike Stump11289f42009-09-09 15:08:12 +00002316
John McCall8ccfcb52009-09-24 19:53:00 +00002317 // If we are composing extended qualifiers together, merge together
2318 // into one ExtQuals node.
2319 QualifierCollector Quals;
2320 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002321
John McCall8ccfcb52009-09-24 19:53:00 +00002322 // If this type already has an ObjCGC specified, it cannot get
2323 // another one.
2324 assert(!Quals.hasObjCGCAttr() &&
2325 "Type cannot have multiple ObjCGCs!");
2326 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002327
John McCall8ccfcb52009-09-24 19:53:00 +00002328 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002329}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002330
John McCall4f5019e2010-12-19 02:44:49 +00002331const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2332 FunctionType::ExtInfo Info) {
2333 if (T->getExtInfo() == Info)
2334 return T;
2335
2336 QualType Result;
2337 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002338 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002339 } else {
2340 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2341 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2342 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002343 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002344 }
2345
2346 return cast<FunctionType>(Result.getTypePtr());
2347}
2348
Richard Smith2a7d4812013-05-04 07:00:32 +00002349void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2350 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002351 FD = FD->getMostRecentDecl();
2352 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002353 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2354 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002355 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002356 if (FunctionDecl *Next = FD->getPreviousDecl())
2357 FD = Next;
2358 else
2359 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002360 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002361 if (ASTMutationListener *L = getASTMutationListener())
2362 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002363}
2364
Richard Smith0b3a4622014-11-13 20:01:57 +00002365/// Get a function type and produce the equivalent function type with the
2366/// specified exception specification. Type sugar that can be present on a
2367/// declaration of a function with an exception specification is permitted
2368/// and preserved. Other type sugar (for instance, typedefs) is not.
2369static QualType getFunctionTypeWithExceptionSpec(
2370 ASTContext &Context, QualType Orig,
2371 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2372 // Might have some parens.
2373 if (auto *PT = dyn_cast<ParenType>(Orig))
2374 return Context.getParenType(
2375 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2376
2377 // Might have a calling-convention attribute.
2378 if (auto *AT = dyn_cast<AttributedType>(Orig))
2379 return Context.getAttributedType(
2380 AT->getAttrKind(),
2381 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2382 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2383 ESI));
2384
2385 // Anything else must be a function type. Rebuild it with the new exception
2386 // specification.
2387 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2388 return Context.getFunctionType(
2389 Proto->getReturnType(), Proto->getParamTypes(),
2390 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2391}
2392
Richard Smithdfe85e22016-12-15 02:35:39 +00002393bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2394 QualType U) {
2395 return hasSameType(T, U) ||
2396 (getLangOpts().CPlusPlus1z &&
2397 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2398 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2399}
2400
Richard Smith0b3a4622014-11-13 20:01:57 +00002401void ASTContext::adjustExceptionSpec(
2402 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2403 bool AsWritten) {
2404 // Update the type.
2405 QualType Updated =
2406 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2407 FD->setType(Updated);
2408
2409 if (!AsWritten)
2410 return;
2411
2412 // Update the type in the type source information too.
2413 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2414 // If the type and the type-as-written differ, we may need to update
2415 // the type-as-written too.
2416 if (TSInfo->getType() != FD->getType())
2417 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2418
2419 // FIXME: When we get proper type location information for exceptions,
2420 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2421 // up the TypeSourceInfo;
2422 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2423 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2424 "TypeLoc size mismatch from updating exception specification");
2425 TSInfo->overrideType(Updated);
2426 }
2427}
2428
Chris Lattnerc6395932007-06-22 20:56:16 +00002429/// getComplexType - Return the uniqued reference to the type for a complex
2430/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002431QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002432 // Unique pointers, to guarantee there is only one pointer of a particular
2433 // structure.
2434 llvm::FoldingSetNodeID ID;
2435 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002436
Craig Topper36250ad2014-05-12 05:36:57 +00002437 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002438 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2439 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002440
Chris Lattnerc6395932007-06-22 20:56:16 +00002441 // If the pointee type isn't canonical, this won't be a canonical type either,
2442 // so fill in the canonical type field.
2443 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002444 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002445 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002446
Chris Lattnerc6395932007-06-22 20:56:16 +00002447 // Get the new insert position for the node we care about.
2448 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002449 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002450 }
John McCall90d1c2d2009-09-24 23:30:46 +00002451 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002452 Types.push_back(New);
2453 ComplexTypes.InsertNode(New, InsertPos);
2454 return QualType(New, 0);
2455}
2456
Chris Lattner970e54e2006-11-12 00:37:36 +00002457/// getPointerType - Return the uniqued reference to the type for a pointer to
2458/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002459QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002460 // Unique pointers, to guarantee there is only one pointer of a particular
2461 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002462 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002463 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Craig Topper36250ad2014-05-12 05:36:57 +00002465 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002466 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002467 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002468
Chris Lattner7ccecb92006-11-12 08:50:50 +00002469 // If the pointee type isn't canonical, this won't be a canonical type either,
2470 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002471 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002472 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002473 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002474
Bob Wilsonc8541f22013-03-15 17:12:43 +00002475 // Get the new insert position for the node we care about.
2476 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002477 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002478 }
John McCall90d1c2d2009-09-24 23:30:46 +00002479 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002480 Types.push_back(New);
2481 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002482 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002483}
2484
Reid Kleckner0503a872013-12-05 01:23:43 +00002485QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2486 llvm::FoldingSetNodeID ID;
2487 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002488 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002489 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2490 if (AT)
2491 return QualType(AT, 0);
2492
2493 QualType Canonical = getCanonicalType(New);
2494
2495 // Get the new insert position for the node we care about.
2496 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002497 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002498
2499 AT = new (*this, TypeAlignment)
2500 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2501 Types.push_back(AT);
2502 AdjustedTypes.InsertNode(AT, InsertPos);
2503 return QualType(AT, 0);
2504}
2505
Reid Kleckner8a365022013-06-24 17:51:48 +00002506QualType ASTContext::getDecayedType(QualType T) const {
2507 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2508
Reid Kleckner8a365022013-06-24 17:51:48 +00002509 QualType Decayed;
2510
2511 // C99 6.7.5.3p7:
2512 // A declaration of a parameter as "array of type" shall be
2513 // adjusted to "qualified pointer to type", where the type
2514 // qualifiers (if any) are those specified within the [ and ] of
2515 // the array type derivation.
2516 if (T->isArrayType())
2517 Decayed = getArrayDecayedType(T);
2518
2519 // C99 6.7.5.3p8:
2520 // A declaration of a parameter as "function returning type"
2521 // shall be adjusted to "pointer to function returning type", as
2522 // in 6.3.2.1.
2523 if (T->isFunctionType())
2524 Decayed = getPointerType(T);
2525
Reid Kleckner0503a872013-12-05 01:23:43 +00002526 llvm::FoldingSetNodeID ID;
2527 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002528 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002529 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2530 if (AT)
2531 return QualType(AT, 0);
2532
Reid Kleckner8a365022013-06-24 17:51:48 +00002533 QualType Canonical = getCanonicalType(Decayed);
2534
2535 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002536 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002537 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002538
Reid Kleckner0503a872013-12-05 01:23:43 +00002539 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2540 Types.push_back(AT);
2541 AdjustedTypes.InsertNode(AT, InsertPos);
2542 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002543}
2544
Mike Stump11289f42009-09-09 15:08:12 +00002545/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002546/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002547QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002548 assert(T->isFunctionType() && "block of function types only");
2549 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002550 // structure.
2551 llvm::FoldingSetNodeID ID;
2552 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Craig Topper36250ad2014-05-12 05:36:57 +00002554 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002555 if (BlockPointerType *PT =
2556 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2557 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002558
2559 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002560 // type either so fill in the canonical type field.
2561 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002562 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002563 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002564
Steve Naroffec33ed92008-08-27 16:04:49 +00002565 // Get the new insert position for the node we care about.
2566 BlockPointerType *NewIP =
2567 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002568 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002569 }
John McCall90d1c2d2009-09-24 23:30:46 +00002570 BlockPointerType *New
2571 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002572 Types.push_back(New);
2573 BlockPointerTypes.InsertNode(New, InsertPos);
2574 return QualType(New, 0);
2575}
2576
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002577/// getLValueReferenceType - Return the uniqued reference to the type for an
2578/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002579QualType
2580ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002581 assert(getCanonicalType(T) != OverloadTy &&
2582 "Unresolved overloaded function type");
2583
Bill Wendling3708c182007-05-27 10:15:43 +00002584 // Unique pointers, to guarantee there is only one pointer of a particular
2585 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002586 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002587 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002588
Craig Topper36250ad2014-05-12 05:36:57 +00002589 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002590 if (LValueReferenceType *RT =
2591 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002592 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002593
John McCallfc93cf92009-10-22 22:37:11 +00002594 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2595
Bill Wendling3708c182007-05-27 10:15:43 +00002596 // If the referencee type isn't canonical, this won't be a canonical type
2597 // either, so fill in the canonical type field.
2598 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002599 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2600 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2601 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002602
Bill Wendling3708c182007-05-27 10:15:43 +00002603 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002604 LValueReferenceType *NewIP =
2605 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002606 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002607 }
2608
John McCall90d1c2d2009-09-24 23:30:46 +00002609 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002610 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2611 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002612 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002613 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002614
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002615 return QualType(New, 0);
2616}
2617
2618/// getRValueReferenceType - Return the uniqued reference to the type for an
2619/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002620QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002621 // Unique pointers, to guarantee there is only one pointer of a particular
2622 // structure.
2623 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002624 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002625
Craig Topper36250ad2014-05-12 05:36:57 +00002626 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002627 if (RValueReferenceType *RT =
2628 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2629 return QualType(RT, 0);
2630
John McCallfc93cf92009-10-22 22:37:11 +00002631 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2632
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002633 // If the referencee type isn't canonical, this won't be a canonical type
2634 // either, so fill in the canonical type field.
2635 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002636 if (InnerRef || !T.isCanonical()) {
2637 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2638 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002639
2640 // Get the new insert position for the node we care about.
2641 RValueReferenceType *NewIP =
2642 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002643 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002644 }
2645
John McCall90d1c2d2009-09-24 23:30:46 +00002646 RValueReferenceType *New
2647 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002648 Types.push_back(New);
2649 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002650 return QualType(New, 0);
2651}
2652
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002653/// getMemberPointerType - Return the uniqued reference to the type for a
2654/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002655QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002656 // Unique pointers, to guarantee there is only one pointer of a particular
2657 // structure.
2658 llvm::FoldingSetNodeID ID;
2659 MemberPointerType::Profile(ID, T, Cls);
2660
Craig Topper36250ad2014-05-12 05:36:57 +00002661 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002662 if (MemberPointerType *PT =
2663 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2664 return QualType(PT, 0);
2665
2666 // If the pointee or class type isn't canonical, this won't be a canonical
2667 // type either, so fill in the canonical type field.
2668 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002669 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002670 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2671
2672 // Get the new insert position for the node we care about.
2673 MemberPointerType *NewIP =
2674 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002675 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002676 }
John McCall90d1c2d2009-09-24 23:30:46 +00002677 MemberPointerType *New
2678 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002679 Types.push_back(New);
2680 MemberPointerTypes.InsertNode(New, InsertPos);
2681 return QualType(New, 0);
2682}
2683
Mike Stump11289f42009-09-09 15:08:12 +00002684/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002685/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002686QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002687 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002688 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002689 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002690 assert((EltTy->isDependentType() ||
2691 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002692 "Constant array of VLAs is illegal!");
2693
Chris Lattnere2df3f92009-05-13 04:12:56 +00002694 // Convert the array size into a canonical width matching the pointer size for
2695 // the target.
2696 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002697 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002698
Chris Lattner23b7eb62007-06-15 23:05:46 +00002699 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002700 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002701
Craig Topper36250ad2014-05-12 05:36:57 +00002702 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002703 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002704 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002705 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002706
John McCall33ddac02011-01-19 10:06:00 +00002707 // If the element type isn't canonical or has qualifiers, this won't
2708 // be a canonical type either, so fill in the canonical type field.
2709 QualType Canon;
2710 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2711 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002712 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002713 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002714 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002715
Chris Lattner36f8e652007-01-27 08:31:04 +00002716 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002717 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002718 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002719 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002720 }
Mike Stump11289f42009-09-09 15:08:12 +00002721
John McCall90d1c2d2009-09-24 23:30:46 +00002722 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002723 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002724 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002725 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002726 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002727}
2728
John McCall06549462011-01-18 08:40:38 +00002729/// getVariableArrayDecayedType - Turns the given type, which may be
2730/// variably-modified, into the corresponding type with all the known
2731/// sizes replaced with [*].
2732QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2733 // Vastly most common case.
2734 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002735
John McCall06549462011-01-18 08:40:38 +00002736 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002737
John McCall06549462011-01-18 08:40:38 +00002738 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002739 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002740 switch (ty->getTypeClass()) {
2741#define TYPE(Class, Base)
2742#define ABSTRACT_TYPE(Class, Base)
2743#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2744#include "clang/AST/TypeNodes.def"
2745 llvm_unreachable("didn't desugar past all non-canonical types?");
2746
2747 // These types should never be variably-modified.
2748 case Type::Builtin:
2749 case Type::Complex:
2750 case Type::Vector:
2751 case Type::ExtVector:
2752 case Type::DependentSizedExtVector:
2753 case Type::ObjCObject:
2754 case Type::ObjCInterface:
2755 case Type::ObjCObjectPointer:
2756 case Type::Record:
2757 case Type::Enum:
2758 case Type::UnresolvedUsing:
2759 case Type::TypeOfExpr:
2760 case Type::TypeOf:
2761 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002762 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002763 case Type::DependentName:
2764 case Type::InjectedClassName:
2765 case Type::TemplateSpecialization:
2766 case Type::DependentTemplateSpecialization:
2767 case Type::TemplateTypeParm:
2768 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002769 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002770 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002771 case Type::PackExpansion:
2772 llvm_unreachable("type should never be variably-modified");
2773
2774 // These types can be variably-modified but should never need to
2775 // further decay.
2776 case Type::FunctionNoProto:
2777 case Type::FunctionProto:
2778 case Type::BlockPointer:
2779 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002780 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002781 return type;
2782
2783 // These types can be variably-modified. All these modifications
2784 // preserve structure except as noted by comments.
2785 // TODO: if we ever care about optimizing VLAs, there are no-op
2786 // optimizations available here.
2787 case Type::Pointer:
2788 result = getPointerType(getVariableArrayDecayedType(
2789 cast<PointerType>(ty)->getPointeeType()));
2790 break;
2791
2792 case Type::LValueReference: {
2793 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2794 result = getLValueReferenceType(
2795 getVariableArrayDecayedType(lv->getPointeeType()),
2796 lv->isSpelledAsLValue());
2797 break;
2798 }
2799
2800 case Type::RValueReference: {
2801 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2802 result = getRValueReferenceType(
2803 getVariableArrayDecayedType(lv->getPointeeType()));
2804 break;
2805 }
2806
Eli Friedman0dfb8892011-10-06 23:00:33 +00002807 case Type::Atomic: {
2808 const AtomicType *at = cast<AtomicType>(ty);
2809 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2810 break;
2811 }
2812
John McCall06549462011-01-18 08:40:38 +00002813 case Type::ConstantArray: {
2814 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2815 result = getConstantArrayType(
2816 getVariableArrayDecayedType(cat->getElementType()),
2817 cat->getSize(),
2818 cat->getSizeModifier(),
2819 cat->getIndexTypeCVRQualifiers());
2820 break;
2821 }
2822
2823 case Type::DependentSizedArray: {
2824 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2825 result = getDependentSizedArrayType(
2826 getVariableArrayDecayedType(dat->getElementType()),
2827 dat->getSizeExpr(),
2828 dat->getSizeModifier(),
2829 dat->getIndexTypeCVRQualifiers(),
2830 dat->getBracketsRange());
2831 break;
2832 }
2833
2834 // Turn incomplete types into [*] types.
2835 case Type::IncompleteArray: {
2836 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2837 result = getVariableArrayType(
2838 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002839 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002840 ArrayType::Normal,
2841 iat->getIndexTypeCVRQualifiers(),
2842 SourceRange());
2843 break;
2844 }
2845
2846 // Turn VLA types into [*] types.
2847 case Type::VariableArray: {
2848 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2849 result = getVariableArrayType(
2850 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002851 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002852 ArrayType::Star,
2853 vat->getIndexTypeCVRQualifiers(),
2854 vat->getBracketsRange());
2855 break;
2856 }
2857 }
2858
2859 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002860 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002861}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002862
Steve Naroffcadebd02007-08-30 18:14:25 +00002863/// getVariableArrayType - Returns a non-unique reference to the type for a
2864/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002865QualType ASTContext::getVariableArrayType(QualType EltTy,
2866 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002867 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002868 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002869 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002870 // Since we don't unique expressions, it isn't possible to unique VLA's
2871 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002872 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002873
John McCall33ddac02011-01-19 10:06:00 +00002874 // Be sure to pull qualifiers off the element type.
2875 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2876 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002877 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002878 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002879 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002880 }
2881
John McCall90d1c2d2009-09-24 23:30:46 +00002882 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002883 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002884
2885 VariableArrayTypes.push_back(New);
2886 Types.push_back(New);
2887 return QualType(New, 0);
2888}
2889
Douglas Gregor4619e432008-12-05 23:32:09 +00002890/// getDependentSizedArrayType - Returns a non-unique reference to
2891/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002892/// type.
John McCall33ddac02011-01-19 10:06:00 +00002893QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2894 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002895 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002896 unsigned elementTypeQuals,
2897 SourceRange brackets) const {
2898 assert((!numElements || numElements->isTypeDependent() ||
2899 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002900 "Size must be type- or value-dependent!");
2901
John McCall33ddac02011-01-19 10:06:00 +00002902 // Dependently-sized array types that do not have a specified number
2903 // of elements will have their sizes deduced from a dependent
2904 // initializer. We do no canonicalization here at all, which is okay
2905 // because they can't be used in most locations.
2906 if (!numElements) {
2907 DependentSizedArrayType *newType
2908 = new (*this, TypeAlignment)
2909 DependentSizedArrayType(*this, elementType, QualType(),
2910 numElements, ASM, elementTypeQuals,
2911 brackets);
2912 Types.push_back(newType);
2913 return QualType(newType, 0);
2914 }
2915
2916 // Otherwise, we actually build a new type every time, but we
2917 // also build a canonical type.
2918
2919 SplitQualType canonElementType = getCanonicalType(elementType).split();
2920
Craig Topper36250ad2014-05-12 05:36:57 +00002921 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002922 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002923 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002924 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002925 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002926
John McCall33ddac02011-01-19 10:06:00 +00002927 // Look for an existing type with these properties.
2928 DependentSizedArrayType *canonTy =
2929 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002930
John McCall33ddac02011-01-19 10:06:00 +00002931 // If we don't have one, build one.
2932 if (!canonTy) {
2933 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002934 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002935 QualType(), numElements, ASM, elementTypeQuals,
2936 brackets);
2937 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2938 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002939 }
2940
John McCall33ddac02011-01-19 10:06:00 +00002941 // Apply qualifiers from the element type to the array.
2942 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002943 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002944
David Majnemer16a74702015-07-24 05:54:19 +00002945 // If we didn't need extra canonicalization for the element type or the size
2946 // expression, then just use that as our result.
2947 if (QualType(canonElementType.Ty, 0) == elementType &&
2948 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002949 return canon;
2950
2951 // Otherwise, we need to build a type which follows the spelling
2952 // of the element type.
2953 DependentSizedArrayType *sugaredType
2954 = new (*this, TypeAlignment)
2955 DependentSizedArrayType(*this, elementType, canon, numElements,
2956 ASM, elementTypeQuals, brackets);
2957 Types.push_back(sugaredType);
2958 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002959}
2960
John McCall33ddac02011-01-19 10:06:00 +00002961QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002962 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002963 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002964 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002965 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002966
Craig Topper36250ad2014-05-12 05:36:57 +00002967 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002968 if (IncompleteArrayType *iat =
2969 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2970 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002971
2972 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002973 // either, so fill in the canonical type field. We also have to pull
2974 // qualifiers off the element type.
2975 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002976
John McCall33ddac02011-01-19 10:06:00 +00002977 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2978 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002979 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002980 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002981 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002982
2983 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002984 IncompleteArrayType *existing =
2985 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2986 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002987 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002988
John McCall33ddac02011-01-19 10:06:00 +00002989 IncompleteArrayType *newType = new (*this, TypeAlignment)
2990 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002991
John McCall33ddac02011-01-19 10:06:00 +00002992 IncompleteArrayTypes.InsertNode(newType, insertPos);
2993 Types.push_back(newType);
2994 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002995}
2996
Steve Naroff91fcddb2007-07-18 18:00:27 +00002997/// getVectorType - Return the unique reference to a vector type of
2998/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002999QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003000 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003001 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003002
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003003 // Check if we've already instantiated a vector of this type.
3004 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003005 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003006
Craig Topper36250ad2014-05-12 05:36:57 +00003007 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003008 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3009 return QualType(VTP, 0);
3010
3011 // If the element type isn't canonical, this won't be a canonical type either,
3012 // so fill in the canonical type field.
3013 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003014 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003015 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003016
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003017 // Get the new insert position for the node we care about.
3018 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003019 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003020 }
John McCall90d1c2d2009-09-24 23:30:46 +00003021 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003022 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003023 VectorTypes.InsertNode(New, InsertPos);
3024 Types.push_back(New);
3025 return QualType(New, 0);
3026}
3027
Nate Begemance4d7fc2008-04-18 23:10:10 +00003028/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003029/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003030QualType
3031ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003032 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003033
Steve Naroff91fcddb2007-07-18 18:00:27 +00003034 // Check if we've already instantiated a vector of this type.
3035 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003036 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003037 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003038 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003039 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3040 return QualType(VTP, 0);
3041
3042 // If the element type isn't canonical, this won't be a canonical type either,
3043 // so fill in the canonical type field.
3044 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003045 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003046 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003047
Steve Naroff91fcddb2007-07-18 18:00:27 +00003048 // Get the new insert position for the node we care about.
3049 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003050 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003051 }
John McCall90d1c2d2009-09-24 23:30:46 +00003052 ExtVectorType *New = new (*this, TypeAlignment)
3053 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003054 VectorTypes.InsertNode(New, InsertPos);
3055 Types.push_back(New);
3056 return QualType(New, 0);
3057}
3058
Jay Foad39c79802011-01-12 09:06:06 +00003059QualType
3060ASTContext::getDependentSizedExtVectorType(QualType vecType,
3061 Expr *SizeExpr,
3062 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003063 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003064 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003065 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003066
Craig Topper36250ad2014-05-12 05:36:57 +00003067 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003068 DependentSizedExtVectorType *Canon
3069 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3070 DependentSizedExtVectorType *New;
3071 if (Canon) {
3072 // We already have a canonical version of this array type; use it as
3073 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003074 New = new (*this, TypeAlignment)
3075 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3076 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003077 } else {
3078 QualType CanonVecTy = getCanonicalType(vecType);
3079 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003080 New = new (*this, TypeAlignment)
3081 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3082 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003083
3084 DependentSizedExtVectorType *CanonCheck
3085 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3086 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3087 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003088 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3089 } else {
3090 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3091 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003092 New = new (*this, TypeAlignment)
3093 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003094 }
3095 }
Mike Stump11289f42009-09-09 15:08:12 +00003096
Douglas Gregor758a8692009-06-17 21:51:59 +00003097 Types.push_back(New);
3098 return QualType(New, 0);
3099}
3100
John McCall18afab72016-03-01 00:49:02 +00003101/// \brief Determine whether \p T is canonical as the result type of a function.
3102static bool isCanonicalResultType(QualType T) {
3103 return T.isCanonical() &&
3104 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3105 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3106}
3107
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003108/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003109///
Jay Foad39c79802011-01-12 09:06:06 +00003110QualType
3111ASTContext::getFunctionNoProtoType(QualType ResultTy,
3112 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003113 // Unique functions, to guarantee there is only one function of a particular
3114 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003115 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003116 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003117
Craig Topper36250ad2014-05-12 05:36:57 +00003118 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003119 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003120 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003121 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003122
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003123 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003124 if (!isCanonicalResultType(ResultTy)) {
3125 Canonical =
3126 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003127
Chris Lattner47955de2007-01-27 08:37:20 +00003128 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003129 FunctionNoProtoType *NewIP =
3130 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003131 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003132 }
Mike Stump11289f42009-09-09 15:08:12 +00003133
John McCall90d1c2d2009-09-24 23:30:46 +00003134 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003135 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003136 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003137 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003138 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003139}
3140
Douglas Gregora602a152015-10-01 20:20:47 +00003141CanQualType
3142ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3143 CanQualType CanResultType = getCanonicalType(ResultType);
3144
3145 // Canonical result types do not have ARC lifetime qualifiers.
3146 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3147 Qualifiers Qs = CanResultType.getQualifiers();
3148 Qs.removeObjCLifetime();
3149 return CanQualType::CreateUnsafe(
3150 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3151 }
3152
3153 return CanResultType;
3154}
3155
Richard Smith3c4f8d22016-10-16 17:54:23 +00003156static bool isCanonicalExceptionSpecification(
3157 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3158 if (ESI.Type == EST_None)
3159 return true;
3160 if (!NoexceptInType)
3161 return false;
3162
3163 // C++17 onwards: exception specification is part of the type, as a simple
3164 // boolean "can this function type throw".
3165 if (ESI.Type == EST_BasicNoexcept)
3166 return true;
3167
3168 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003169 // expansions (so we can't tell whether it's non-throwing) and all its
3170 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003171 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003172 bool AnyPackExpansions = false;
3173 for (QualType ET : ESI.Exceptions) {
3174 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003175 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003176 if (ET->getAs<PackExpansionType>())
3177 AnyPackExpansions = true;
3178 }
3179 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003180 }
3181
Richard Smith2a2cda52016-10-18 19:29:18 +00003182 // A noexcept(expr) specification is (possibly) canonical if expr is
3183 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003184 if (ESI.Type == EST_ComputedNoexcept)
3185 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3186
3187 return false;
3188}
3189
Richard Smith304b1242016-10-18 20:13:25 +00003190QualType ASTContext::getFunctionTypeInternal(
3191 QualType ResultTy, ArrayRef<QualType> ArgArray,
3192 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003193 size_t NumArgs = ArgArray.size();
3194
Richard Smith2a2cda52016-10-18 19:29:18 +00003195 // Unique functions, to guarantee there is only one function of a particular
3196 // structure.
3197 llvm::FoldingSetNodeID ID;
3198 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3199 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003200
Richard Smith2a2cda52016-10-18 19:29:18 +00003201 QualType Canonical;
3202 bool Unique = false;
3203
3204 void *InsertPos = nullptr;
3205 if (FunctionProtoType *FPT =
3206 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3207 QualType Existing = QualType(FPT, 0);
3208
3209 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3210 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003211 // noexcept expression, or we're just looking for a canonical type.
3212 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003213 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003214 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003215 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3216 return Existing;
3217
3218 // We need a new type sugar node for this one, to hold the new noexcept
3219 // expression. We do no canonicalization here, but that's OK since we don't
3220 // expect to see the same noexcept expression much more than once.
3221 Canonical = getCanonicalType(Existing);
3222 Unique = true;
3223 }
3224
3225 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003226 bool IsCanonicalExceptionSpec =
3227 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3228
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003229 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003230 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003231 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003232 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003233 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003234 isCanonical = false;
3235
Richard Smith304b1242016-10-18 20:13:25 +00003236 if (OnlyWantCanonical)
3237 assert(isCanonical &&
3238 "given non-canonical parameters constructing canonical type");
3239
Richard Smith2a2cda52016-10-18 19:29:18 +00003240 // If this type isn't canonical, get the canonical version of it if we don't
3241 // already have it. The exception spec is only partially part of the
3242 // canonical type, and only in C++17 onwards.
3243 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003244 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003245 CanonicalArgs.reserve(NumArgs);
3246 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003247 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003248
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003249 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003250 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003251 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003252
3253 if (IsCanonicalExceptionSpec) {
3254 // Exception spec is already OK.
3255 } else if (NoexceptInType) {
3256 switch (EPI.ExceptionSpec.Type) {
3257 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3258 // We don't know yet. It shouldn't matter what we pick here; no-one
3259 // should ever look at this.
3260 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003261 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003262 CanonicalEPI.ExceptionSpec.Type = EST_None;
3263 break;
3264
Richard Smith2a2cda52016-10-18 19:29:18 +00003265 // A dynamic exception specification is almost always "not noexcept",
3266 // with the exception that a pack expansion might expand to no types.
3267 case EST_Dynamic: {
3268 bool AnyPacks = false;
3269 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3270 if (ET->getAs<PackExpansionType>())
3271 AnyPacks = true;
3272 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3273 }
3274 if (!AnyPacks)
3275 CanonicalEPI.ExceptionSpec.Type = EST_None;
3276 else {
3277 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3278 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3279 }
3280 break;
3281 }
3282
Richard Smith3c4f8d22016-10-16 17:54:23 +00003283 case EST_DynamicNone: case EST_BasicNoexcept:
3284 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3285 break;
3286
3287 case EST_ComputedNoexcept:
3288 llvm::APSInt Value(1);
3289 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3290 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3291 /*IsEvaluated*/false)) {
3292 // This noexcept specification is invalid.
3293 // FIXME: Should this be able to happen?
3294 CanonicalEPI.ExceptionSpec.Type = EST_None;
3295 break;
3296 }
3297
3298 CanonicalEPI.ExceptionSpec.Type =
3299 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3300 break;
3301 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003302 } else {
3303 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3304 }
John McCalldb40c7f2010-12-14 08:05:40 +00003305
Douglas Gregora602a152015-10-01 20:20:47 +00003306 // Adjust the canonical function result type.
3307 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003308 Canonical =
3309 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003310
Chris Lattnerfd4de792007-01-27 01:15:32 +00003311 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003312 FunctionProtoType *NewIP =
3313 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003314 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003315 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003316
John McCall31168b02011-06-15 23:02:42 +00003317 // FunctionProtoType objects are allocated with extra bytes after
3318 // them for three variable size arrays at the end:
3319 // - parameter types
3320 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003321 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003322 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003323 // expression, or information used to resolve the exception
3324 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003325 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003326 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003327
Richard Smith8acb4282014-07-31 21:57:55 +00003328 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3329 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3330 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003331 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003332 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003333 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003334 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003335 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003336 }
John McCall18afab72016-03-01 00:49:02 +00003337
3338 // Put the ExtParameterInfos last. If all were equal, it would make
3339 // more sense to put these before the exception specification, because
3340 // it's much easier to skip past them compared to the elaborate switch
3341 // required to skip the exception specification. However, all is not
3342 // equal; ExtParameterInfos are used to model very uncommon features,
3343 // and it's better not to burden the more common paths.
3344 if (EPI.ExtParameterInfos) {
3345 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3346 }
John McCall31168b02011-06-15 23:02:42 +00003347
John McCalldb40c7f2010-12-14 08:05:40 +00003348 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003349 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003350 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003351 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003352 if (!Unique)
3353 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003354 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003355}
Chris Lattneref51c202006-11-10 07:17:23 +00003356
Joey Goulye3c85de2016-12-01 11:30:49 +00003357QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003358 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003359 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003360
3361 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003362 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003363 return QualType(PT, 0);
3364
3365 // If the pipe element type isn't canonical, this won't be a canonical type
3366 // either, so fill in the canonical type field.
3367 QualType Canonical;
3368 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003369 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003370
3371 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003372 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003373 assert(!NewIP && "Shouldn't be in the map!");
3374 (void)NewIP;
3375 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003376 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003377 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003378 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003379 return QualType(New, 0);
3380}
3381
Joey Goulye3c85de2016-12-01 11:30:49 +00003382QualType ASTContext::getReadPipeType(QualType T) const {
3383 return getPipeType(T, true);
3384}
3385
Joey Gouly5788b782016-11-18 14:10:54 +00003386QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003387 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003388}
3389
John McCalle78aac42010-03-10 03:28:59 +00003390#ifndef NDEBUG
3391static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3392 if (!isa<CXXRecordDecl>(D)) return false;
3393 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3394 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3395 return true;
3396 if (RD->getDescribedClassTemplate() &&
3397 !isa<ClassTemplateSpecializationDecl>(RD))
3398 return true;
3399 return false;
3400}
3401#endif
3402
3403/// getInjectedClassNameType - Return the unique reference to the
3404/// injected class name type for the specified templated declaration.
3405QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003406 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003407 assert(NeedsInjectedClassNameType(Decl));
3408 if (Decl->TypeForDecl) {
3409 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003410 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003411 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3412 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3413 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3414 } else {
John McCall424cec92011-01-19 06:33:43 +00003415 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003416 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003417 Decl->TypeForDecl = newType;
3418 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003419 }
3420 return QualType(Decl->TypeForDecl, 0);
3421}
3422
Douglas Gregor83a586e2008-04-13 21:07:44 +00003423/// getTypeDeclType - Return the unique reference to the type for the
3424/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003425QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003426 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003427 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003428
Richard Smithdda56e42011-04-15 14:24:37 +00003429 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003430 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003431
John McCall96f0b5f2010-03-10 06:48:02 +00003432 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3433 "Template type parameter types are always available.");
3434
John McCall81e38502010-02-16 03:57:14 +00003435 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003436 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003437 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003438 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003439 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003440 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003441 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003442 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003443 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003444 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3445 Decl->TypeForDecl = newType;
3446 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003447 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003448 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003449
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003450 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003451}
3452
Chris Lattner32d920b2007-01-26 02:01:53 +00003453/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003454/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003455QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003456ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3457 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003458 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003459
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003460 if (Canonical.isNull())
3461 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003462 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003463 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003464 Decl->TypeForDecl = newType;
3465 Types.push_back(newType);
3466 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003467}
3468
Jay Foad39c79802011-01-12 09:06:06 +00003469QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003470 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3471
Douglas Gregorec9fd132012-01-14 16:38:05 +00003472 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003473 if (PrevDecl->TypeForDecl)
3474 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3475
John McCall424cec92011-01-19 06:33:43 +00003476 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3477 Decl->TypeForDecl = newType;
3478 Types.push_back(newType);
3479 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003480}
3481
Jay Foad39c79802011-01-12 09:06:06 +00003482QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003483 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3484
Douglas Gregorec9fd132012-01-14 16:38:05 +00003485 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003486 if (PrevDecl->TypeForDecl)
3487 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3488
John McCall424cec92011-01-19 06:33:43 +00003489 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3490 Decl->TypeForDecl = newType;
3491 Types.push_back(newType);
3492 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003493}
3494
John McCall81904512011-01-06 01:58:22 +00003495QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3496 QualType modifiedType,
3497 QualType equivalentType) {
3498 llvm::FoldingSetNodeID id;
3499 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3500
Craig Topper36250ad2014-05-12 05:36:57 +00003501 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003502 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3503 if (type) return QualType(type, 0);
3504
3505 QualType canon = getCanonicalType(equivalentType);
3506 type = new (*this, TypeAlignment)
3507 AttributedType(canon, attrKind, modifiedType, equivalentType);
3508
3509 Types.push_back(type);
3510 AttributedTypes.InsertNode(type, insertPos);
3511
3512 return QualType(type, 0);
3513}
3514
John McCallcebee162009-10-18 09:09:24 +00003515/// \brief Retrieve a substitution-result type.
3516QualType
3517ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003518 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003519 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003520 && "replacement types must always be canonical");
3521
3522 llvm::FoldingSetNodeID ID;
3523 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003524 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003525 SubstTemplateTypeParmType *SubstParm
3526 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3527
3528 if (!SubstParm) {
3529 SubstParm = new (*this, TypeAlignment)
3530 SubstTemplateTypeParmType(Parm, Replacement);
3531 Types.push_back(SubstParm);
3532 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3533 }
3534
3535 return QualType(SubstParm, 0);
3536}
3537
Douglas Gregorada4b792011-01-14 02:55:32 +00003538/// \brief Retrieve a
3539QualType ASTContext::getSubstTemplateTypeParmPackType(
3540 const TemplateTypeParmType *Parm,
3541 const TemplateArgument &ArgPack) {
3542#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003543 for (const auto &P : ArgPack.pack_elements()) {
3544 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3545 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003546 }
3547#endif
3548
3549 llvm::FoldingSetNodeID ID;
3550 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003551 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003552 if (SubstTemplateTypeParmPackType *SubstParm
3553 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3554 return QualType(SubstParm, 0);
3555
3556 QualType Canon;
3557 if (!Parm->isCanonicalUnqualified()) {
3558 Canon = getCanonicalType(QualType(Parm, 0));
3559 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3560 ArgPack);
3561 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3562 }
3563
3564 SubstTemplateTypeParmPackType *SubstParm
3565 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3566 ArgPack);
3567 Types.push_back(SubstParm);
3568 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3569 return QualType(SubstParm, 0);
3570}
3571
Douglas Gregoreff93e02009-02-05 23:33:38 +00003572/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003573/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003574/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003575QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003576 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003577 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003578 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003579 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003580 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003581 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003582 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3583
3584 if (TypeParm)
3585 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003586
Chandler Carruth08836322011-05-01 00:51:33 +00003587 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003588 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003589 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003590
3591 TemplateTypeParmType *TypeCheck
3592 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3593 assert(!TypeCheck && "Template type parameter canonical type broken");
3594 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003595 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003596 TypeParm = new (*this, TypeAlignment)
3597 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003598
3599 Types.push_back(TypeParm);
3600 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3601
3602 return QualType(TypeParm, 0);
3603}
3604
John McCalle78aac42010-03-10 03:28:59 +00003605TypeSourceInfo *
3606ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3607 SourceLocation NameLoc,
3608 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003609 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003610 assert(!Name.getAsDependentTemplateName() &&
3611 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003612 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003613
3614 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003615 TemplateSpecializationTypeLoc TL =
3616 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003617 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003618 TL.setTemplateNameLoc(NameLoc);
3619 TL.setLAngleLoc(Args.getLAngleLoc());
3620 TL.setRAngleLoc(Args.getRAngleLoc());
3621 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3622 TL.setArgLocInfo(i, Args[i].getLocInfo());
3623 return DI;
3624}
3625
Mike Stump11289f42009-09-09 15:08:12 +00003626QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003627ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003628 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003629 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003630 assert(!Template.getAsDependentTemplateName() &&
3631 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003632
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003633 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003634 ArgVec.reserve(Args.size());
3635 for (const TemplateArgumentLoc &Arg : Args.arguments())
3636 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003637
David Majnemer6fbeee32016-07-07 04:43:07 +00003638 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003639}
3640
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003641#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003642static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3643 for (const TemplateArgument &Arg : Args)
3644 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003645 return true;
3646
3647 return true;
3648}
3649#endif
3650
John McCall0ad16662009-10-29 08:12:44 +00003651QualType
3652ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003653 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003654 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003655 assert(!Template.getAsDependentTemplateName() &&
3656 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003657 // Look through qualified template names.
3658 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3659 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003660
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003661 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003662 Template.getAsTemplateDecl() &&
3663 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003664 QualType CanonType;
3665 if (!Underlying.isNull())
3666 CanonType = getCanonicalType(Underlying);
3667 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003668 // We can get here with an alias template when the specialization contains
3669 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003670 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003671 "Caller must compute aliased type");
3672 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003673 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003674 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003675
Douglas Gregora8e02e72009-07-28 23:00:59 +00003676 // Allocate the (non-canonical) template specialization type, but don't
3677 // try to unique it: these types typically have location information that
3678 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003679 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003680 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003681 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003682 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003683 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003684 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003685 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003686
Douglas Gregor8bf42052009-02-09 18:46:07 +00003687 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003688 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003689}
3690
David Majnemer6fbeee32016-07-07 04:43:07 +00003691QualType ASTContext::getCanonicalTemplateSpecializationType(
3692 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003693 assert(!Template.getAsDependentTemplateName() &&
3694 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003695
Douglas Gregore29139c2011-03-03 17:04:51 +00003696 // Look through qualified template names.
3697 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3698 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003699
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003700 // Build the canonical template specialization type.
3701 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003702 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003703 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003704 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003705 for (const TemplateArgument &Arg : Args)
3706 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003707
3708 // Determine whether this canonical template specialization type already
3709 // exists.
3710 llvm::FoldingSetNodeID ID;
3711 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003712 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003713
Craig Topper36250ad2014-05-12 05:36:57 +00003714 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003715 TemplateSpecializationType *Spec
3716 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3717
3718 if (!Spec) {
3719 // Allocate a new canonical template specialization type.
3720 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3721 sizeof(TemplateArgument) * NumArgs),
3722 TypeAlignment);
3723 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003724 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003725 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003726 Types.push_back(Spec);
3727 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3728 }
3729
3730 assert(Spec->isDependentType() &&
3731 "Non-dependent template-id type must have a canonical type");
3732 return QualType(Spec, 0);
3733}
3734
3735QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003736ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3737 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003738 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003739 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003740 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003741
Craig Topper36250ad2014-05-12 05:36:57 +00003742 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003743 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003744 if (T)
3745 return QualType(T, 0);
3746
Douglas Gregorc42075a2010-02-04 18:10:26 +00003747 QualType Canon = NamedType;
3748 if (!Canon.isCanonical()) {
3749 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003750 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3751 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003752 (void)CheckT;
3753 }
3754
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003755 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003756 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003757 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003758 return QualType(T, 0);
3759}
3760
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003761QualType
Jay Foad39c79802011-01-12 09:06:06 +00003762ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003763 llvm::FoldingSetNodeID ID;
3764 ParenType::Profile(ID, InnerType);
3765
Craig Topper36250ad2014-05-12 05:36:57 +00003766 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003767 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3768 if (T)
3769 return QualType(T, 0);
3770
3771 QualType Canon = InnerType;
3772 if (!Canon.isCanonical()) {
3773 Canon = getCanonicalType(InnerType);
3774 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3775 assert(!CheckT && "Paren canonical type broken");
3776 (void)CheckT;
3777 }
3778
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003779 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003780 Types.push_back(T);
3781 ParenTypes.InsertNode(T, InsertPos);
3782 return QualType(T, 0);
3783}
3784
Douglas Gregor02085352010-03-31 20:19:30 +00003785QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3786 NestedNameSpecifier *NNS,
3787 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003788 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003789 if (Canon.isNull()) {
3790 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00003791 if (CanonNNS != NNS)
3792 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003793 }
3794
3795 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003796 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003797
Craig Topper36250ad2014-05-12 05:36:57 +00003798 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003799 DependentNameType *T
3800 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003801 if (T)
3802 return QualType(T, 0);
3803
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003804 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003805 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003806 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003807 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003808}
3809
Mike Stump11289f42009-09-09 15:08:12 +00003810QualType
John McCallc392f372010-06-11 00:33:02 +00003811ASTContext::getDependentTemplateSpecializationType(
3812 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003813 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003814 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003815 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003816 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003817 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003818 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3819 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003820 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003821}
3822
3823QualType
3824ASTContext::getDependentTemplateSpecializationType(
3825 ElaboratedTypeKeyword Keyword,
3826 NestedNameSpecifier *NNS,
3827 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003828 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003829 assert((!NNS || NNS->isDependent()) &&
3830 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003831
Douglas Gregorc42075a2010-02-04 18:10:26 +00003832 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003833 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003834 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003835
Craig Topper36250ad2014-05-12 05:36:57 +00003836 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003837 DependentTemplateSpecializationType *T
3838 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003839 if (T)
3840 return QualType(T, 0);
3841
John McCallc392f372010-06-11 00:33:02 +00003842 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003843
John McCallc392f372010-06-11 00:33:02 +00003844 ElaboratedTypeKeyword CanonKeyword = Keyword;
3845 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3846
3847 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003848 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003849 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003850 for (unsigned I = 0; I != NumArgs; ++I) {
3851 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3852 if (!CanonArgs[I].structurallyEquals(Args[I]))
3853 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003854 }
3855
John McCallc392f372010-06-11 00:33:02 +00003856 QualType Canon;
3857 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3858 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003859 Name,
3860 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003861
3862 // Find the insert position again.
3863 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3864 }
3865
3866 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3867 sizeof(TemplateArgument) * NumArgs),
3868 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003869 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003870 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003871 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003872 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003873 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003874}
3875
Richard Smith32918772017-02-14 00:25:28 +00003876TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3877 TemplateArgument Arg;
3878 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3879 QualType ArgType = getTypeDeclType(TTP);
3880 if (TTP->isParameterPack())
3881 ArgType = getPackExpansionType(ArgType, None);
3882
3883 Arg = TemplateArgument(ArgType);
3884 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3885 Expr *E = new (*this) DeclRefExpr(
3886 NTTP, /*enclosing*/false,
3887 NTTP->getType().getNonLValueExprType(*this),
3888 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3889
3890 if (NTTP->isParameterPack())
3891 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3892 None);
3893 Arg = TemplateArgument(E);
3894 } else {
3895 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3896 if (TTP->isParameterPack())
3897 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3898 else
3899 Arg = TemplateArgument(TemplateName(TTP));
3900 }
3901
3902 if (Param->isTemplateParameterPack())
3903 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3904
3905 return Arg;
3906}
3907
Richard Smith43e14d22016-12-23 02:10:11 +00003908void
3909ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3910 SmallVectorImpl<TemplateArgument> &Args) {
3911 Args.reserve(Args.size() + Params->size());
3912
Richard Smith32918772017-02-14 00:25:28 +00003913 for (NamedDecl *Param : *Params)
3914 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00003915}
3916
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003917QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003918 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003919 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003920 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003921
3922 assert(Pattern->containsUnexpandedParameterPack() &&
3923 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003924 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003925 PackExpansionType *T
3926 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3927 if (T)
3928 return QualType(T, 0);
3929
3930 QualType Canon;
3931 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003932 Canon = getCanonicalType(Pattern);
3933 // The canonical type might not contain an unexpanded parameter pack, if it
3934 // contains an alias template specialization which ignores one of its
3935 // parameters.
3936 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003937 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003938
Richard Smith68eea502012-07-16 00:20:35 +00003939 // Find the insert position again, in case we inserted an element into
3940 // PackExpansionTypes and invalidated our insert position.
3941 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3942 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003943 }
3944
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003945 T = new (*this, TypeAlignment)
3946 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003947 Types.push_back(T);
3948 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003949 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003950}
3951
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003952/// CmpProtocolNames - Comparison predicate for sorting protocols
3953/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003954static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3955 ObjCProtocolDecl *const *RHS) {
3956 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003957}
3958
Craig Topper1f26d5b2016-01-03 19:43:23 +00003959static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3960 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003961
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003962 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3963 return false;
3964
Craig Topper1f26d5b2016-01-03 19:43:23 +00003965 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003966 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003967 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003968 return false;
3969 return true;
3970}
3971
Craig Topper6a8c1512015-10-22 01:56:18 +00003972static void
3973SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003974 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003975 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003976
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003977 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003978 for (ObjCProtocolDecl *&P : Protocols)
3979 P = P->getCanonicalDecl();
3980
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003981 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003982 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3983 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003984}
3985
John McCall8b07ec22010-05-15 11:32:37 +00003986QualType ASTContext::getObjCObjectType(QualType BaseType,
3987 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003988 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003989 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003990 llvm::makeArrayRef(Protocols, NumProtocols),
3991 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003992}
3993
3994QualType ASTContext::getObjCObjectType(
3995 QualType baseType,
3996 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003997 ArrayRef<ObjCProtocolDecl *> protocols,
3998 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003999 // If the base type is an interface and there aren't any protocols or
4000 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004001 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4002 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004003 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004004
4005 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004006 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004007 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004008 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004009 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4010 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004011
Douglas Gregore9d95f12015-07-07 03:57:35 +00004012 // Determine the type arguments to be used for canonicalization,
4013 // which may be explicitly specified here or written on the base
4014 // type.
4015 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4016 if (effectiveTypeArgs.empty()) {
4017 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4018 effectiveTypeArgs = baseObject->getTypeArgs();
4019 }
John McCallfc93cf92009-10-22 22:37:11 +00004020
Douglas Gregore9d95f12015-07-07 03:57:35 +00004021 // Build the canonical type, which has the canonical base type and a
4022 // sorted-and-uniqued list of protocols and the type arguments
4023 // canonicalized.
4024 QualType canonical;
4025 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4026 effectiveTypeArgs.end(),
4027 [&](QualType type) {
4028 return type.isCanonical();
4029 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004030 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004031 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4032 // Determine the canonical type arguments.
4033 ArrayRef<QualType> canonTypeArgs;
4034 SmallVector<QualType, 4> canonTypeArgsVec;
4035 if (!typeArgsAreCanonical) {
4036 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4037 for (auto typeArg : effectiveTypeArgs)
4038 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4039 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004040 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004041 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004042 }
4043
Douglas Gregore9d95f12015-07-07 03:57:35 +00004044 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4045 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4046 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004047 canonProtocolsVec.append(protocols.begin(), protocols.end());
4048 SortAndUniqueProtocols(canonProtocolsVec);
4049 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004050 } else {
4051 canonProtocols = protocols;
4052 }
4053
4054 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004055 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004056
John McCallfc93cf92009-10-22 22:37:11 +00004057 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004058 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4059 }
4060
Douglas Gregore9d95f12015-07-07 03:57:35 +00004061 unsigned size = sizeof(ObjCObjectTypeImpl);
4062 size += typeArgs.size() * sizeof(QualType);
4063 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4064 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004065 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004066 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4067 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004068
4069 Types.push_back(T);
4070 ObjCObjectTypes.InsertNode(T, InsertPos);
4071 return QualType(T, 0);
4072}
4073
Manman Ren3569eb52016-09-13 17:03:12 +00004074/// Apply Objective-C protocol qualifiers to the given type.
4075/// If this is for the canonical type of a type parameter, we can apply
4076/// protocol qualifiers on the ObjCObjectPointerType.
4077QualType
4078ASTContext::applyObjCProtocolQualifiers(QualType type,
4079 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4080 bool allowOnPointerType) const {
4081 hasError = false;
4082
Manman Renc5705ba2016-09-13 17:41:05 +00004083 if (const ObjCTypeParamType *objT =
4084 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4085 return getObjCTypeParamType(objT->getDecl(), protocols);
4086 }
4087
Manman Ren3569eb52016-09-13 17:03:12 +00004088 // Apply protocol qualifiers to ObjCObjectPointerType.
4089 if (allowOnPointerType) {
4090 if (const ObjCObjectPointerType *objPtr =
4091 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4092 const ObjCObjectType *objT = objPtr->getObjectType();
4093 // Merge protocol lists and construct ObjCObjectType.
4094 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4095 protocolsVec.append(objT->qual_begin(),
4096 objT->qual_end());
4097 protocolsVec.append(protocols.begin(), protocols.end());
4098 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4099 type = getObjCObjectType(
4100 objT->getBaseType(),
4101 objT->getTypeArgsAsWritten(),
4102 protocols,
4103 objT->isKindOfTypeAsWritten());
4104 return getObjCObjectPointerType(type);
4105 }
4106 }
4107
4108 // Apply protocol qualifiers to ObjCObjectType.
4109 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4110 // FIXME: Check for protocols to which the class type is already
4111 // known to conform.
4112
4113 return getObjCObjectType(objT->getBaseType(),
4114 objT->getTypeArgsAsWritten(),
4115 protocols,
4116 objT->isKindOfTypeAsWritten());
4117 }
4118
4119 // If the canonical type is ObjCObjectType, ...
4120 if (type->isObjCObjectType()) {
4121 // Silently overwrite any existing protocol qualifiers.
4122 // TODO: determine whether that's the right thing to do.
4123
4124 // FIXME: Check for protocols to which the class type is already
4125 // known to conform.
4126 return getObjCObjectType(type, { }, protocols, false);
4127 }
4128
4129 // id<protocol-list>
4130 if (type->isObjCIdType()) {
4131 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4132 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4133 objPtr->isKindOfType());
4134 return getObjCObjectPointerType(type);
4135 }
4136
4137 // Class<protocol-list>
4138 if (type->isObjCClassType()) {
4139 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4140 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4141 objPtr->isKindOfType());
4142 return getObjCObjectPointerType(type);
4143 }
4144
4145 hasError = true;
4146 return type;
4147}
4148
Manman Rene6be26c2016-09-13 17:25:08 +00004149QualType
4150ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4151 ArrayRef<ObjCProtocolDecl *> protocols,
4152 QualType Canonical) const {
4153 // Look in the folding set for an existing type.
4154 llvm::FoldingSetNodeID ID;
4155 ObjCTypeParamType::Profile(ID, Decl, protocols);
4156 void *InsertPos = nullptr;
4157 if (ObjCTypeParamType *TypeParam =
4158 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4159 return QualType(TypeParam, 0);
4160
4161 if (Canonical.isNull()) {
4162 // We canonicalize to the underlying type.
4163 Canonical = getCanonicalType(Decl->getUnderlyingType());
4164 if (!protocols.empty()) {
4165 // Apply the protocol qualifers.
4166 bool hasError;
4167 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4168 true/*allowOnPointerType*/);
4169 assert(!hasError && "Error when apply protocol qualifier to bound type");
4170 }
4171 }
4172
4173 unsigned size = sizeof(ObjCTypeParamType);
4174 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4175 void *mem = Allocate(size, TypeAlignment);
4176 ObjCTypeParamType *newType = new (mem)
4177 ObjCTypeParamType(Decl, Canonical, protocols);
4178
4179 Types.push_back(newType);
4180 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4181 return QualType(newType, 0);
4182}
4183
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004184/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4185/// protocol list adopt all protocols in QT's qualified-id protocol
4186/// list.
4187bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4188 ObjCInterfaceDecl *IC) {
4189 if (!QT->isObjCQualifiedIdType())
4190 return false;
4191
4192 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4193 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004194 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004195 if (!IC->ClassImplementsProtocol(Proto, false))
4196 return false;
4197 }
4198 return true;
4199 }
4200 return false;
4201}
4202
4203/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4204/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4205/// of protocols.
4206bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4207 ObjCInterfaceDecl *IDecl) {
4208 if (!QT->isObjCQualifiedIdType())
4209 return false;
4210 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4211 if (!OPT)
4212 return false;
4213 if (!IDecl->hasDefinition())
4214 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004215 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4216 CollectInheritedProtocols(IDecl, InheritedProtocols);
4217 if (InheritedProtocols.empty())
4218 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004219 // Check that if every protocol in list of id<plist> conforms to a protcol
4220 // of IDecl's, then bridge casting is ok.
4221 bool Conforms = false;
4222 for (auto *Proto : OPT->quals()) {
4223 Conforms = false;
4224 for (auto *PI : InheritedProtocols) {
4225 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4226 Conforms = true;
4227 break;
4228 }
4229 }
4230 if (!Conforms)
4231 break;
4232 }
4233 if (Conforms)
4234 return true;
4235
Aaron Ballman83731462014-03-17 16:14:00 +00004236 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004237 // If both the right and left sides have qualifiers.
4238 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004239 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004240 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004241 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004242 break;
4243 }
4244 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004245 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004246 }
4247 return true;
4248}
4249
John McCall8b07ec22010-05-15 11:32:37 +00004250/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4251/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004252QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004253 llvm::FoldingSetNodeID ID;
4254 ObjCObjectPointerType::Profile(ID, ObjectT);
4255
Craig Topper36250ad2014-05-12 05:36:57 +00004256 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004257 if (ObjCObjectPointerType *QT =
4258 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4259 return QualType(QT, 0);
4260
4261 // Find the canonical object type.
4262 QualType Canonical;
4263 if (!ObjectT.isCanonical()) {
4264 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4265
4266 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004267 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4268 }
4269
Douglas Gregorf85bee62010-02-08 22:59:26 +00004270 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004271 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4272 ObjCObjectPointerType *QType =
4273 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004274
Steve Narofffb4330f2009-06-17 22:40:22 +00004275 Types.push_back(QType);
4276 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004277 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004278}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004279
Douglas Gregor1c283312010-08-11 12:19:30 +00004280/// getObjCInterfaceType - Return the unique reference to the type for the
4281/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004282QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4283 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004284 if (Decl->TypeForDecl)
4285 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004286
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004287 if (PrevDecl) {
4288 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4289 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4290 return QualType(PrevDecl->TypeForDecl, 0);
4291 }
4292
Douglas Gregor7671e532011-12-16 16:34:57 +00004293 // Prefer the definition, if there is one.
4294 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4295 Decl = Def;
4296
Douglas Gregor1c283312010-08-11 12:19:30 +00004297 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4298 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4299 Decl->TypeForDecl = T;
4300 Types.push_back(T);
4301 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004302}
4303
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004304/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4305/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004306/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004307/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004308/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004309QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004310 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004311 if (tofExpr->isTypeDependent()) {
4312 llvm::FoldingSetNodeID ID;
4313 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004314
Craig Topper36250ad2014-05-12 05:36:57 +00004315 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004316 DependentTypeOfExprType *Canon
4317 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4318 if (Canon) {
4319 // We already have a "canonical" version of an identical, dependent
4320 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004321 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004322 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004323 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004324 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004325 Canon
4326 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004327 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4328 toe = Canon;
4329 }
4330 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004331 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004332 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004333 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004334 Types.push_back(toe);
4335 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004336}
4337
Steve Naroffa773cd52007-08-01 18:02:17 +00004338/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004339/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004340/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004341/// an issue. This doesn't affect the type checker, since it operates
4342/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004343QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004344 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004345 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004346 Types.push_back(tot);
4347 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004348}
4349
Richard Smith8eb1d322014-06-05 20:13:13 +00004350/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4351/// nodes. This would never be helpful, since each such type has its own
4352/// expression, and would not give a significant memory saving, since there
4353/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004354QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004355 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004356
4357 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004358 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004359 // unique dependent type. Two such decltype-specifiers refer to the same
4360 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004361 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004362 llvm::FoldingSetNodeID ID;
4363 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004364
Craig Topper36250ad2014-05-12 05:36:57 +00004365 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004366 DependentDecltypeType *Canon
4367 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004368 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004369 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004370 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004371 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004372 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004373 dt = new (*this, TypeAlignment)
4374 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004375 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004376 dt = new (*this, TypeAlignment)
4377 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004378 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004379 Types.push_back(dt);
4380 return QualType(dt, 0);
4381}
4382
Alexis Hunte852b102011-05-24 22:41:36 +00004383/// getUnaryTransformationType - We don't unique these, since the memory
4384/// savings are minimal and these are rare.
4385QualType ASTContext::getUnaryTransformType(QualType BaseType,
4386 QualType UnderlyingType,
4387 UnaryTransformType::UTTKind Kind)
4388 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004389 UnaryTransformType *ut = nullptr;
4390
4391 if (BaseType->isDependentType()) {
4392 // Look in the folding set for an existing type.
4393 llvm::FoldingSetNodeID ID;
4394 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4395
4396 void *InsertPos = nullptr;
4397 DependentUnaryTransformType *Canon
4398 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4399
4400 if (!Canon) {
4401 // Build a new, canonical __underlying_type(type) type.
4402 Canon = new (*this, TypeAlignment)
4403 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4404 Kind);
4405 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4406 }
4407 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4408 QualType(), Kind,
4409 QualType(Canon, 0));
4410 } else {
4411 QualType CanonType = getCanonicalType(UnderlyingType);
4412 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4413 UnderlyingType, Kind,
4414 CanonType);
4415 }
4416 Types.push_back(ut);
4417 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004418}
4419
Richard Smith2a7d4812013-05-04 07:00:32 +00004420/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4421/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4422/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004423QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004424 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004425 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004426 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004427
Richard Smith2a7d4812013-05-04 07:00:32 +00004428 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004429 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004430 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004431 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004432 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4433 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004434
Richard Smith74aeef52013-04-26 16:15:35 +00004435 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004436 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004437 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004438 Types.push_back(AT);
4439 if (InsertPos)
4440 AutoTypes.InsertNode(AT, InsertPos);
4441 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004442}
4443
Richard Smith600b5262017-01-26 20:40:47 +00004444/// Return the uniqued reference to the deduced template specialization type
4445/// which has been deduced to the given type, or to the canonical undeduced
4446/// such type, or the canonical deduced-but-dependent such type.
4447QualType ASTContext::getDeducedTemplateSpecializationType(
4448 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4449 // Look in the folding set for an existing type.
4450 void *InsertPos = nullptr;
4451 llvm::FoldingSetNodeID ID;
4452 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4453 IsDependent);
4454 if (DeducedTemplateSpecializationType *DTST =
4455 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4456 return QualType(DTST, 0);
4457
4458 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4459 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4460 Types.push_back(DTST);
4461 if (InsertPos)
4462 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4463 return QualType(DTST, 0);
4464}
4465
Eli Friedman0dfb8892011-10-06 23:00:33 +00004466/// getAtomicType - Return the uniqued reference to the atomic type for
4467/// the given value type.
4468QualType ASTContext::getAtomicType(QualType T) const {
4469 // Unique pointers, to guarantee there is only one pointer of a particular
4470 // structure.
4471 llvm::FoldingSetNodeID ID;
4472 AtomicType::Profile(ID, T);
4473
Craig Topper36250ad2014-05-12 05:36:57 +00004474 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004475 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4476 return QualType(AT, 0);
4477
4478 // If the atomic value type isn't canonical, this won't be a canonical type
4479 // either, so fill in the canonical type field.
4480 QualType Canonical;
4481 if (!T.isCanonical()) {
4482 Canonical = getAtomicType(getCanonicalType(T));
4483
4484 // Get the new insert position for the node we care about.
4485 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004486 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004487 }
4488 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4489 Types.push_back(New);
4490 AtomicTypes.InsertNode(New, InsertPos);
4491 return QualType(New, 0);
4492}
4493
Richard Smith02e85f32011-04-14 22:09:26 +00004494/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4495QualType ASTContext::getAutoDeductType() const {
4496 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004497 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004498 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004499 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004500 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004501 return AutoDeductTy;
4502}
4503
4504/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4505QualType ASTContext::getAutoRRefDeductType() const {
4506 if (AutoRRefDeductTy.isNull())
4507 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4508 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4509 return AutoRRefDeductTy;
4510}
4511
Chris Lattnerfb072462007-01-23 05:45:31 +00004512/// getTagDeclType - Return the unique reference to the type for the
4513/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004514QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004515 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004516 // FIXME: What is the design on getTagDeclType when it requires casting
4517 // away const? mutable?
4518 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004519}
4520
Mike Stump11289f42009-09-09 15:08:12 +00004521/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4522/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4523/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004524CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004525 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004526}
Chris Lattnerfb072462007-01-23 05:45:31 +00004527
Hans Wennborg27541db2011-10-27 08:29:09 +00004528/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4529CanQualType ASTContext::getIntMaxType() const {
4530 return getFromTargetType(Target->getIntMaxType());
4531}
4532
4533/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4534CanQualType ASTContext::getUIntMaxType() const {
4535 return getFromTargetType(Target->getUIntMaxType());
4536}
4537
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004538/// getSignedWCharType - Return the type of "signed wchar_t".
4539/// Used when in C++, as a GCC extension.
4540QualType ASTContext::getSignedWCharType() const {
4541 // FIXME: derive from "Target" ?
4542 return WCharTy;
4543}
4544
4545/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4546/// Used when in C++, as a GCC extension.
4547QualType ASTContext::getUnsignedWCharType() const {
4548 // FIXME: derive from "Target" ?
4549 return UnsignedIntTy;
4550}
4551
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004552QualType ASTContext::getIntPtrType() const {
4553 return getFromTargetType(Target->getIntPtrType());
4554}
4555
4556QualType ASTContext::getUIntPtrType() const {
4557 return getCorrespondingUnsignedType(getIntPtrType());
4558}
4559
Hans Wennborg27541db2011-10-27 08:29:09 +00004560/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004561/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4562QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004563 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004564}
4565
Eli Friedman4e91899e2012-11-27 02:58:24 +00004566/// \brief Return the unique type for "pid_t" defined in
4567/// <sys/types.h>. We need this to compute the correct type for vfork().
4568QualType ASTContext::getProcessIDType() const {
4569 return getFromTargetType(Target->getProcessIDType());
4570}
4571
Chris Lattnera21ad802008-04-02 05:18:44 +00004572//===----------------------------------------------------------------------===//
4573// Type Operators
4574//===----------------------------------------------------------------------===//
4575
Jay Foad39c79802011-01-12 09:06:06 +00004576CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004577 // Push qualifiers into arrays, and then discard any remaining
4578 // qualifiers.
4579 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004580 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004581 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004582 QualType Result;
4583 if (isa<ArrayType>(Ty)) {
4584 Result = getArrayDecayedType(QualType(Ty,0));
4585 } else if (isa<FunctionType>(Ty)) {
4586 Result = getPointerType(QualType(Ty, 0));
4587 } else {
4588 Result = QualType(Ty, 0);
4589 }
4590
4591 return CanQualType::CreateUnsafe(Result);
4592}
4593
John McCall6c9dd522011-01-18 07:41:22 +00004594QualType ASTContext::getUnqualifiedArrayType(QualType type,
4595 Qualifiers &quals) {
4596 SplitQualType splitType = type.getSplitUnqualifiedType();
4597
4598 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4599 // the unqualified desugared type and then drops it on the floor.
4600 // We then have to strip that sugar back off with
4601 // getUnqualifiedDesugaredType(), which is silly.
4602 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004603 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004604
4605 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004606 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004607 quals = splitType.Quals;
4608 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004609 }
4610
John McCall6c9dd522011-01-18 07:41:22 +00004611 // Otherwise, recurse on the array's element type.
4612 QualType elementType = AT->getElementType();
4613 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4614
4615 // If that didn't change the element type, AT has no qualifiers, so we
4616 // can just use the results in splitType.
4617 if (elementType == unqualElementType) {
4618 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004619 quals = splitType.Quals;
4620 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004621 }
4622
4623 // Otherwise, add in the qualifiers from the outermost type, then
4624 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004625 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004626
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004627 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004628 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004629 CAT->getSizeModifier(), 0);
4630 }
4631
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004632 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004633 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004634 }
4635
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004636 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004637 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004638 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004639 VAT->getSizeModifier(),
4640 VAT->getIndexTypeCVRQualifiers(),
4641 VAT->getBracketsRange());
4642 }
4643
4644 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004645 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004646 DSAT->getSizeModifier(), 0,
4647 SourceRange());
4648}
4649
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004650/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4651/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4652/// they point to and return true. If T1 and T2 aren't pointer types
4653/// or pointer-to-member types, or if they are not similar at this
4654/// level, returns false and leaves T1 and T2 unchanged. Top-level
4655/// qualifiers on T1 and T2 are ignored. This function will typically
4656/// be called in a loop that successively "unwraps" pointer and
4657/// pointer-to-member types to compare them at each level.
4658bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4659 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4660 *T2PtrType = T2->getAs<PointerType>();
4661 if (T1PtrType && T2PtrType) {
4662 T1 = T1PtrType->getPointeeType();
4663 T2 = T2PtrType->getPointeeType();
4664 return true;
4665 }
4666
4667 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4668 *T2MPType = T2->getAs<MemberPointerType>();
4669 if (T1MPType && T2MPType &&
4670 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4671 QualType(T2MPType->getClass(), 0))) {
4672 T1 = T1MPType->getPointeeType();
4673 T2 = T2MPType->getPointeeType();
4674 return true;
4675 }
4676
David Blaikiebbafb8a2012-03-11 07:00:24 +00004677 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004678 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4679 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4680 if (T1OPType && T2OPType) {
4681 T1 = T1OPType->getPointeeType();
4682 T2 = T2OPType->getPointeeType();
4683 return true;
4684 }
4685 }
4686
4687 // FIXME: Block pointers, too?
4688
4689 return false;
4690}
4691
Jay Foad39c79802011-01-12 09:06:06 +00004692DeclarationNameInfo
4693ASTContext::getNameForTemplate(TemplateName Name,
4694 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004695 switch (Name.getKind()) {
4696 case TemplateName::QualifiedTemplate:
4697 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004698 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004699 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4700 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004701
John McCalld9dfe3a2011-06-30 08:33:18 +00004702 case TemplateName::OverloadedTemplate: {
4703 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4704 // DNInfo work in progress: CHECKME: what about DNLoc?
4705 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4706 }
4707
4708 case TemplateName::DependentTemplate: {
4709 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004710 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004711 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004712 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4713 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004714 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004715 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4716 // DNInfo work in progress: FIXME: source locations?
4717 DeclarationNameLoc DNLoc;
4718 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4719 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4720 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004721 }
4722 }
4723
John McCalld9dfe3a2011-06-30 08:33:18 +00004724 case TemplateName::SubstTemplateTemplateParm: {
4725 SubstTemplateTemplateParmStorage *subst
4726 = Name.getAsSubstTemplateTemplateParm();
4727 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4728 NameLoc);
4729 }
4730
4731 case TemplateName::SubstTemplateTemplateParmPack: {
4732 SubstTemplateTemplateParmPackStorage *subst
4733 = Name.getAsSubstTemplateTemplateParmPack();
4734 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4735 NameLoc);
4736 }
4737 }
4738
4739 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004740}
4741
Jay Foad39c79802011-01-12 09:06:06 +00004742TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004743 switch (Name.getKind()) {
4744 case TemplateName::QualifiedTemplate:
4745 case TemplateName::Template: {
4746 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004747 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004748 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004749 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4750
4751 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004752 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004753 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004754
John McCalld9dfe3a2011-06-30 08:33:18 +00004755 case TemplateName::OverloadedTemplate:
4756 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004757
John McCalld9dfe3a2011-06-30 08:33:18 +00004758 case TemplateName::DependentTemplate: {
4759 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4760 assert(DTN && "Non-dependent template names must refer to template decls.");
4761 return DTN->CanonicalTemplateName;
4762 }
4763
4764 case TemplateName::SubstTemplateTemplateParm: {
4765 SubstTemplateTemplateParmStorage *subst
4766 = Name.getAsSubstTemplateTemplateParm();
4767 return getCanonicalTemplateName(subst->getReplacement());
4768 }
4769
4770 case TemplateName::SubstTemplateTemplateParmPack: {
4771 SubstTemplateTemplateParmPackStorage *subst
4772 = Name.getAsSubstTemplateTemplateParmPack();
4773 TemplateTemplateParmDecl *canonParameter
4774 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4775 TemplateArgument canonArgPack
4776 = getCanonicalTemplateArgument(subst->getArgumentPack());
4777 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4778 }
4779 }
4780
4781 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004782}
4783
Douglas Gregoradee3e32009-11-11 23:06:43 +00004784bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4785 X = getCanonicalTemplateName(X);
4786 Y = getCanonicalTemplateName(Y);
4787 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4788}
4789
Mike Stump11289f42009-09-09 15:08:12 +00004790TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004791ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004792 switch (Arg.getKind()) {
4793 case TemplateArgument::Null:
4794 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004795
Douglas Gregora8e02e72009-07-28 23:00:59 +00004796 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004797 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004798
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004799 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004800 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004801 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004802 }
Mike Stump11289f42009-09-09 15:08:12 +00004803
Eli Friedmanb826a002012-09-26 02:36:12 +00004804 case TemplateArgument::NullPtr:
4805 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4806 /*isNullPtr*/true);
4807
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004808 case TemplateArgument::Template:
4809 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004810
4811 case TemplateArgument::TemplateExpansion:
4812 return TemplateArgument(getCanonicalTemplateName(
4813 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004814 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004815
Douglas Gregora8e02e72009-07-28 23:00:59 +00004816 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004817 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004818
Douglas Gregora8e02e72009-07-28 23:00:59 +00004819 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004820 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004821
Douglas Gregora8e02e72009-07-28 23:00:59 +00004822 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004823 if (Arg.pack_size() == 0)
4824 return Arg;
4825
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004826 TemplateArgument *CanonArgs
4827 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004828 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004829 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004830 AEnd = Arg.pack_end();
4831 A != AEnd; (void)++A, ++Idx)
4832 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004833
Benjamin Kramercce63472015-08-05 09:40:22 +00004834 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004835 }
4836 }
4837
4838 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004839 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004840}
4841
Douglas Gregor333489b2009-03-27 23:10:48 +00004842NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004843ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004844 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004845 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004846
4847 switch (NNS->getKind()) {
4848 case NestedNameSpecifier::Identifier:
4849 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004850 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004851 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4852 NNS->getAsIdentifier());
4853
4854 case NestedNameSpecifier::Namespace:
4855 // A namespace is canonical; build a nested-name-specifier with
4856 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004857 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004858 NNS->getAsNamespace()->getOriginalNamespace());
4859
4860 case NestedNameSpecifier::NamespaceAlias:
4861 // A namespace is canonical; build a nested-name-specifier with
4862 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004863 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004864 NNS->getAsNamespaceAlias()->getNamespace()
4865 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004866
4867 case NestedNameSpecifier::TypeSpec:
4868 case NestedNameSpecifier::TypeSpecWithTemplate: {
4869 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004870
4871 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4872 // break it apart into its prefix and identifier, then reconsititute those
4873 // as the canonical nested-name-specifier. This is required to canonicalize
4874 // a dependent nested-name-specifier involving typedefs of dependent-name
4875 // types, e.g.,
4876 // typedef typename T::type T1;
4877 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004878 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4879 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004880 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004881
Eli Friedman5358a0a2012-03-03 04:09:56 +00004882 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4883 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4884 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004885 return NestedNameSpecifier::Create(*this, nullptr, false,
4886 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004887 }
4888
4889 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004890 case NestedNameSpecifier::Super:
4891 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004892 return NNS;
4893 }
4894
David Blaikie8a40f702012-01-17 06:56:22 +00004895 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004896}
4897
Jay Foad39c79802011-01-12 09:06:06 +00004898const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004899 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004900 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004901 // Handle the common positive case fast.
4902 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4903 return AT;
4904 }
Mike Stump11289f42009-09-09 15:08:12 +00004905
John McCall8ccfcb52009-09-24 19:53:00 +00004906 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004907 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004908 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004909
John McCall8ccfcb52009-09-24 19:53:00 +00004910 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004911 // implements C99 6.7.3p8: "If the specification of an array type includes
4912 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004913
Chris Lattner7adf0762008-08-04 07:31:14 +00004914 // If we get here, we either have type qualifiers on the type, or we have
4915 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004916 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004917
John McCall33ddac02011-01-19 10:06:00 +00004918 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004919 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004920
Chris Lattner7adf0762008-08-04 07:31:14 +00004921 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004922 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004923 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004924 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004925
Chris Lattner7adf0762008-08-04 07:31:14 +00004926 // Otherwise, we have an array and we have qualifiers on it. Push the
4927 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004928 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004929
Chris Lattner7adf0762008-08-04 07:31:14 +00004930 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4931 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4932 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004933 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004934 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4935 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4936 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004937 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004938
Mike Stump11289f42009-09-09 15:08:12 +00004939 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004940 = dyn_cast<DependentSizedArrayType>(ATy))
4941 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004942 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004943 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004944 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004945 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004946 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004947
Chris Lattner7adf0762008-08-04 07:31:14 +00004948 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004949 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004950 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004951 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004952 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004953 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004954}
4955
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004956QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004957 if (T->isArrayType() || T->isFunctionType())
4958 return getDecayedType(T);
4959 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004960}
4961
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004962QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004963 T = getVariableArrayDecayedType(T);
4964 T = getAdjustedParameterType(T);
4965 return T.getUnqualifiedType();
4966}
4967
David Majnemerd09a51c2015-03-03 01:50:05 +00004968QualType ASTContext::getExceptionObjectType(QualType T) const {
4969 // C++ [except.throw]p3:
4970 // A throw-expression initializes a temporary object, called the exception
4971 // object, the type of which is determined by removing any top-level
4972 // cv-qualifiers from the static type of the operand of throw and adjusting
4973 // the type from "array of T" or "function returning T" to "pointer to T"
4974 // or "pointer to function returning T", [...]
4975 T = getVariableArrayDecayedType(T);
4976 if (T->isArrayType() || T->isFunctionType())
4977 T = getDecayedType(T);
4978 return T.getUnqualifiedType();
4979}
4980
Chris Lattnera21ad802008-04-02 05:18:44 +00004981/// getArrayDecayedType - Return the properly qualified result of decaying the
4982/// specified array type to a pointer. This operation is non-trivial when
4983/// handling typedefs etc. The canonical type of "T" must be an array type,
4984/// this returns a pointer to a properly qualified element of the array.
4985///
4986/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004987QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004988 // Get the element type with 'getAsArrayType' so that we don't lose any
4989 // typedefs in the element type of the array. This also handles propagation
4990 // of type qualifiers from the array type into the element type if present
4991 // (C99 6.7.3p8).
4992 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4993 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004994
Chris Lattner7adf0762008-08-04 07:31:14 +00004995 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004996
4997 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00004998 QualType Result = getQualifiedType(PtrTy,
4999 PrettyArrayType->getIndexTypeQualifiers());
5000
5001 // int x[_Nullable] -> int * _Nullable
5002 if (auto Nullability = Ty->getNullability(*this)) {
5003 Result = const_cast<ASTContext *>(this)->getAttributedType(
5004 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5005 }
5006 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005007}
5008
John McCall33ddac02011-01-19 10:06:00 +00005009QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5010 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005011}
5012
John McCall33ddac02011-01-19 10:06:00 +00005013QualType ASTContext::getBaseElementType(QualType type) const {
5014 Qualifiers qs;
5015 while (true) {
5016 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005017 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005018 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005019
John McCall33ddac02011-01-19 10:06:00 +00005020 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005021 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005022 }
Mike Stump11289f42009-09-09 15:08:12 +00005023
John McCall33ddac02011-01-19 10:06:00 +00005024 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005025}
5026
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005027/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005028uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005029ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5030 uint64_t ElementCount = 1;
5031 do {
5032 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005033 CA = dyn_cast_or_null<ConstantArrayType>(
5034 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005035 } while (CA);
5036 return ElementCount;
5037}
5038
Steve Naroff0af91202007-04-27 21:51:21 +00005039/// getFloatingRank - Return a relative rank for floating point types.
5040/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005041static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005042 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005043 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005044
John McCall9dd450b2009-09-21 23:43:11 +00005045 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5046 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005047 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005048 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005049 case BuiltinType::Float: return FloatRank;
5050 case BuiltinType::Double: return DoubleRank;
5051 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005052 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005053 }
5054}
5055
Mike Stump11289f42009-09-09 15:08:12 +00005056/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5057/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005058/// 'typeDomain' is a real floating point or complex type.
5059/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005060QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5061 QualType Domain) const {
5062 FloatingRank EltRank = getFloatingRank(Size);
5063 if (Domain->isComplexType()) {
5064 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00005065 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005066 case FloatRank: return FloatComplexTy;
5067 case DoubleRank: return DoubleComplexTy;
5068 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005069 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005070 }
Steve Naroff0af91202007-04-27 21:51:21 +00005071 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005072
5073 assert(Domain->isRealFloatingType() && "Unknown domain!");
5074 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00005075 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005076 case FloatRank: return FloatTy;
5077 case DoubleRank: return DoubleTy;
5078 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005079 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005080 }
David Blaikief47fa302012-01-17 02:30:50 +00005081 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005082}
5083
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005084/// getFloatingTypeOrder - Compare the rank of the two specified floating
5085/// point types, ignoring the domain of the type (i.e. 'double' ==
5086/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005087/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005088int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005089 FloatingRank LHSR = getFloatingRank(LHS);
5090 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005091
Chris Lattnerb90739d2008-04-06 23:38:49 +00005092 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005093 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005094 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005095 return 1;
5096 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005097}
5098
Chris Lattner76a00cf2008-04-06 22:59:24 +00005099/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5100/// routine will assert if passed a built-in type that isn't an integer or enum,
5101/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005102unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005103 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005104
Chris Lattner76a00cf2008-04-06 22:59:24 +00005105 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005106 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005107 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005108 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005109 case BuiltinType::Char_S:
5110 case BuiltinType::Char_U:
5111 case BuiltinType::SChar:
5112 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005113 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005114 case BuiltinType::Short:
5115 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005116 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005117 case BuiltinType::Int:
5118 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005119 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005120 case BuiltinType::Long:
5121 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005122 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005123 case BuiltinType::LongLong:
5124 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005125 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005126 case BuiltinType::Int128:
5127 case BuiltinType::UInt128:
5128 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005129 }
5130}
5131
Eli Friedman629ffb92009-08-20 04:21:42 +00005132/// \brief Whether this is a promotable bitfield reference according
5133/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5134///
5135/// \returns the type this bit-field will promote to, or NULL if no
5136/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005137QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005138 if (E->isTypeDependent() || E->isValueDependent())
5139 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005140
5141 // FIXME: We should not do this unless E->refersToBitField() is true. This
5142 // matters in C where getSourceBitField() will find bit-fields for various
5143 // cases where the source expression is not a bit-field designator.
5144
John McCalld25db7e2013-05-06 21:39:12 +00005145 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005146 if (!Field)
5147 return QualType();
5148
5149 QualType FT = Field->getType();
5150
Richard Smithcaf33902011-10-10 18:28:20 +00005151 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005152 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005153 // C++ [conv.prom]p5:
5154 // A prvalue for an integral bit-field can be converted to a prvalue of type
5155 // int if int can represent all the values of the bit-field; otherwise, it
5156 // can be converted to unsigned int if unsigned int can represent all the
5157 // values of the bit-field. If the bit-field is larger yet, no integral
5158 // promotion applies to it.
5159 // C11 6.3.1.1/2:
5160 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5161 // If an int can represent all values of the original type (as restricted by
5162 // the width, for a bit-field), the value is converted to an int; otherwise,
5163 // it is converted to an unsigned int.
5164 //
5165 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5166 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005167 if (BitWidth < IntSize)
5168 return IntTy;
5169
5170 if (BitWidth == IntSize)
5171 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5172
5173 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005174 // like the base type. GCC has some weird bugs in this area that we
5175 // deliberately do not follow (GCC follows a pre-standard resolution to
5176 // C's DR315 which treats bit-width as being part of the type, and this leaks
5177 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005178 return QualType();
5179}
5180
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005181/// getPromotedIntegerType - Returns the type that Promotable will
5182/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5183/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005184QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005185 assert(!Promotable.isNull());
5186 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005187 if (const EnumType *ET = Promotable->getAs<EnumType>())
5188 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005189
5190 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5191 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5192 // (3.9.1) can be converted to a prvalue of the first of the following
5193 // types that can represent all the values of its underlying type:
5194 // int, unsigned int, long int, unsigned long int, long long int, or
5195 // unsigned long long int [...]
5196 // FIXME: Is there some better way to compute this?
5197 if (BT->getKind() == BuiltinType::WChar_S ||
5198 BT->getKind() == BuiltinType::WChar_U ||
5199 BT->getKind() == BuiltinType::Char16 ||
5200 BT->getKind() == BuiltinType::Char32) {
5201 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5202 uint64_t FromSize = getTypeSize(BT);
5203 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5204 LongLongTy, UnsignedLongLongTy };
5205 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5206 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5207 if (FromSize < ToSize ||
5208 (FromSize == ToSize &&
5209 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5210 return PromoteTypes[Idx];
5211 }
5212 llvm_unreachable("char type should fit into long long");
5213 }
5214 }
5215
5216 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005217 if (Promotable->isSignedIntegerType())
5218 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005219 uint64_t PromotableSize = getIntWidth(Promotable);
5220 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005221 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5222 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5223}
5224
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005225/// \brief Recurses in pointer/array types until it finds an objc retainable
5226/// type and returns its ownership.
5227Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5228 while (!T.isNull()) {
5229 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5230 return T.getObjCLifetime();
5231 if (T->isArrayType())
5232 T = getBaseElementType(T);
5233 else if (const PointerType *PT = T->getAs<PointerType>())
5234 T = PT->getPointeeType();
5235 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005236 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005237 else
5238 break;
5239 }
5240
5241 return Qualifiers::OCL_None;
5242}
5243
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005244static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5245 // Incomplete enum types are not treated as integer types.
5246 // FIXME: In C++, enum types are never integer types.
5247 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5248 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005249 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005250}
5251
Mike Stump11289f42009-09-09 15:08:12 +00005252/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005253/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005254/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005255int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005256 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5257 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005258
5259 // Unwrap enums to their underlying type.
5260 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5261 LHSC = getIntegerTypeForEnum(ET);
5262 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5263 RHSC = getIntegerTypeForEnum(ET);
5264
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005265 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005266
Chris Lattner76a00cf2008-04-06 22:59:24 +00005267 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5268 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005269
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005270 unsigned LHSRank = getIntegerRank(LHSC);
5271 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005272
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005273 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5274 if (LHSRank == RHSRank) return 0;
5275 return LHSRank > RHSRank ? 1 : -1;
5276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005278 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5279 if (LHSUnsigned) {
5280 // If the unsigned [LHS] type is larger, return it.
5281 if (LHSRank >= RHSRank)
5282 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005283
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005284 // If the signed type can represent all values of the unsigned type, it
5285 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005286 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005287 return -1;
5288 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005289
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005290 // If the unsigned [RHS] type is larger, return it.
5291 if (RHSRank >= LHSRank)
5292 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005293
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005294 // If the signed type can represent all values of the unsigned type, it
5295 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005296 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005297 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005298}
Anders Carlsson98f07902007-08-17 05:31:46 +00005299
Ben Langmuirf5416742016-02-04 00:55:24 +00005300TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005301 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005302 assert(!CFConstantStringTagDecl &&
5303 "tag and typedef should be initialized together");
5304 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5305 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005306
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005307 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005308 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005309
Anders Carlsson98f07902007-08-17 05:31:46 +00005310 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005311 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005312 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005313 // int flags;
5314 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005315 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005316 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005317 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005318 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005319 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005320 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005321 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005322
Anders Carlsson98f07902007-08-17 05:31:46 +00005323 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005324 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005325 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005326 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005327 SourceLocation(),
5328 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005329 FieldTypes[i], /*TInfo=*/nullptr,
5330 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005331 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005332 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005333 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005334 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005335 }
5336
Ben Langmuirf5416742016-02-04 00:55:24 +00005337 CFConstantStringTagDecl->completeDefinition();
5338 // This type is designed to be compatible with NSConstantString, but cannot
5339 // use the same name, since NSConstantString is an interface.
5340 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5341 CFConstantStringTypeDecl =
5342 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005343 }
Mike Stump11289f42009-09-09 15:08:12 +00005344
Quentin Colombet043406b2016-02-03 22:41:00 +00005345 return CFConstantStringTypeDecl;
5346}
5347
Ben Langmuirf5416742016-02-04 00:55:24 +00005348RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5349 if (!CFConstantStringTagDecl)
5350 getCFConstantStringDecl(); // Build the tag and the typedef.
5351 return CFConstantStringTagDecl;
5352}
5353
Quentin Colombet043406b2016-02-03 22:41:00 +00005354// getCFConstantStringType - Return the type used for constant CFStrings.
5355QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005356 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005357}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005358
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005359QualType ASTContext::getObjCSuperType() const {
5360 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005361 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005362 TUDecl->addDecl(ObjCSuperTypeDecl);
5363 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5364 }
5365 return ObjCSuperType;
5366}
5367
Douglas Gregor512b0772009-04-23 22:29:11 +00005368void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005369 const TypedefType *TD = T->getAs<TypedefType>();
5370 assert(TD && "Invalid CFConstantStringType");
5371 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5372 auto TagType =
5373 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5374 assert(TagType && "Invalid CFConstantStringType");
5375 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005376}
5377
Jay Foad39c79802011-01-12 09:06:06 +00005378QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005379 if (BlockDescriptorType)
5380 return getTagDeclType(BlockDescriptorType);
5381
Alp Toker2dea15b2013-12-17 01:22:38 +00005382 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005383 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005384 RD = buildImplicitRecord("__block_descriptor");
5385 RD->startDefinition();
5386
Mike Stumpd0153282009-10-20 02:12:22 +00005387 QualType FieldTypes[] = {
5388 UnsignedLongTy,
5389 UnsignedLongTy,
5390 };
5391
Craig Topperd6d31ac2013-07-15 08:24:27 +00005392 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005393 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005394 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005395 };
5396
5397 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005398 FieldDecl *Field = FieldDecl::Create(
5399 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005400 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5401 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005402 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005403 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005404 }
5405
Alp Toker2dea15b2013-12-17 01:22:38 +00005406 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005407
Alp Toker2dea15b2013-12-17 01:22:38 +00005408 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005409
5410 return getTagDeclType(BlockDescriptorType);
5411}
5412
Jay Foad39c79802011-01-12 09:06:06 +00005413QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005414 if (BlockDescriptorExtendedType)
5415 return getTagDeclType(BlockDescriptorExtendedType);
5416
Alp Toker2dea15b2013-12-17 01:22:38 +00005417 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005418 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005419 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5420 RD->startDefinition();
5421
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005422 QualType FieldTypes[] = {
5423 UnsignedLongTy,
5424 UnsignedLongTy,
5425 getPointerType(VoidPtrTy),
5426 getPointerType(VoidPtrTy)
5427 };
5428
Craig Topperd6d31ac2013-07-15 08:24:27 +00005429 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005430 "reserved",
5431 "Size",
5432 "CopyFuncPtr",
5433 "DestroyFuncPtr"
5434 };
5435
5436 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005437 FieldDecl *Field = FieldDecl::Create(
5438 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005439 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5440 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005441 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005442 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005443 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005444 }
5445
Alp Toker2dea15b2013-12-17 01:22:38 +00005446 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005447
Alp Toker2dea15b2013-12-17 01:22:38 +00005448 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005449 return getTagDeclType(BlockDescriptorExtendedType);
5450}
5451
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005452/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5453/// requires copy/dispose. Note that this must match the logic
5454/// in buildByrefHelpers.
5455bool ASTContext::BlockRequiresCopying(QualType Ty,
5456 const VarDecl *D) {
5457 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5458 const Expr *copyExpr = getBlockVarCopyInits(D);
5459 if (!copyExpr && record->hasTrivialDestructor()) return false;
5460
Mike Stump94967902009-10-21 18:16:27 +00005461 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005462 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005463
5464 if (!Ty->isObjCRetainableType()) return false;
5465
5466 Qualifiers qs = Ty.getQualifiers();
5467
5468 // If we have lifetime, that dominates.
5469 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005470 switch (lifetime) {
5471 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5472
5473 // These are just bits as far as the runtime is concerned.
5474 case Qualifiers::OCL_ExplicitNone:
5475 case Qualifiers::OCL_Autoreleasing:
5476 return false;
5477
5478 // Tell the runtime that this is ARC __weak, called by the
5479 // byref routines.
5480 case Qualifiers::OCL_Weak:
5481 // ARC __strong __block variables need to be retained.
5482 case Qualifiers::OCL_Strong:
5483 return true;
5484 }
5485 llvm_unreachable("fell out of lifetime switch!");
5486 }
5487 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5488 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005489}
5490
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005491bool ASTContext::getByrefLifetime(QualType Ty,
5492 Qualifiers::ObjCLifetime &LifeTime,
5493 bool &HasByrefExtendedLayout) const {
5494
5495 if (!getLangOpts().ObjC1 ||
5496 getLangOpts().getGC() != LangOptions::NonGC)
5497 return false;
5498
5499 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005500 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005501 HasByrefExtendedLayout = true;
5502 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005503 } else if ((LifeTime = Ty.getObjCLifetime())) {
5504 // Honor the ARC qualifiers.
5505 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5506 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005507 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005508 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005509 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005510 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005511 return true;
5512}
5513
Douglas Gregorbab8a962011-09-08 01:46:34 +00005514TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5515 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005516 ObjCInstanceTypeDecl =
5517 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005518 return ObjCInstanceTypeDecl;
5519}
5520
Anders Carlsson18acd442007-10-29 06:33:42 +00005521// This returns true if a type has been typedefed to BOOL:
5522// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005523static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005524 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005525 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5526 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005527
Anders Carlssond8499822007-10-29 05:01:08 +00005528 return false;
5529}
5530
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005531/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005532/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005533CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005534 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5535 return CharUnits::Zero();
5536
Ken Dyck40775002010-01-11 17:06:35 +00005537 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005538
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005539 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005540 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005541 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005542 // Treat arrays as pointers, since that's how they're passed in.
5543 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005544 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005545 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005546}
5547
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005548bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005549 return getTargetInfo().getCXXABI().isMicrosoft() &&
5550 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005551 VD->getType()->isIntegralOrEnumerationType() &&
5552 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005553}
5554
Richard Smithd9b90092016-07-02 01:32:16 +00005555ASTContext::InlineVariableDefinitionKind
5556ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5557 if (!VD->isInline())
5558 return InlineVariableDefinitionKind::None;
5559
5560 // In almost all cases, it's a weak definition.
5561 auto *First = VD->getFirstDecl();
5562 if (!First->isConstexpr() || First->isInlineSpecified() ||
5563 !VD->isStaticDataMember())
5564 return InlineVariableDefinitionKind::Weak;
5565
5566 // If there's a file-context declaration in this translation unit, it's a
5567 // non-discardable definition.
5568 for (auto *D : VD->redecls())
5569 if (D->getLexicalDeclContext()->isFileContext())
5570 return InlineVariableDefinitionKind::Strong;
5571
5572 // If we've not seen one yet, we don't know.
5573 return InlineVariableDefinitionKind::WeakUnknown;
5574}
5575
Ken Dyck40775002010-01-11 17:06:35 +00005576static inline
5577std::string charUnitsToString(const CharUnits &CU) {
5578 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005579}
5580
John McCall351762c2011-02-07 10:33:21 +00005581/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005582/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005583std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5584 std::string S;
5585
David Chisnall950a9512009-11-17 19:33:30 +00005586 const BlockDecl *Decl = Expr->getBlockDecl();
5587 QualType BlockTy =
5588 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5589 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005590 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005591 getObjCEncodingForMethodParameter(
5592 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5593 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005594 else
Alp Toker314cc812014-01-25 16:55:45 +00005595 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005596 // Compute size of all parameters.
5597 // Start with computing size of a pointer in number of bytes.
5598 // FIXME: There might(should) be a better way of doing this computation!
5599 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005600 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5601 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005602 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005603 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005604 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005605 if (sz.isZero())
5606 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005607 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005608 ParmOffset += sz;
5609 }
5610 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005611 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005612 // Block pointer and offset.
5613 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005614
5615 // Argument types.
5616 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005617 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005618 QualType PType = PVDecl->getOriginalType();
5619 if (const ArrayType *AT =
5620 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5621 // Use array's original type only if it has known number of
5622 // elements.
5623 if (!isa<ConstantArrayType>(AT))
5624 PType = PVDecl->getType();
5625 } else if (PType->isFunctionType())
5626 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005627 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005628 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5629 S, true /*Extended*/);
5630 else
5631 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005632 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005633 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005634 }
John McCall351762c2011-02-07 10:33:21 +00005635
5636 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005637}
5638
John McCall843dfcc2016-11-29 21:57:00 +00005639std::string
5640ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5641 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005642 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005643 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005644 CharUnits ParmOffset;
5645 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005646 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005647 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005648 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005649 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005650 continue;
5651
John McCall843dfcc2016-11-29 21:57:00 +00005652 assert(sz.isPositive() &&
5653 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005654 ParmOffset += sz;
5655 }
5656 S += charUnitsToString(ParmOffset);
5657 ParmOffset = CharUnits::Zero();
5658
5659 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005660 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005661 QualType PType = PVDecl->getOriginalType();
5662 if (const ArrayType *AT =
5663 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5664 // Use array's original type only if it has known number of
5665 // elements.
5666 if (!isa<ConstantArrayType>(AT))
5667 PType = PVDecl->getType();
5668 } else if (PType->isFunctionType())
5669 PType = PVDecl->getType();
5670 getObjCEncodingForType(PType, S);
5671 S += charUnitsToString(ParmOffset);
5672 ParmOffset += getObjCEncodingTypeSize(PType);
5673 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005674
John McCall843dfcc2016-11-29 21:57:00 +00005675 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005676}
5677
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005678/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5679/// method parameter or return type. If Extended, include class names and
5680/// block object types.
5681void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5682 QualType T, std::string& S,
5683 bool Extended) const {
5684 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5685 getObjCEncodingForTypeQualifier(QT, S);
5686 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005687 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005688 true /*OutermostType*/,
5689 false /*EncodingProperty*/,
5690 false /*StructField*/,
5691 Extended /*EncodeBlockParameters*/,
5692 Extended /*EncodeClassNames*/);
5693}
5694
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005695/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005696/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005697std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5698 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005699 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005700 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005701 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005702 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5703 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005704 // Compute size of all parameters.
5705 // Start with computing size of a pointer in number of bytes.
5706 // FIXME: There might(should) be a better way of doing this computation!
5707 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005708 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005709 // The first two arguments (self and _cmd) are pointers; account for
5710 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005711 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005712 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005713 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005714 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005715 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005716 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005717 continue;
5718
Ken Dyck40775002010-01-11 17:06:35 +00005719 assert (sz.isPositive() &&
5720 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005721 ParmOffset += sz;
5722 }
Ken Dyck40775002010-01-11 17:06:35 +00005723 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005724 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005725 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005726
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005727 // Argument types.
5728 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005729 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005730 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005731 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005732 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005733 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005734 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5735 // Use array's original type only if it has known number of
5736 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005737 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005738 PType = PVDecl->getType();
5739 } else if (PType->isFunctionType())
5740 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005741 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5742 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005743 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005744 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005745 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005746
John McCall843dfcc2016-11-29 21:57:00 +00005747 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005748}
5749
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005750ObjCPropertyImplDecl *
5751ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5752 const ObjCPropertyDecl *PD,
5753 const Decl *Container) const {
5754 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005755 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005756 if (const ObjCCategoryImplDecl *CID =
5757 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005758 for (auto *PID : CID->property_impls())
5759 if (PID->getPropertyDecl() == PD)
5760 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005761 } else {
5762 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5763 for (auto *PID : OID->property_impls())
5764 if (PID->getPropertyDecl() == PD)
5765 return PID;
5766 }
5767 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005768}
5769
Daniel Dunbar4932b362008-08-28 04:38:10 +00005770/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005771/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005772/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5773/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005774/// Property attributes are stored as a comma-delimited C string. The simple
5775/// attributes readonly and bycopy are encoded as single characters. The
5776/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5777/// encoded as single characters, followed by an identifier. Property types
5778/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005779/// these attributes are defined by the following enumeration:
5780/// @code
5781/// enum PropertyAttributes {
5782/// kPropertyReadOnly = 'R', // property is read-only.
5783/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5784/// kPropertyByref = '&', // property is a reference to the value last assigned
5785/// kPropertyDynamic = 'D', // property is dynamic
5786/// kPropertyGetter = 'G', // followed by getter selector name
5787/// kPropertySetter = 'S', // followed by setter selector name
5788/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005789/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005790/// kPropertyWeak = 'W' // 'weak' property
5791/// kPropertyStrong = 'P' // property GC'able
5792/// kPropertyNonAtomic = 'N' // property non-atomic
5793/// };
5794/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005795std::string
5796ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5797 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005798 // Collect information from the property implementation decl(s).
5799 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005800 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005801
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005802 if (ObjCPropertyImplDecl *PropertyImpDecl =
5803 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5804 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5805 Dynamic = true;
5806 else
5807 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005808 }
5809
5810 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005811 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005812
5813 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005814 // GCC has some special rules regarding encoding of properties which
5815 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005816 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005817
5818 if (PD->isReadOnly()) {
5819 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005820 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5821 S += ",C";
5822 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5823 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005824 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5825 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005826 } else {
5827 switch (PD->getSetterKind()) {
5828 case ObjCPropertyDecl::Assign: break;
5829 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005830 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005831 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005832 }
5833 }
5834
5835 // It really isn't clear at all what this means, since properties
5836 // are "dynamic by default".
5837 if (Dynamic)
5838 S += ",D";
5839
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005840 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5841 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005842
Daniel Dunbar4932b362008-08-28 04:38:10 +00005843 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5844 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005845 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005846 }
5847
5848 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5849 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005850 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005851 }
5852
5853 if (SynthesizePID) {
5854 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5855 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005856 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005857 }
5858
5859 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005860 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005861}
5862
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005863/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005864/// Another legacy compatibility encoding: 32-bit longs are encoded as
5865/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005866/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5867///
5868void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005869 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005870 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005871 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005872 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005873 else
Jay Foad39c79802011-01-12 09:06:06 +00005874 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005875 PointeeTy = IntTy;
5876 }
5877 }
5878}
5879
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005880void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005881 const FieldDecl *Field,
5882 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005883 // We follow the behavior of gcc, expanding structures which are
5884 // directly pointed to, and expanding embedded structures. Note that
5885 // these rules are sufficient to prevent recursive encoding of the
5886 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005887 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005888 true /* outermost type */, false, false,
5889 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005890}
5891
Joe Groff98ac7d22014-07-07 22:25:15 +00005892void ASTContext::getObjCEncodingForPropertyType(QualType T,
5893 std::string& S) const {
5894 // Encode result type.
5895 // GCC has some special rules regarding encoding of properties which
5896 // closely resembles encoding of ivars.
5897 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5898 true /* outermost type */,
5899 true /* encoding property */);
5900}
5901
John McCall393a78d2012-12-20 02:45:14 +00005902static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5903 BuiltinType::Kind kind) {
5904 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005905 case BuiltinType::Void: return 'v';
5906 case BuiltinType::Bool: return 'B';
5907 case BuiltinType::Char_U:
5908 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005909 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005910 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005911 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005912 case BuiltinType::UInt: return 'I';
5913 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005914 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005915 case BuiltinType::UInt128: return 'T';
5916 case BuiltinType::ULongLong: return 'Q';
5917 case BuiltinType::Char_S:
5918 case BuiltinType::SChar: return 'c';
5919 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005920 case BuiltinType::WChar_S:
5921 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005922 case BuiltinType::Int: return 'i';
5923 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005924 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005925 case BuiltinType::LongLong: return 'q';
5926 case BuiltinType::Int128: return 't';
5927 case BuiltinType::Float: return 'f';
5928 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005929 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005930 case BuiltinType::NullPtr: return '*'; // like char*
5931
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005932 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005933 case BuiltinType::Half:
5934 // FIXME: potentially need @encodes for these!
5935 return ' ';
5936
5937 case BuiltinType::ObjCId:
5938 case BuiltinType::ObjCClass:
5939 case BuiltinType::ObjCSel:
5940 llvm_unreachable("@encoding ObjC primitive type");
5941
5942 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005943#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5944 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005945#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005946 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005947 case BuiltinType::OCLClkEvent:
5948 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005949 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005950 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005951 case BuiltinType::Dependent:
5952#define BUILTIN_TYPE(KIND, ID)
5953#define PLACEHOLDER_TYPE(KIND, ID) \
5954 case BuiltinType::KIND:
5955#include "clang/AST/BuiltinTypes.def"
5956 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005957 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005958 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005959}
5960
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005961static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5962 EnumDecl *Enum = ET->getDecl();
5963
5964 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5965 if (!Enum->isFixed())
5966 return 'i';
5967
5968 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005969 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5970 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005971}
5972
Jay Foad39c79802011-01-12 09:06:06 +00005973static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005974 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005975 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005976 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005977 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5978 // The GNU runtime requires more information; bitfields are encoded as b,
5979 // then the offset (in bits) of the first element, then the type of the
5980 // bitfield, then the size in bits. For example, in this structure:
5981 //
5982 // struct
5983 // {
5984 // int integer;
5985 // int flags:2;
5986 // };
5987 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5988 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5989 // information is not especially sensible, but we're stuck with it for
5990 // compatibility with GCC, although providing it breaks anything that
5991 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005992 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005993 const RecordDecl *RD = FD->getParent();
5994 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005995 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005996 if (const EnumType *ET = T->getAs<EnumType>())
5997 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005998 else {
5999 const BuiltinType *BT = T->castAs<BuiltinType>();
6000 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6001 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006002 }
Richard Smithcaf33902011-10-10 18:28:20 +00006003 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006004}
6005
Daniel Dunbar07d07852009-10-18 21:17:35 +00006006// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006007void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6008 bool ExpandPointedToStructures,
6009 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006010 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006011 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006012 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006013 bool StructField,
6014 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006015 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006016 bool EncodePointerToObjCTypedef,
6017 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006018 CanQualType CT = getCanonicalType(T);
6019 switch (CT->getTypeClass()) {
6020 case Type::Builtin:
6021 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006022 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006023 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006024 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6025 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6026 else
6027 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006028 return;
Mike Stump11289f42009-09-09 15:08:12 +00006029
John McCall393a78d2012-12-20 02:45:14 +00006030 case Type::Complex: {
6031 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006032 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006033 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006034 return;
6035 }
John McCall393a78d2012-12-20 02:45:14 +00006036
6037 case Type::Atomic: {
6038 const AtomicType *AT = T->castAs<AtomicType>();
6039 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006040 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006041 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006042 }
John McCall393a78d2012-12-20 02:45:14 +00006043
6044 // encoding for pointer or reference types.
6045 case Type::Pointer:
6046 case Type::LValueReference:
6047 case Type::RValueReference: {
6048 QualType PointeeTy;
6049 if (isa<PointerType>(CT)) {
6050 const PointerType *PT = T->castAs<PointerType>();
6051 if (PT->isObjCSelType()) {
6052 S += ':';
6053 return;
6054 }
6055 PointeeTy = PT->getPointeeType();
6056 } else {
6057 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6058 }
6059
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006060 bool isReadOnly = false;
6061 // For historical/compatibility reasons, the read-only qualifier of the
6062 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6063 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006064 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006065 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006066 if (OutermostType && T.isConstQualified()) {
6067 isReadOnly = true;
6068 S += 'r';
6069 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006070 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006071 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006072 while (P->getAs<PointerType>())
6073 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006074 if (P.isConstQualified()) {
6075 isReadOnly = true;
6076 S += 'r';
6077 }
6078 }
6079 if (isReadOnly) {
6080 // Another legacy compatibility encoding. Some ObjC qualifier and type
6081 // combinations need to be rearranged.
6082 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006083 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006084 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006085 }
Mike Stump11289f42009-09-09 15:08:12 +00006086
Anders Carlssond8499822007-10-29 05:01:08 +00006087 if (PointeeTy->isCharType()) {
6088 // char pointer types should be encoded as '*' unless it is a
6089 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006090 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006091 S += '*';
6092 return;
6093 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006094 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006095 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6096 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6097 S += '#';
6098 return;
6099 }
6100 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6101 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6102 S += '@';
6103 return;
6104 }
6105 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006106 }
Anders Carlssond8499822007-10-29 05:01:08 +00006107 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006108 getLegacyIntegralTypeEncoding(PointeeTy);
6109
Mike Stump11289f42009-09-09 15:08:12 +00006110 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006111 nullptr, false, false, false, false, false, false,
6112 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006113 return;
6114 }
John McCall393a78d2012-12-20 02:45:14 +00006115
6116 case Type::ConstantArray:
6117 case Type::IncompleteArray:
6118 case Type::VariableArray: {
6119 const ArrayType *AT = cast<ArrayType>(CT);
6120
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006121 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006122 // Incomplete arrays are encoded as a pointer to the array element.
6123 S += '^';
6124
Mike Stump11289f42009-09-09 15:08:12 +00006125 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006126 false, ExpandStructures, FD);
6127 } else {
6128 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006129
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006130 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6131 S += llvm::utostr(CAT->getSize().getZExtValue());
6132 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006133 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006134 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6135 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006136 S += '0';
6137 }
Mike Stump11289f42009-09-09 15:08:12 +00006138
6139 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006140 false, ExpandStructures, FD,
6141 false, false, false, false, false, false,
6142 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006143 S += ']';
6144 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006145 return;
6146 }
Mike Stump11289f42009-09-09 15:08:12 +00006147
John McCall393a78d2012-12-20 02:45:14 +00006148 case Type::FunctionNoProto:
6149 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006150 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006151 return;
Mike Stump11289f42009-09-09 15:08:12 +00006152
John McCall393a78d2012-12-20 02:45:14 +00006153 case Type::Record: {
6154 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006155 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006156 // Anonymous structures print as '?'
6157 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6158 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006159 if (ClassTemplateSpecializationDecl *Spec
6160 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6161 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006162 llvm::raw_string_ostream OS(S);
6163 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006164 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006165 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006166 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006167 } else {
6168 S += '?';
6169 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006170 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006171 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006172 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006173 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006174 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006175 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006176 if (FD) {
6177 S += '"';
6178 S += Field->getNameAsString();
6179 S += '"';
6180 }
Mike Stump11289f42009-09-09 15:08:12 +00006181
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006182 // Special case bit-fields.
6183 if (Field->isBitField()) {
6184 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006185 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006186 } else {
6187 QualType qt = Field->getType();
6188 getLegacyIntegralTypeEncoding(qt);
6189 getObjCEncodingForTypeImpl(qt, S, false, true,
6190 FD, /*OutermostType*/false,
6191 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006192 /*StructField*/true,
6193 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006194 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006195 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006196 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006197 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006198 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006199 return;
6200 }
Mike Stump11289f42009-09-09 15:08:12 +00006201
John McCall393a78d2012-12-20 02:45:14 +00006202 case Type::BlockPointer: {
6203 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006204 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006205 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006206 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006207
6208 S += '<';
6209 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006210 getObjCEncodingForTypeImpl(
6211 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6212 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006213 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6214 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006215 // Block self
6216 S += "@?";
6217 // Block parameters
6218 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006219 for (const auto &I : FPT->param_types())
6220 getObjCEncodingForTypeImpl(
6221 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6222 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006223 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6224 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006225 }
6226 S += '>';
6227 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006228 return;
6229 }
Mike Stump11289f42009-09-09 15:08:12 +00006230
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006231 case Type::ObjCObject: {
6232 // hack to match legacy encoding of *id and *Class
6233 QualType Ty = getObjCObjectPointerType(CT);
6234 if (Ty->isObjCIdType()) {
6235 S += "{objc_object=}";
6236 return;
6237 }
6238 else if (Ty->isObjCClassType()) {
6239 S += "{objc_class=}";
6240 return;
6241 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006242 // TODO: Double check to make sure this intentially falls through.
6243 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006244 }
6245
John McCall393a78d2012-12-20 02:45:14 +00006246 case Type::ObjCInterface: {
6247 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006248 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006249 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006250 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006251 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006252 if (ExpandStructures) {
6253 S += '=';
6254 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6255 DeepCollectObjCIvars(OI, true, Ivars);
6256 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6257 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6258 if (Field->isBitField())
6259 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6260 else
6261 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6262 false, false, false, false, false,
6263 EncodePointerToObjCTypedef,
6264 NotEncodedT);
6265 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006266 }
6267 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006268 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006269 }
Mike Stump11289f42009-09-09 15:08:12 +00006270
John McCall393a78d2012-12-20 02:45:14 +00006271 case Type::ObjCObjectPointer: {
6272 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006273 if (OPT->isObjCIdType()) {
6274 S += '@';
6275 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006276 }
Mike Stump11289f42009-09-09 15:08:12 +00006277
Steve Narofff0c86112009-10-28 22:03:49 +00006278 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6279 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6280 // Since this is a binary compatibility issue, need to consult with runtime
6281 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006282 S += '#';
6283 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006284 }
Mike Stump11289f42009-09-09 15:08:12 +00006285
Chris Lattnere7cabb92009-07-13 00:10:46 +00006286 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006287 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006288 ExpandPointedToStructures,
6289 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006290 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006291 // Note that we do extended encoding of protocol qualifer list
6292 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006293 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006294 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006295 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006296 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006297 S += '>';
6298 }
6299 S += '"';
6300 }
6301 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006302 }
Mike Stump11289f42009-09-09 15:08:12 +00006303
Chris Lattnere7cabb92009-07-13 00:10:46 +00006304 QualType PointeeTy = OPT->getPointeeType();
6305 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006306 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6307 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006308 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006309 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006310 // {...};
6311 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006312 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006313 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006314 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6315 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6316 DeepCollectObjCIvars(OI, true, Ivars);
6317 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6318 if (cast<FieldDecl>(Ivars[i]) == FD) {
6319 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006320 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006321 S += '}';
6322 return;
6323 }
6324 }
6325 }
Mike Stump11289f42009-09-09 15:08:12 +00006326 getObjCEncodingForTypeImpl(PointeeTy, S,
6327 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006328 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006329 false, false, false, false, false,
6330 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006331 return;
6332 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006333
6334 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006335 if (OPT->getInterfaceDecl() &&
6336 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006337 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006338 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006339 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006340 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006341 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006342 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006343 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006344 S += '"';
6345 }
6346 return;
6347 }
Mike Stump11289f42009-09-09 15:08:12 +00006348
John McCalla9e6e8d2010-05-17 23:56:34 +00006349 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006350 // FIXME: we shoul do better than that. 'M' is available.
6351 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006352 // This matches gcc's encoding, even though technically it is insufficient.
6353 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006354 case Type::Vector:
6355 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006356 // Until we have a coherent encoding of these three types, issue warning.
6357 { if (NotEncodedT)
6358 *NotEncodedT = T;
6359 return;
6360 }
6361
6362 // We could see an undeduced auto type here during error recovery.
6363 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006364 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006365 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006366 return;
6367
Xiuli Pan9c14e282016-01-09 12:53:17 +00006368 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006369#define ABSTRACT_TYPE(KIND, BASE)
6370#define TYPE(KIND, BASE)
6371#define DEPENDENT_TYPE(KIND, BASE) \
6372 case Type::KIND:
6373#define NON_CANONICAL_TYPE(KIND, BASE) \
6374 case Type::KIND:
6375#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6376 case Type::KIND:
6377#include "clang/AST/TypeNodes.def"
6378 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006379 }
John McCall393a78d2012-12-20 02:45:14 +00006380 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006381}
6382
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006383void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6384 std::string &S,
6385 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006386 bool includeVBases,
6387 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006388 assert(RDecl && "Expected non-null RecordDecl");
6389 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006390 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006391 return;
6392
6393 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6394 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6395 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6396
6397 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006398 for (const auto &BI : CXXRec->bases()) {
6399 if (!BI.isVirtual()) {
6400 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006401 if (base->isEmpty())
6402 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006403 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006404 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6405 std::make_pair(offs, base));
6406 }
6407 }
6408 }
6409
6410 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006411 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006412 uint64_t offs = layout.getFieldOffset(i);
6413 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006414 std::make_pair(offs, Field));
6415 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006416 }
6417
6418 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006419 for (const auto &BI : CXXRec->vbases()) {
6420 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006421 if (base->isEmpty())
6422 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006423 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006424 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6425 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006426 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6427 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006428 }
6429 }
6430
6431 CharUnits size;
6432 if (CXXRec) {
6433 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6434 } else {
6435 size = layout.getSize();
6436 }
6437
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006438#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006439 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006440#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006441 std::multimap<uint64_t, NamedDecl *>::iterator
6442 CurLayObj = FieldOrBaseOffsets.begin();
6443
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006444 if (CXXRec && CXXRec->isDynamicClass() &&
6445 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006446 if (FD) {
6447 S += "\"_vptr$";
6448 std::string recname = CXXRec->getNameAsString();
6449 if (recname.empty()) recname = "?";
6450 S += recname;
6451 S += '"';
6452 }
6453 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006454#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006455 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006456#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006457 }
6458
6459 if (!RDecl->hasFlexibleArrayMember()) {
6460 // Mark the end of the structure.
6461 uint64_t offs = toBits(size);
6462 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006463 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006464 }
6465
6466 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006467#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006468 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006469 if (CurOffs < CurLayObj->first) {
6470 uint64_t padding = CurLayObj->first - CurOffs;
6471 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6472 // packing/alignment of members is different that normal, in which case
6473 // the encoding will be out-of-sync with the real layout.
6474 // If the runtime switches to just consider the size of types without
6475 // taking into account alignment, we could make padding explicit in the
6476 // encoding (e.g. using arrays of chars). The encoding strings would be
6477 // longer then though.
6478 CurOffs += padding;
6479 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006480#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006481
6482 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006483 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006484 break; // reached end of structure.
6485
6486 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6487 // We expand the bases without their virtual bases since those are going
6488 // in the initial structure. Note that this differs from gcc which
6489 // expands virtual bases each time one is encountered in the hierarchy,
6490 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006491 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6492 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006493 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006494#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006495 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006496#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006497 } else {
6498 FieldDecl *field = cast<FieldDecl>(dcl);
6499 if (FD) {
6500 S += '"';
6501 S += field->getNameAsString();
6502 S += '"';
6503 }
6504
6505 if (field->isBitField()) {
6506 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006507#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006508 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006509#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006510 } else {
6511 QualType qt = field->getType();
6512 getLegacyIntegralTypeEncoding(qt);
6513 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6514 /*OutermostType*/false,
6515 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006516 /*StructField*/true,
6517 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006518#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006519 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006520#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006521 }
6522 }
6523 }
6524}
6525
Mike Stump11289f42009-09-09 15:08:12 +00006526void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006527 std::string& S) const {
6528 if (QT & Decl::OBJC_TQ_In)
6529 S += 'n';
6530 if (QT & Decl::OBJC_TQ_Inout)
6531 S += 'N';
6532 if (QT & Decl::OBJC_TQ_Out)
6533 S += 'o';
6534 if (QT & Decl::OBJC_TQ_Bycopy)
6535 S += 'O';
6536 if (QT & Decl::OBJC_TQ_Byref)
6537 S += 'R';
6538 if (QT & Decl::OBJC_TQ_Oneway)
6539 S += 'V';
6540}
6541
Douglas Gregor3ea72692011-08-12 05:46:01 +00006542TypedefDecl *ASTContext::getObjCIdDecl() const {
6543 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006544 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006545 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006546 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006547 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006548 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006549}
6550
Douglas Gregor52e02802011-08-12 06:17:30 +00006551TypedefDecl *ASTContext::getObjCSelDecl() const {
6552 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006553 QualType T = getPointerType(ObjCBuiltinSelTy);
6554 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006555 }
6556 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006557}
6558
Douglas Gregor0a586182011-08-12 05:59:41 +00006559TypedefDecl *ASTContext::getObjCClassDecl() const {
6560 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006561 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006562 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006563 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006564 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006565 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006566}
6567
Douglas Gregord53ae832012-01-17 18:09:05 +00006568ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6569 if (!ObjCProtocolClassDecl) {
6570 ObjCProtocolClassDecl
6571 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6572 SourceLocation(),
6573 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006574 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006575 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006576 SourceLocation(), true);
6577 }
6578
6579 return ObjCProtocolClassDecl;
6580}
6581
Meador Inge5d3fb222012-06-16 03:34:49 +00006582//===----------------------------------------------------------------------===//
6583// __builtin_va_list Construction Functions
6584//===----------------------------------------------------------------------===//
6585
Charles Davisc7d5c942015-09-17 20:55:33 +00006586static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6587 StringRef Name) {
6588 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006589 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006590 return Context->buildImplicitTypedef(T, Name);
6591}
6592
6593static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6594 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6595}
6596
6597static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6598 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006599}
6600
6601static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6602 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006603 QualType T = Context->getPointerType(Context->VoidTy);
6604 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006605}
6606
Tim Northover9bb857a2013-01-31 12:13:10 +00006607static TypedefDecl *
6608CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006609 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006610 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006611 if (Context->getLangOpts().CPlusPlus) {
6612 // namespace std { struct __va_list {
6613 NamespaceDecl *NS;
6614 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6615 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006616 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006617 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006618 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006619 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006620 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006621 }
6622
6623 VaListTagDecl->startDefinition();
6624
6625 const size_t NumFields = 5;
6626 QualType FieldTypes[NumFields];
6627 const char *FieldNames[NumFields];
6628
6629 // void *__stack;
6630 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6631 FieldNames[0] = "__stack";
6632
6633 // void *__gr_top;
6634 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6635 FieldNames[1] = "__gr_top";
6636
6637 // void *__vr_top;
6638 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6639 FieldNames[2] = "__vr_top";
6640
6641 // int __gr_offs;
6642 FieldTypes[3] = Context->IntTy;
6643 FieldNames[3] = "__gr_offs";
6644
6645 // int __vr_offs;
6646 FieldTypes[4] = Context->IntTy;
6647 FieldNames[4] = "__vr_offs";
6648
6649 // Create fields
6650 for (unsigned i = 0; i < NumFields; ++i) {
6651 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6652 VaListTagDecl,
6653 SourceLocation(),
6654 SourceLocation(),
6655 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006656 FieldTypes[i], /*TInfo=*/nullptr,
6657 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006658 /*Mutable=*/false,
6659 ICIS_NoInit);
6660 Field->setAccess(AS_public);
6661 VaListTagDecl->addDecl(Field);
6662 }
6663 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006664 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006665 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006666
6667 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006668 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006669}
6670
Meador Inge5d3fb222012-06-16 03:34:49 +00006671static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6672 // typedef struct __va_list_tag {
6673 RecordDecl *VaListTagDecl;
6674
Alp Toker2dea15b2013-12-17 01:22:38 +00006675 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006676 VaListTagDecl->startDefinition();
6677
6678 const size_t NumFields = 5;
6679 QualType FieldTypes[NumFields];
6680 const char *FieldNames[NumFields];
6681
6682 // unsigned char gpr;
6683 FieldTypes[0] = Context->UnsignedCharTy;
6684 FieldNames[0] = "gpr";
6685
6686 // unsigned char fpr;
6687 FieldTypes[1] = Context->UnsignedCharTy;
6688 FieldNames[1] = "fpr";
6689
6690 // unsigned short reserved;
6691 FieldTypes[2] = Context->UnsignedShortTy;
6692 FieldNames[2] = "reserved";
6693
6694 // void* overflow_arg_area;
6695 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6696 FieldNames[3] = "overflow_arg_area";
6697
6698 // void* reg_save_area;
6699 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6700 FieldNames[4] = "reg_save_area";
6701
6702 // Create fields
6703 for (unsigned i = 0; i < NumFields; ++i) {
6704 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6705 SourceLocation(),
6706 SourceLocation(),
6707 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006708 FieldTypes[i], /*TInfo=*/nullptr,
6709 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006710 /*Mutable=*/false,
6711 ICIS_NoInit);
6712 Field->setAccess(AS_public);
6713 VaListTagDecl->addDecl(Field);
6714 }
6715 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006716 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006717 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6718
6719 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006720 TypedefDecl *VaListTagTypedefDecl =
6721 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6722
Meador Inge5d3fb222012-06-16 03:34:49 +00006723 QualType VaListTagTypedefType =
6724 Context->getTypedefType(VaListTagTypedefDecl);
6725
6726 // typedef __va_list_tag __builtin_va_list[1];
6727 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6728 QualType VaListTagArrayType
6729 = Context->getConstantArrayType(VaListTagTypedefType,
6730 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006731 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006732}
6733
6734static TypedefDecl *
6735CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006736 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006737 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006738 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006739 VaListTagDecl->startDefinition();
6740
6741 const size_t NumFields = 4;
6742 QualType FieldTypes[NumFields];
6743 const char *FieldNames[NumFields];
6744
6745 // unsigned gp_offset;
6746 FieldTypes[0] = Context->UnsignedIntTy;
6747 FieldNames[0] = "gp_offset";
6748
6749 // unsigned fp_offset;
6750 FieldTypes[1] = Context->UnsignedIntTy;
6751 FieldNames[1] = "fp_offset";
6752
6753 // void* overflow_arg_area;
6754 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6755 FieldNames[2] = "overflow_arg_area";
6756
6757 // void* reg_save_area;
6758 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6759 FieldNames[3] = "reg_save_area";
6760
6761 // Create fields
6762 for (unsigned i = 0; i < NumFields; ++i) {
6763 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6764 VaListTagDecl,
6765 SourceLocation(),
6766 SourceLocation(),
6767 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006768 FieldTypes[i], /*TInfo=*/nullptr,
6769 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006770 /*Mutable=*/false,
6771 ICIS_NoInit);
6772 Field->setAccess(AS_public);
6773 VaListTagDecl->addDecl(Field);
6774 }
6775 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006776 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006777 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6778
Richard Smith9b88a4c2015-07-27 05:40:23 +00006779 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006780
Richard Smith9b88a4c2015-07-27 05:40:23 +00006781 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006782 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006783 QualType VaListTagArrayType =
6784 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006785 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006786}
6787
6788static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6789 // typedef int __builtin_va_list[4];
6790 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006791 QualType IntArrayType =
6792 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006793 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006794}
6795
Logan Chien57086ce2012-10-10 06:56:20 +00006796static TypedefDecl *
6797CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006798 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006799 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006800 if (Context->getLangOpts().CPlusPlus) {
6801 // namespace std { struct __va_list {
6802 NamespaceDecl *NS;
6803 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6804 Context->getTranslationUnitDecl(),
6805 /*Inline*/false, SourceLocation(),
6806 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006807 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006808 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006809 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006810 }
6811
6812 VaListDecl->startDefinition();
6813
6814 // void * __ap;
6815 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6816 VaListDecl,
6817 SourceLocation(),
6818 SourceLocation(),
6819 &Context->Idents.get("__ap"),
6820 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006821 /*TInfo=*/nullptr,
6822 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006823 /*Mutable=*/false,
6824 ICIS_NoInit);
6825 Field->setAccess(AS_public);
6826 VaListDecl->addDecl(Field);
6827
6828 // };
6829 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006830 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006831
6832 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006833 QualType T = Context->getRecordType(VaListDecl);
6834 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006835}
6836
Ulrich Weigand47445072013-05-06 16:26:41 +00006837static TypedefDecl *
6838CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006839 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006840 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006841 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006842 VaListTagDecl->startDefinition();
6843
6844 const size_t NumFields = 4;
6845 QualType FieldTypes[NumFields];
6846 const char *FieldNames[NumFields];
6847
6848 // long __gpr;
6849 FieldTypes[0] = Context->LongTy;
6850 FieldNames[0] = "__gpr";
6851
6852 // long __fpr;
6853 FieldTypes[1] = Context->LongTy;
6854 FieldNames[1] = "__fpr";
6855
6856 // void *__overflow_arg_area;
6857 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6858 FieldNames[2] = "__overflow_arg_area";
6859
6860 // void *__reg_save_area;
6861 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6862 FieldNames[3] = "__reg_save_area";
6863
6864 // Create fields
6865 for (unsigned i = 0; i < NumFields; ++i) {
6866 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6867 VaListTagDecl,
6868 SourceLocation(),
6869 SourceLocation(),
6870 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006871 FieldTypes[i], /*TInfo=*/nullptr,
6872 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006873 /*Mutable=*/false,
6874 ICIS_NoInit);
6875 Field->setAccess(AS_public);
6876 VaListTagDecl->addDecl(Field);
6877 }
6878 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006879 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006880 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006881
Richard Smith9b88a4c2015-07-27 05:40:23 +00006882 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006883
6884 // typedef __va_list_tag __builtin_va_list[1];
6885 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006886 QualType VaListTagArrayType =
6887 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006888
Alp Toker56b5cc92013-12-15 10:36:26 +00006889 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006890}
6891
Meador Inge5d3fb222012-06-16 03:34:49 +00006892static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6893 TargetInfo::BuiltinVaListKind Kind) {
6894 switch (Kind) {
6895 case TargetInfo::CharPtrBuiltinVaList:
6896 return CreateCharPtrBuiltinVaListDecl(Context);
6897 case TargetInfo::VoidPtrBuiltinVaList:
6898 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006899 case TargetInfo::AArch64ABIBuiltinVaList:
6900 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006901 case TargetInfo::PowerABIBuiltinVaList:
6902 return CreatePowerABIBuiltinVaListDecl(Context);
6903 case TargetInfo::X86_64ABIBuiltinVaList:
6904 return CreateX86_64ABIBuiltinVaListDecl(Context);
6905 case TargetInfo::PNaClABIBuiltinVaList:
6906 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006907 case TargetInfo::AAPCSABIBuiltinVaList:
6908 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006909 case TargetInfo::SystemZBuiltinVaList:
6910 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006911 }
6912
6913 llvm_unreachable("Unhandled __builtin_va_list type kind");
6914}
6915
6916TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006917 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006918 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006919 assert(BuiltinVaListDecl->isImplicit());
6920 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006921
6922 return BuiltinVaListDecl;
6923}
6924
Richard Smith9b88a4c2015-07-27 05:40:23 +00006925Decl *ASTContext::getVaListTagDecl() const {
6926 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006927 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006928 if (!VaListTagDecl)
6929 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006930
Richard Smith9b88a4c2015-07-27 05:40:23 +00006931 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006932}
6933
Charles Davisc7d5c942015-09-17 20:55:33 +00006934TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6935 if (!BuiltinMSVaListDecl)
6936 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6937
6938 return BuiltinMSVaListDecl;
6939}
6940
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006941void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006942 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006943 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006944
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006945 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006946}
6947
John McCalld28ae272009-12-02 08:04:21 +00006948/// \brief Retrieve the template name that corresponds to a non-empty
6949/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006950TemplateName
6951ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6952 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006953 unsigned size = End - Begin;
6954 assert(size > 1 && "set is not overloaded!");
6955
6956 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6957 size * sizeof(FunctionTemplateDecl*));
6958 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6959
6960 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006961 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006962 NamedDecl *D = *I;
6963 assert(isa<FunctionTemplateDecl>(D) ||
6964 (isa<UsingShadowDecl>(D) &&
6965 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6966 *Storage++ = D;
6967 }
6968
6969 return TemplateName(OT);
6970}
6971
Douglas Gregordc572a32009-03-30 22:58:21 +00006972/// \brief Retrieve the template name that represents a qualified
6973/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006974TemplateName
6975ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6976 bool TemplateKeyword,
6977 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006978 assert(NNS && "Missing nested-name-specifier in qualified template name");
6979
Douglas Gregorc42075a2010-02-04 18:10:26 +00006980 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006981 llvm::FoldingSetNodeID ID;
6982 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6983
Craig Topper36250ad2014-05-12 05:36:57 +00006984 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006985 QualifiedTemplateName *QTN =
6986 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6987 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006988 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006989 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006990 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6991 }
6992
6993 return TemplateName(QTN);
6994}
6995
6996/// \brief Retrieve the template name that represents a dependent
6997/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006998TemplateName
6999ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7000 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007001 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007002 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007003
7004 llvm::FoldingSetNodeID ID;
7005 DependentTemplateName::Profile(ID, NNS, Name);
7006
Craig Topper36250ad2014-05-12 05:36:57 +00007007 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007008 DependentTemplateName *QTN =
7009 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7010
7011 if (QTN)
7012 return TemplateName(QTN);
7013
7014 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7015 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007016 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007017 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007018 } else {
7019 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007020 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007021 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007022 DependentTemplateName *CheckQTN =
7023 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7024 assert(!CheckQTN && "Dependent type name canonicalization broken");
7025 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007026 }
7027
7028 DependentTemplateNames.InsertNode(QTN, InsertPos);
7029 return TemplateName(QTN);
7030}
7031
Douglas Gregor71395fa2009-11-04 00:56:37 +00007032/// \brief Retrieve the template name that represents a dependent
7033/// template name such as \c MetaFun::template operator+.
7034TemplateName
7035ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007036 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007037 assert((!NNS || NNS->isDependent()) &&
7038 "Nested name specifier must be dependent");
7039
7040 llvm::FoldingSetNodeID ID;
7041 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007042
7043 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007044 DependentTemplateName *QTN
7045 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007046
7047 if (QTN)
7048 return TemplateName(QTN);
7049
7050 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7051 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007052 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007053 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007054 } else {
7055 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007056 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007057 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007058
Douglas Gregorc42075a2010-02-04 18:10:26 +00007059 DependentTemplateName *CheckQTN
7060 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7061 assert(!CheckQTN && "Dependent template name canonicalization broken");
7062 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007063 }
7064
7065 DependentTemplateNames.InsertNode(QTN, InsertPos);
7066 return TemplateName(QTN);
7067}
7068
Douglas Gregor5590be02011-01-15 06:45:20 +00007069TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007070ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7071 TemplateName replacement) const {
7072 llvm::FoldingSetNodeID ID;
7073 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007074
7075 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007076 SubstTemplateTemplateParmStorage *subst
7077 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7078
7079 if (!subst) {
7080 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7081 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7082 }
7083
7084 return TemplateName(subst);
7085}
7086
7087TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007088ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7089 const TemplateArgument &ArgPack) const {
7090 ASTContext &Self = const_cast<ASTContext &>(*this);
7091 llvm::FoldingSetNodeID ID;
7092 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007093
7094 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007095 SubstTemplateTemplateParmPackStorage *Subst
7096 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7097
7098 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007099 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007100 ArgPack.pack_size(),
7101 ArgPack.pack_begin());
7102 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7103 }
7104
7105 return TemplateName(Subst);
7106}
7107
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007108/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007109/// TargetInfo, produce the corresponding type. The unsigned @p Type
7110/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007111CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007112 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007113 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007114 case TargetInfo::SignedChar: return SignedCharTy;
7115 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007116 case TargetInfo::SignedShort: return ShortTy;
7117 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7118 case TargetInfo::SignedInt: return IntTy;
7119 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7120 case TargetInfo::SignedLong: return LongTy;
7121 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7122 case TargetInfo::SignedLongLong: return LongLongTy;
7123 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7124 }
7125
David Blaikie83d382b2011-09-23 05:06:16 +00007126 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007127}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007128
7129//===----------------------------------------------------------------------===//
7130// Type Predicates.
7131//===----------------------------------------------------------------------===//
7132
Fariborz Jahanian96207692009-02-18 21:49:28 +00007133/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7134/// garbage collection attribute.
7135///
John McCall553d45a2011-01-12 00:34:59 +00007136Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007137 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007138 return Qualifiers::GCNone;
7139
David Blaikiebbafb8a2012-03-11 07:00:24 +00007140 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007141 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7142
7143 // Default behaviour under objective-C's gc is for ObjC pointers
7144 // (or pointers to them) be treated as though they were declared
7145 // as __strong.
7146 if (GCAttrs == Qualifiers::GCNone) {
7147 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7148 return Qualifiers::Strong;
7149 else if (Ty->isPointerType())
7150 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7151 } else {
7152 // It's not valid to set GC attributes on anything that isn't a
7153 // pointer.
7154#ifndef NDEBUG
7155 QualType CT = Ty->getCanonicalTypeInternal();
7156 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7157 CT = AT->getElementType();
7158 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7159#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007160 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007161 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007162}
7163
Chris Lattner49af6a42008-04-07 06:51:04 +00007164//===----------------------------------------------------------------------===//
7165// Type Compatibility Testing
7166//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007167
Mike Stump11289f42009-09-09 15:08:12 +00007168/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007169/// compatible.
7170static bool areCompatVectorTypes(const VectorType *LHS,
7171 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007172 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007173 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007174 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007175}
7176
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007177bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7178 QualType SecondVec) {
7179 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7180 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7181
7182 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7183 return true;
7184
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007185 // Treat Neon vector types and most AltiVec vector types as if they are the
7186 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007187 const VectorType *First = FirstVec->getAs<VectorType>();
7188 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007189 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007190 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007191 First->getVectorKind() != VectorType::AltiVecPixel &&
7192 First->getVectorKind() != VectorType::AltiVecBool &&
7193 Second->getVectorKind() != VectorType::AltiVecPixel &&
7194 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007195 return true;
7196
7197 return false;
7198}
7199
Steve Naroff8e6aee52009-07-23 01:01:38 +00007200//===----------------------------------------------------------------------===//
7201// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7202//===----------------------------------------------------------------------===//
7203
7204/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7205/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007206bool
7207ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7208 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007209 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007210 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007211 for (auto *PI : rProto->protocols())
7212 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007213 return true;
7214 return false;
7215}
7216
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007217/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7218/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007219bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7220 QualType rhs) {
7221 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7222 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7223 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7224
Aaron Ballman83731462014-03-17 16:14:00 +00007225 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007226 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007227 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007228 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7229 match = true;
7230 break;
7231 }
7232 }
7233 if (!match)
7234 return false;
7235 }
7236 return true;
7237}
7238
Steve Naroff8e6aee52009-07-23 01:01:38 +00007239/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7240/// ObjCQualifiedIDType.
7241bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7242 bool compare) {
7243 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007244 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007245 lhs->isObjCIdType() || lhs->isObjCClassType())
7246 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007247 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007248 rhs->isObjCIdType() || rhs->isObjCClassType())
7249 return true;
7250
7251 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007252 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007253
Steve Naroff8e6aee52009-07-23 01:01:38 +00007254 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007255
Steve Naroff8e6aee52009-07-23 01:01:38 +00007256 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007257 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007258 // make sure we check the class hierarchy.
7259 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007260 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007261 // when comparing an id<P> on lhs with a static type on rhs,
7262 // see if static class implements all of id's protocols, directly or
7263 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007264 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007265 return false;
7266 }
7267 }
7268 // If there are no qualifiers and no interface, we have an 'id'.
7269 return true;
7270 }
Mike Stump11289f42009-09-09 15:08:12 +00007271 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007272 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007273 bool match = false;
7274
7275 // when comparing an id<P> on lhs with a static type on rhs,
7276 // see if static class implements all of id's protocols, directly or
7277 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007278 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007279 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7280 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7281 match = true;
7282 break;
7283 }
7284 }
Mike Stump11289f42009-09-09 15:08:12 +00007285 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007286 // make sure we check the class hierarchy.
7287 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007288 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007289 // when comparing an id<P> on lhs with a static type on rhs,
7290 // see if static class implements all of id's protocols, directly or
7291 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007292 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007293 match = true;
7294 break;
7295 }
7296 }
7297 }
7298 if (!match)
7299 return false;
7300 }
Mike Stump11289f42009-09-09 15:08:12 +00007301
Steve Naroff8e6aee52009-07-23 01:01:38 +00007302 return true;
7303 }
Mike Stump11289f42009-09-09 15:08:12 +00007304
Steve Naroff8e6aee52009-07-23 01:01:38 +00007305 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7306 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7307
Mike Stump11289f42009-09-09 15:08:12 +00007308 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007309 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007310 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007311 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007312 bool match = false;
7313
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007314 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007315 // see if static class implements all of id's protocols, directly or
7316 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007317 // First, lhs protocols in the qualifier list must be found, direct
7318 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007319 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007320 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7321 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7322 match = true;
7323 break;
7324 }
7325 }
7326 if (!match)
7327 return false;
7328 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007329
7330 // Static class's protocols, or its super class or category protocols
7331 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7332 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7333 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7334 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7335 // This is rather dubious but matches gcc's behavior. If lhs has
7336 // no type qualifier and its class has no static protocol(s)
7337 // assume that it is mismatch.
7338 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7339 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007340 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007341 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007342 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007343 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7344 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7345 match = true;
7346 break;
7347 }
7348 }
7349 if (!match)
7350 return false;
7351 }
7352 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007353 return true;
7354 }
7355 return false;
7356}
7357
Eli Friedman47f77112008-08-22 00:56:42 +00007358/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007359/// compatible for assignment from RHS to LHS. This handles validation of any
7360/// protocol qualifiers on the LHS or RHS.
7361///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007362bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7363 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007364 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7365 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7366
Steve Naroff1329fa02009-07-15 18:40:39 +00007367 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007368 if (LHS->isObjCUnqualifiedIdOrClass() ||
7369 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007370 return true;
7371
Douglas Gregorab209d82015-07-07 03:58:42 +00007372 // Function object that propagates a successful result or handles
7373 // __kindof types.
7374 auto finish = [&](bool succeeded) -> bool {
7375 if (succeeded)
7376 return true;
7377
7378 if (!RHS->isKindOfType())
7379 return false;
7380
7381 // Strip off __kindof and protocol qualifiers, then check whether
7382 // we can assign the other way.
7383 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7384 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7385 };
7386
7387 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7388 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7389 QualType(RHSOPT,0),
7390 false));
7391 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007392
Douglas Gregorab209d82015-07-07 03:58:42 +00007393 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7394 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7395 QualType(RHSOPT,0)));
7396 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007397
John McCall8b07ec22010-05-15 11:32:37 +00007398 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007399 if (LHS->getInterface() && RHS->getInterface()) {
7400 return finish(canAssignObjCInterfaces(LHS, RHS));
7401 }
Mike Stump11289f42009-09-09 15:08:12 +00007402
Steve Naroff8e6aee52009-07-23 01:01:38 +00007403 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007404}
7405
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007406/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007407/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007408/// arguments in block literals. When passed as arguments, passing 'A*' where
7409/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7410/// not OK. For the return type, the opposite is not OK.
7411bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7412 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007413 const ObjCObjectPointerType *RHSOPT,
7414 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007415
7416 // Function object that propagates a successful result or handles
7417 // __kindof types.
7418 auto finish = [&](bool succeeded) -> bool {
7419 if (succeeded)
7420 return true;
7421
7422 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7423 if (!Expected->isKindOfType())
7424 return false;
7425
7426 // Strip off __kindof and protocol qualifiers, then check whether
7427 // we can assign the other way.
7428 return canAssignObjCInterfacesInBlockPointer(
7429 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7430 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7431 BlockReturnType);
7432 };
7433
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007434 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007435 return true;
7436
7437 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007438 return finish(RHSOPT->isObjCBuiltinType() ||
7439 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007440 }
7441
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007442 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007443 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7444 QualType(RHSOPT,0),
7445 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007446
7447 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7448 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7449 if (LHS && RHS) { // We have 2 user-defined types.
7450 if (LHS != RHS) {
7451 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007452 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007453 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007454 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007455 }
7456 else
7457 return true;
7458 }
7459 return false;
7460}
7461
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007462/// Comparison routine for Objective-C protocols to be used with
7463/// llvm::array_pod_sort.
7464static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7465 ObjCProtocolDecl * const *rhs) {
7466 return (*lhs)->getName().compare((*rhs)->getName());
7467
7468}
7469
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007470/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007471/// of protocols inherited from two distinct objective-c pointer objects with
7472/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007473/// It is used to build composite qualifier list of the composite type of
7474/// the conditional expression involving two objective-c pointer objects.
7475static
7476void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007477 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007478 const ObjCObjectPointerType *LHSOPT,
7479 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007480 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007481
John McCall8b07ec22010-05-15 11:32:37 +00007482 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7483 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7484 assert(LHS->getInterface() && "LHS must have an interface base");
7485 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007486
7487 // Add all of the protocols for the LHS.
7488 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7489
7490 // Start with the protocol qualifiers.
7491 for (auto proto : LHS->quals()) {
7492 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007493 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007494
7495 // Also add the protocols associated with the LHS interface.
7496 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7497
7498 // Add all of the protocls for the RHS.
7499 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7500
7501 // Start with the protocol qualifiers.
7502 for (auto proto : RHS->quals()) {
7503 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007504 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007505
7506 // Also add the protocols associated with the RHS interface.
7507 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7508
7509 // Compute the intersection of the collected protocol sets.
7510 for (auto proto : LHSProtocolSet) {
7511 if (RHSProtocolSet.count(proto))
7512 IntersectionSet.push_back(proto);
7513 }
7514
7515 // Compute the set of protocols that is implied by either the common type or
7516 // the protocols within the intersection.
7517 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7518 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7519
7520 // Remove any implied protocols from the list of inherited protocols.
7521 if (!ImpliedProtocols.empty()) {
7522 IntersectionSet.erase(
7523 std::remove_if(IntersectionSet.begin(),
7524 IntersectionSet.end(),
7525 [&](ObjCProtocolDecl *proto) -> bool {
7526 return ImpliedProtocols.count(proto) > 0;
7527 }),
7528 IntersectionSet.end());
7529 }
7530
7531 // Sort the remaining protocols by name.
7532 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7533 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007534}
7535
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007536/// Determine whether the first type is a subtype of the second.
7537static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7538 QualType rhs) {
7539 // Common case: two object pointers.
7540 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7541 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7542 if (lhsOPT && rhsOPT)
7543 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7544
7545 // Two block pointers.
7546 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7547 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7548 if (lhsBlock && rhsBlock)
7549 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7550
7551 // If either is an unqualified 'id' and the other is a block, it's
7552 // acceptable.
7553 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7554 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7555 return true;
7556
7557 return false;
7558}
7559
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007560// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007561static bool sameObjCTypeArgs(ASTContext &ctx,
7562 const ObjCInterfaceDecl *iface,
7563 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007564 ArrayRef<QualType> rhsArgs,
7565 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007566 if (lhsArgs.size() != rhsArgs.size())
7567 return false;
7568
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007569 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007570 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007571 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7572 continue;
7573
7574 switch (typeParams->begin()[i]->getVariance()) {
7575 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007576 if (!stripKindOf ||
7577 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7578 rhsArgs[i].stripObjCKindOfType(ctx))) {
7579 return false;
7580 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007581 break;
7582
7583 case ObjCTypeParamVariance::Covariant:
7584 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7585 return false;
7586 break;
7587
7588 case ObjCTypeParamVariance::Contravariant:
7589 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7590 return false;
7591 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007592 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007593 }
7594
7595 return true;
7596}
7597
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007598QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007599 const ObjCObjectPointerType *Lptr,
7600 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007601 const ObjCObjectType *LHS = Lptr->getObjectType();
7602 const ObjCObjectType *RHS = Rptr->getObjectType();
7603 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7604 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007605
7606 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007607 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007608
Manman Renc46f7d12016-05-06 19:35:02 +00007609 // When either LHS or RHS is a kindof type, we should return a kindof type.
7610 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7611 // kindof(A).
7612 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7613
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007614 // Follow the left-hand side up the class hierarchy until we either hit a
7615 // root or find the RHS. Record the ancestors in case we don't find it.
7616 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7617 LHSAncestors;
7618 while (true) {
7619 // Record this ancestor. We'll need this if the common type isn't in the
7620 // path from the LHS to the root.
7621 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007622
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007623 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7624 // Get the type arguments.
7625 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7626 bool anyChanges = false;
7627 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7628 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007629 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7630 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007631 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007632 return QualType();
7633 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7634 // If only one has type arguments, the result will not have type
7635 // arguments.
7636 LHSTypeArgs = { };
7637 anyChanges = true;
7638 }
7639
7640 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007641 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007642 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7643 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007644 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007645 anyChanges = true;
7646
7647 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007648 // If we need to return a kindof type but LHS is not a kindof type, we
7649 // build a new result type.
7650 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007651 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007652 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007653 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007654 return getObjCObjectPointerType(Result);
7655 }
7656
7657 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007658 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007659
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007660 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007661 QualType LHSSuperType = LHS->getSuperClassType();
7662 if (LHSSuperType.isNull())
7663 break;
7664
7665 LHS = LHSSuperType->castAs<ObjCObjectType>();
7666 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007667
7668 // We didn't find anything by following the LHS to its root; now check
7669 // the RHS against the cached set of ancestors.
7670 while (true) {
7671 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7672 if (KnownLHS != LHSAncestors.end()) {
7673 LHS = KnownLHS->second;
7674
7675 // Get the type arguments.
7676 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7677 bool anyChanges = false;
7678 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7679 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007680 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7681 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007682 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007683 return QualType();
7684 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7685 // If only one has type arguments, the result will not have type
7686 // arguments.
7687 RHSTypeArgs = { };
7688 anyChanges = true;
7689 }
7690
7691 // Compute the intersection of protocols.
7692 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7693 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7694 Protocols);
7695 if (!Protocols.empty())
7696 anyChanges = true;
7697
Manman Renc46f7d12016-05-06 19:35:02 +00007698 // If we need to return a kindof type but RHS is not a kindof type, we
7699 // build a new result type.
7700 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007701 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007702 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007703 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007704 return getObjCObjectPointerType(Result);
7705 }
7706
7707 return getObjCObjectPointerType(QualType(RHS, 0));
7708 }
7709
7710 // Find the superclass of the RHS.
7711 QualType RHSSuperType = RHS->getSuperClassType();
7712 if (RHSSuperType.isNull())
7713 break;
7714
7715 RHS = RHSSuperType->castAs<ObjCObjectType>();
7716 }
7717
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007718 return QualType();
7719}
7720
John McCall8b07ec22010-05-15 11:32:37 +00007721bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7722 const ObjCObjectType *RHS) {
7723 assert(LHS->getInterface() && "LHS is not an interface type");
7724 assert(RHS->getInterface() && "RHS is not an interface type");
7725
Chris Lattner49af6a42008-04-07 06:51:04 +00007726 // Verify that the base decls are compatible: the RHS must be a subclass of
7727 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007728 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7729 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7730 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007731 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007732
Douglas Gregore83b9562015-07-07 03:57:53 +00007733 // If the LHS has protocol qualifiers, determine whether all of them are
7734 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7735 // LHS).
7736 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007737 // OK if conversion of LHS to SuperClass results in narrowing of types
7738 // ; i.e., SuperClass may implement at least one of the protocols
7739 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7740 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7741 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7742 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7743 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7744 // qualifiers.
7745 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007746 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007747 // If there is no protocols associated with RHS, it is not a match.
7748 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007749 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007750
7751 for (const auto *LHSProto : LHS->quals()) {
7752 bool SuperImplementsProtocol = false;
7753 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7754 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7755 SuperImplementsProtocol = true;
7756 break;
7757 }
7758 if (!SuperImplementsProtocol)
7759 return false;
7760 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007761 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007762
7763 // If the LHS is specialized, we may need to check type arguments.
7764 if (LHS->isSpecialized()) {
7765 // Follow the superclass chain until we've matched the LHS class in the
7766 // hierarchy. This substitutes type arguments through.
7767 const ObjCObjectType *RHSSuper = RHS;
7768 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7769 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7770
7771 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007772 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007773 !sameObjCTypeArgs(*this, LHS->getInterface(),
7774 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007775 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007776 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007777 }
7778 }
7779
7780 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007781}
7782
Steve Naroffb7605152009-02-12 17:52:19 +00007783bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7784 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007785 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7786 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007787
Steve Naroff7cae42b2009-07-10 23:34:53 +00007788 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007789 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007790
7791 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7792 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007793}
7794
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007795bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7796 return canAssignObjCInterfaces(
7797 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7798 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7799}
7800
Mike Stump11289f42009-09-09 15:08:12 +00007801/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007802/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007803/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007804/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007805bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7806 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007807 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007808 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007809
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007810 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007811}
7812
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007813bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007814 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007815}
7816
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007817bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7818 return !mergeTypes(LHS, RHS, true).isNull();
7819}
7820
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007821/// mergeTransparentUnionType - if T is a transparent union type and a member
7822/// of T is compatible with SubType, return the merged type, else return
7823/// QualType()
7824QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7825 bool OfBlockPointer,
7826 bool Unqualified) {
7827 if (const RecordType *UT = T->getAsUnionType()) {
7828 RecordDecl *UD = UT->getDecl();
7829 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007830 for (const auto *I : UD->fields()) {
7831 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007832 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7833 if (!MT.isNull())
7834 return MT;
7835 }
7836 }
7837 }
7838
7839 return QualType();
7840}
7841
Alp Toker9cacbab2014-01-20 20:26:09 +00007842/// mergeFunctionParameterTypes - merge two types which appear as function
7843/// parameter types
7844QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7845 bool OfBlockPointer,
7846 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007847 // GNU extension: two types are compatible if they appear as a function
7848 // argument, one of the types is a transparent union type and the other
7849 // type is compatible with a union member
7850 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7851 Unqualified);
7852 if (!lmerge.isNull())
7853 return lmerge;
7854
7855 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7856 Unqualified);
7857 if (!rmerge.isNull())
7858 return rmerge;
7859
7860 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7861}
7862
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007863QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007864 bool OfBlockPointer,
7865 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007866 const FunctionType *lbase = lhs->getAs<FunctionType>();
7867 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007868 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7869 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007870 bool allLTypes = true;
7871 bool allRTypes = true;
7872
7873 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007874 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007875 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007876 QualType RHS = rbase->getReturnType();
7877 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007878 bool UnqualifiedResult = Unqualified;
7879 if (!UnqualifiedResult)
7880 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007881 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007882 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007883 else
Alp Toker314cc812014-01-25 16:55:45 +00007884 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007885 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007886 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007887
7888 if (Unqualified)
7889 retType = retType.getUnqualifiedType();
7890
Alp Toker314cc812014-01-25 16:55:45 +00007891 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7892 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007893 if (Unqualified) {
7894 LRetType = LRetType.getUnqualifiedType();
7895 RRetType = RRetType.getUnqualifiedType();
7896 }
7897
7898 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007899 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007900 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007901 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007902
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007903 // FIXME: double check this
7904 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7905 // rbase->getRegParmAttr() != 0 &&
7906 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007907 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7908 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007909
Douglas Gregor8c940862010-01-18 17:14:39 +00007910 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007911 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007912 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007913
John McCall8c6b56f2010-12-15 01:06:38 +00007914 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007915 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7916 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007917 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7918 return QualType();
7919
John McCall31168b02011-06-15 23:02:42 +00007920 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7921 return QualType();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00007922 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
7923 return QualType();
John McCall31168b02011-06-15 23:02:42 +00007924
John McCall8c6b56f2010-12-15 01:06:38 +00007925 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7926 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007927
Rafael Espindola8778c282012-11-29 16:09:03 +00007928 if (lbaseInfo.getNoReturn() != NoReturn)
7929 allLTypes = false;
7930 if (rbaseInfo.getNoReturn() != NoReturn)
7931 allRTypes = false;
7932
John McCall31168b02011-06-15 23:02:42 +00007933 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007934
Eli Friedman47f77112008-08-22 00:56:42 +00007935 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007936 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7937 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007938 // Compatible functions must have the same number of parameters
7939 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007940 return QualType();
7941
7942 // Variadic and non-variadic functions aren't compatible
7943 if (lproto->isVariadic() != rproto->isVariadic())
7944 return QualType();
7945
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007946 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7947 return QualType();
7948
John McCall18afab72016-03-01 00:49:02 +00007949 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007950 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007951
7952 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007953 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007954 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7955 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7956 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7957 QualType paramType = mergeFunctionParameterTypes(
7958 lParamType, rParamType, OfBlockPointer, Unqualified);
7959 if (paramType.isNull())
7960 return QualType();
7961
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007962 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007963 paramType = paramType.getUnqualifiedType();
7964
7965 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007966 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007967 lParamType = lParamType.getUnqualifiedType();
7968 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007969 }
Alp Toker601b22c2014-01-21 23:35:24 +00007970
7971 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007972 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007973 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007974 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007975 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007976
Eli Friedman47f77112008-08-22 00:56:42 +00007977 if (allLTypes) return lhs;
7978 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007979
7980 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7981 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007982 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007983 }
7984
7985 if (lproto) allRTypes = false;
7986 if (rproto) allLTypes = false;
7987
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007988 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007989 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007990 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007991 if (proto->isVariadic()) return QualType();
7992 // Check that the types are compatible with the types that
7993 // would result from default argument promotions (C99 6.7.5.3p15).
7994 // The only types actually affected are promotable integer
7995 // types and floats, which would be passed as a different
7996 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007997 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7998 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007999
Eli Friedman448ce402012-08-30 00:44:15 +00008000 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008001 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00008002 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8003 paramTy = Enum->getDecl()->getIntegerType();
8004 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008005 return QualType();
8006 }
Alp Toker601b22c2014-01-21 23:35:24 +00008007
8008 if (paramTy->isPromotableIntegerType() ||
8009 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008010 return QualType();
8011 }
8012
8013 if (allLTypes) return lhs;
8014 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008015
8016 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8017 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008018 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008019 }
8020
8021 if (allLTypes) return lhs;
8022 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008023 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008024}
8025
John McCall433c2e62013-03-21 00:10:07 +00008026/// Given that we have an enum type and a non-enum type, try to merge them.
8027static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8028 QualType other, bool isBlockReturnType) {
8029 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8030 // a signed integer type, or an unsigned integer type.
8031 // Compatibility is based on the underlying type, not the promotion
8032 // type.
8033 QualType underlyingType = ET->getDecl()->getIntegerType();
8034 if (underlyingType.isNull()) return QualType();
8035 if (Context.hasSameType(underlyingType, other))
8036 return other;
8037
8038 // In block return types, we're more permissive and accept any
8039 // integral type of the same size.
8040 if (isBlockReturnType && other->isIntegerType() &&
8041 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8042 return other;
8043
8044 return QualType();
8045}
8046
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008047QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008048 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008049 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008050 // C++ [expr]: If an expression initially has the type "reference to T", the
8051 // type is adjusted to "T" prior to any further analysis, the expression
8052 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008053 // expression is an lvalue unless the reference is an rvalue reference and
8054 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008055 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8056 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008057
8058 if (Unqualified) {
8059 LHS = LHS.getUnqualifiedType();
8060 RHS = RHS.getUnqualifiedType();
8061 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008062
Eli Friedman47f77112008-08-22 00:56:42 +00008063 QualType LHSCan = getCanonicalType(LHS),
8064 RHSCan = getCanonicalType(RHS);
8065
8066 // If two types are identical, they are compatible.
8067 if (LHSCan == RHSCan)
8068 return LHS;
8069
John McCall8ccfcb52009-09-24 19:53:00 +00008070 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008071 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8072 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008073 if (LQuals != RQuals) {
8074 // If any of these qualifiers are different, we have a type
8075 // mismatch.
8076 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008077 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008078 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8079 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008080 return QualType();
8081
8082 // Exactly one GC qualifier difference is allowed: __strong is
8083 // okay if the other type has no GC qualifier but is an Objective
8084 // C object pointer (i.e. implicitly strong by default). We fix
8085 // this by pretending that the unqualified type was actually
8086 // qualified __strong.
8087 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8088 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8089 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8090
8091 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8092 return QualType();
8093
8094 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8095 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8096 }
8097 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8098 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8099 }
Eli Friedman47f77112008-08-22 00:56:42 +00008100 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008101 }
8102
8103 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008104
Eli Friedmandcca6332009-06-01 01:22:52 +00008105 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8106 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008107
Chris Lattnerfd652912008-01-14 05:45:46 +00008108 // We want to consider the two function types to be the same for these
8109 // comparisons, just force one to the other.
8110 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8111 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008112
8113 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008114 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8115 LHSClass = Type::ConstantArray;
8116 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8117 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008118
John McCall8b07ec22010-05-15 11:32:37 +00008119 // ObjCInterfaces are just specialized ObjCObjects.
8120 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8121 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8122
Nate Begemance4d7fc2008-04-18 23:10:10 +00008123 // Canonicalize ExtVector -> Vector.
8124 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8125 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008126
Chris Lattner95554662008-04-07 05:43:21 +00008127 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008128 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008129 // Note that we only have special rules for turning block enum
8130 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008131 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008132 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008133 }
John McCall9dd450b2009-09-21 23:43:11 +00008134 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008135 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008136 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008137 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008138 if (OfBlockPointer && !BlockReturnType) {
8139 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8140 return LHS;
8141 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8142 return RHS;
8143 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008144
Eli Friedman47f77112008-08-22 00:56:42 +00008145 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008146 }
Eli Friedman47f77112008-08-22 00:56:42 +00008147
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008148 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008149 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008150#define TYPE(Class, Base)
8151#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008152#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008153#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8154#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8155#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008156 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008157
Richard Smith27d807c2013-04-30 13:56:41 +00008158 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008159 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008160 case Type::LValueReference:
8161 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008162 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008163 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008164
John McCall8b07ec22010-05-15 11:32:37 +00008165 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008166 case Type::IncompleteArray:
8167 case Type::VariableArray:
8168 case Type::FunctionProto:
8169 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008170 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008171
Chris Lattnerfd652912008-01-14 05:45:46 +00008172 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008173 {
8174 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008175 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8176 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008177 if (Unqualified) {
8178 LHSPointee = LHSPointee.getUnqualifiedType();
8179 RHSPointee = RHSPointee.getUnqualifiedType();
8180 }
8181 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8182 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008183 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008184 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008185 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008186 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008187 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008188 return getPointerType(ResultType);
8189 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008190 case Type::BlockPointer:
8191 {
8192 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008193 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8194 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008195 if (Unqualified) {
8196 LHSPointee = LHSPointee.getUnqualifiedType();
8197 RHSPointee = RHSPointee.getUnqualifiedType();
8198 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008199 if (getLangOpts().OpenCL) {
8200 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8201 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8202 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8203 // 6.12.5) thus the following check is asymmetric.
8204 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8205 return QualType();
8206 LHSPteeQual.removeAddressSpace();
8207 RHSPteeQual.removeAddressSpace();
8208 LHSPointee =
8209 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8210 RHSPointee =
8211 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8212 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008213 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8214 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008215 if (ResultType.isNull()) return QualType();
8216 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8217 return LHS;
8218 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8219 return RHS;
8220 return getBlockPointerType(ResultType);
8221 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008222 case Type::Atomic:
8223 {
8224 // Merge two pointer types, while trying to preserve typedef info
8225 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8226 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8227 if (Unqualified) {
8228 LHSValue = LHSValue.getUnqualifiedType();
8229 RHSValue = RHSValue.getUnqualifiedType();
8230 }
8231 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8232 Unqualified);
8233 if (ResultType.isNull()) return QualType();
8234 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8235 return LHS;
8236 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8237 return RHS;
8238 return getAtomicType(ResultType);
8239 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008240 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008241 {
8242 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8243 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8244 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8245 return QualType();
8246
8247 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8248 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008249 if (Unqualified) {
8250 LHSElem = LHSElem.getUnqualifiedType();
8251 RHSElem = RHSElem.getUnqualifiedType();
8252 }
8253
8254 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008255 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008256 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8257 return LHS;
8258 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8259 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008260 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8261 ArrayType::ArraySizeModifier(), 0);
8262 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8263 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008264 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8265 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008266 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8267 return LHS;
8268 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8269 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008270 if (LVAT) {
8271 // FIXME: This isn't correct! But tricky to implement because
8272 // the array's size has to be the size of LHS, but the type
8273 // has to be different.
8274 return LHS;
8275 }
8276 if (RVAT) {
8277 // FIXME: This isn't correct! But tricky to implement because
8278 // the array's size has to be the size of RHS, but the type
8279 // has to be different.
8280 return RHS;
8281 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008282 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8283 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008284 return getIncompleteArrayType(ResultType,
8285 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008286 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008287 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008288 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008289 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008290 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008291 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008292 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008293 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008294 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008295 case Type::Complex:
8296 // Distinct complex types are incompatible.
8297 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008298 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008299 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008300 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8301 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008302 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008303 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008304 case Type::ObjCObject: {
8305 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008306 // FIXME: This should be type compatibility, e.g. whether
8307 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008308 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8309 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8310 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008311 return LHS;
8312
Eli Friedman47f77112008-08-22 00:56:42 +00008313 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008314 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008315 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008316 if (OfBlockPointer) {
8317 if (canAssignObjCInterfacesInBlockPointer(
8318 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008319 RHS->getAs<ObjCObjectPointerType>(),
8320 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008321 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008322 return QualType();
8323 }
John McCall9dd450b2009-09-21 23:43:11 +00008324 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8325 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008326 return LHS;
8327
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008328 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008329 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008330 case Type::Pipe:
8331 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008332 assert(LHS != RHS &&
8333 "Equivalent pipe types should have already been handled!");
8334 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008335 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008336 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008337
David Blaikie8a40f702012-01-17 06:56:22 +00008338 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008339}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008340
John McCall18afab72016-03-01 00:49:02 +00008341bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8342 const FunctionProtoType *firstFnType,
8343 const FunctionProtoType *secondFnType) {
8344 // Fast path: if the first type doesn't have ext parameter infos,
8345 // we match if and only if they second type also doesn't have them.
8346 if (!firstFnType->hasExtParameterInfos())
8347 return !secondFnType->hasExtParameterInfos();
8348
8349 // Otherwise, we can only match if the second type has them.
8350 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008351 return false;
John McCall18afab72016-03-01 00:49:02 +00008352
8353 auto firstEPI = firstFnType->getExtParameterInfos();
8354 auto secondEPI = secondFnType->getExtParameterInfos();
8355 assert(firstEPI.size() == secondEPI.size());
8356
8357 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8358 if (firstEPI[i] != secondEPI[i])
8359 return false;
8360 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008361 return true;
8362}
8363
Chandler Carruth21c90602015-12-30 03:24:14 +00008364void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8365 ObjCLayouts[CD] = nullptr;
8366}
8367
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008368/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8369/// 'RHS' attributes and returns the merged version; including for function
8370/// return types.
8371QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8372 QualType LHSCan = getCanonicalType(LHS),
8373 RHSCan = getCanonicalType(RHS);
8374 // If two types are identical, they are compatible.
8375 if (LHSCan == RHSCan)
8376 return LHS;
8377 if (RHSCan->isFunctionType()) {
8378 if (!LHSCan->isFunctionType())
8379 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008380 QualType OldReturnType =
8381 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008382 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008383 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008384 QualType ResReturnType =
8385 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8386 if (ResReturnType.isNull())
8387 return QualType();
8388 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8389 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8390 // In either case, use OldReturnType to build the new function type.
8391 const FunctionType *F = LHS->getAs<FunctionType>();
8392 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008393 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8394 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008395 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008396 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008397 return ResultType;
8398 }
8399 }
8400 return QualType();
8401 }
8402
8403 // If the qualifiers are different, the types can still be merged.
8404 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8405 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8406 if (LQuals != RQuals) {
8407 // If any of these qualifiers are different, we have a type mismatch.
8408 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8409 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8410 return QualType();
8411
8412 // Exactly one GC qualifier difference is allowed: __strong is
8413 // okay if the other type has no GC qualifier but is an Objective
8414 // C object pointer (i.e. implicitly strong by default). We fix
8415 // this by pretending that the unqualified type was actually
8416 // qualified __strong.
8417 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8418 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8419 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8420
8421 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8422 return QualType();
8423
8424 if (GC_L == Qualifiers::Strong)
8425 return LHS;
8426 if (GC_R == Qualifiers::Strong)
8427 return RHS;
8428 return QualType();
8429 }
8430
8431 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8432 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8433 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8434 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8435 if (ResQT == LHSBaseQT)
8436 return LHS;
8437 if (ResQT == RHSBaseQT)
8438 return RHS;
8439 }
8440 return QualType();
8441}
8442
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008443//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008444// Integer Predicates
8445//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008446
Jay Foad39c79802011-01-12 09:06:06 +00008447unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008448 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008449 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008450 if (T->isBooleanType())
8451 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008452 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008453 return (unsigned)getTypeSize(T);
8454}
8455
Abramo Bagnara13640492012-09-09 10:21:24 +00008456QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008457 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008458
8459 // Turn <4 x signed int> -> <4 x unsigned int>
8460 if (const VectorType *VTy = T->getAs<VectorType>())
8461 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008462 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008463
8464 // For enums, we return the unsigned version of the base type.
8465 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008466 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008467
8468 const BuiltinType *BTy = T->getAs<BuiltinType>();
8469 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008470 switch (BTy->getKind()) {
8471 case BuiltinType::Char_S:
8472 case BuiltinType::SChar:
8473 return UnsignedCharTy;
8474 case BuiltinType::Short:
8475 return UnsignedShortTy;
8476 case BuiltinType::Int:
8477 return UnsignedIntTy;
8478 case BuiltinType::Long:
8479 return UnsignedLongTy;
8480 case BuiltinType::LongLong:
8481 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008482 case BuiltinType::Int128:
8483 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008484 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008485 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008486 }
8487}
8488
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008489ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008490
Richard Smith1fa5d642013-05-11 05:45:24 +00008491void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8492 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008493
8494//===----------------------------------------------------------------------===//
8495// Builtin Type Computation
8496//===----------------------------------------------------------------------===//
8497
8498/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008499/// pointer over the consumed characters. This returns the resultant type. If
8500/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8501/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8502/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008503///
8504/// RequiresICE is filled in on return to indicate whether the value is required
8505/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008506static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008507 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008508 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008509 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008510 // Modifiers.
8511 int HowLong = 0;
8512 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008513 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008514
Chris Lattnerdc226c22010-10-01 22:42:38 +00008515 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008516 bool Done = false;
8517 while (!Done) {
8518 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008519 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008520 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008521 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008522 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008523 case 'S':
8524 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8525 assert(!Signed && "Can't use 'S' modifier multiple times!");
8526 Signed = true;
8527 break;
8528 case 'U':
8529 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008530 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008531 Unsigned = true;
8532 break;
8533 case 'L':
8534 assert(HowLong <= 2 && "Can't have LLLL modifier");
8535 ++HowLong;
8536 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008537 case 'W':
8538 // This modifier represents int64 type.
8539 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8540 switch (Context.getTargetInfo().getInt64Type()) {
8541 default:
8542 llvm_unreachable("Unexpected integer type");
8543 case TargetInfo::SignedLong:
8544 HowLong = 1;
8545 break;
8546 case TargetInfo::SignedLongLong:
8547 HowLong = 2;
8548 break;
8549 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008550 }
8551 }
8552
8553 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008554
Chris Lattnerecd79c62009-06-14 00:45:47 +00008555 // Read the base type.
8556 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008557 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008558 case 'v':
8559 assert(HowLong == 0 && !Signed && !Unsigned &&
8560 "Bad modifiers used with 'v'!");
8561 Type = Context.VoidTy;
8562 break;
Jack Carter24bef982013-08-15 15:16:57 +00008563 case 'h':
8564 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008565 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008566 Type = Context.HalfTy;
8567 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008568 case 'f':
8569 assert(HowLong == 0 && !Signed && !Unsigned &&
8570 "Bad modifiers used with 'f'!");
8571 Type = Context.FloatTy;
8572 break;
8573 case 'd':
8574 assert(HowLong < 2 && !Signed && !Unsigned &&
8575 "Bad modifiers used with 'd'!");
8576 if (HowLong)
8577 Type = Context.LongDoubleTy;
8578 else
8579 Type = Context.DoubleTy;
8580 break;
8581 case 's':
8582 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8583 if (Unsigned)
8584 Type = Context.UnsignedShortTy;
8585 else
8586 Type = Context.ShortTy;
8587 break;
8588 case 'i':
8589 if (HowLong == 3)
8590 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8591 else if (HowLong == 2)
8592 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8593 else if (HowLong == 1)
8594 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8595 else
8596 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8597 break;
8598 case 'c':
8599 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8600 if (Signed)
8601 Type = Context.SignedCharTy;
8602 else if (Unsigned)
8603 Type = Context.UnsignedCharTy;
8604 else
8605 Type = Context.CharTy;
8606 break;
8607 case 'b': // boolean
8608 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8609 Type = Context.BoolTy;
8610 break;
8611 case 'z': // size_t.
8612 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8613 Type = Context.getSizeType();
8614 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008615 case 'w': // wchar_t.
8616 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8617 Type = Context.getWideCharType();
8618 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008619 case 'F':
8620 Type = Context.getCFConstantStringType();
8621 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008622 case 'G':
8623 Type = Context.getObjCIdType();
8624 break;
8625 case 'H':
8626 Type = Context.getObjCSelType();
8627 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008628 case 'M':
8629 Type = Context.getObjCSuperType();
8630 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008631 case 'a':
8632 Type = Context.getBuiltinVaListType();
8633 assert(!Type.isNull() && "builtin va list type not initialized!");
8634 break;
8635 case 'A':
8636 // This is a "reference" to a va_list; however, what exactly
8637 // this means depends on how va_list is defined. There are two
8638 // different kinds of va_list: ones passed by value, and ones
8639 // passed by reference. An example of a by-value va_list is
8640 // x86, where va_list is a char*. An example of by-ref va_list
8641 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8642 // we want this argument to be a char*&; for x86-64, we want
8643 // it to be a __va_list_tag*.
8644 Type = Context.getBuiltinVaListType();
8645 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008646 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008647 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008648 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008649 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008650 break;
8651 case 'V': {
8652 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008653 unsigned NumElements = strtoul(Str, &End, 10);
8654 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008655 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008656
Chandler Carruth45bbe012017-03-24 09:11:57 +00008657 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8658 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008659 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008660
8661 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008662 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008663 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008664 break;
8665 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008666 case 'E': {
8667 char *End;
8668
8669 unsigned NumElements = strtoul(Str, &End, 10);
8670 assert(End != Str && "Missing vector size");
8671
8672 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008673
Douglas Gregorfed66992012-06-07 18:08:25 +00008674 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008675 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00008676 Type = Context.getExtVectorType(ElementType, NumElements);
8677 break;
8678 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008679 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008680 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008681 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008682 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008683 Type = Context.getComplexType(ElementType);
8684 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008685 }
8686 case 'Y' : {
8687 Type = Context.getPointerDiffType();
8688 break;
8689 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008690 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008691 Type = Context.getFILEType();
8692 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008693 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008694 return QualType();
8695 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008696 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008697 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008698 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008699 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008700 else
8701 Type = Context.getjmp_bufType();
8702
Mike Stump2adb4da2009-07-28 23:47:15 +00008703 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008704 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008705 return QualType();
8706 }
8707 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008708 case 'K':
8709 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8710 Type = Context.getucontext_tType();
8711
8712 if (Type.isNull()) {
8713 Error = ASTContext::GE_Missing_ucontext;
8714 return QualType();
8715 }
8716 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008717 case 'p':
8718 Type = Context.getProcessIDType();
8719 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008720 }
Mike Stump11289f42009-09-09 15:08:12 +00008721
Chris Lattnerdc226c22010-10-01 22:42:38 +00008722 // If there are modifiers and if we're allowed to parse them, go for it.
8723 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008724 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008725 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008726 default: Done = true; --Str; break;
8727 case '*':
8728 case '&': {
8729 // Both pointers and references can have their pointee types
8730 // qualified with an address space.
8731 char *End;
8732 unsigned AddrSpace = strtoul(Str, &End, 10);
8733 if (End != Str && AddrSpace != 0) {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00008734 Type = Context.getAddrSpaceQualType(
8735 Type, AddrSpace + LangAS::FirstTargetAddressSpace);
Chris Lattnerdc226c22010-10-01 22:42:38 +00008736 Str = End;
8737 }
8738 if (c == '*')
8739 Type = Context.getPointerType(Type);
8740 else
8741 Type = Context.getLValueReferenceType(Type);
8742 break;
8743 }
8744 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8745 case 'C':
8746 Type = Type.withConst();
8747 break;
8748 case 'D':
8749 Type = Context.getVolatileType(Type);
8750 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008751 case 'R':
8752 Type = Type.withRestrict();
8753 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008754 }
8755 }
Chris Lattner84733392010-10-01 07:13:18 +00008756
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008757 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008758 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008759
Chris Lattnerecd79c62009-06-14 00:45:47 +00008760 return Type;
8761}
8762
8763/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00008764QualType ASTContext::GetBuiltinType(unsigned Id,
8765 GetBuiltinTypeError &Error,
8766 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008767 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008768
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008769 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008770
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008771 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008772 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008773 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8774 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008775 if (Error != GE_None)
8776 return QualType();
Chandler Carruth45bbe012017-03-24 09:11:57 +00008777
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008778 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00008779
Chris Lattnerecd79c62009-06-14 00:45:47 +00008780 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00008781 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008782 if (Error != GE_None)
8783 return QualType();
8784
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008785 // If this argument is required to be an IntegerConstantExpression and the
8786 // caller cares, fill in the bitmask we return.
8787 if (RequiresICE && IntegerConstantArgs)
8788 *IntegerConstantArgs |= 1 << ArgTypes.size();
8789
Chris Lattnerecd79c62009-06-14 00:45:47 +00008790 // Do array -> pointer decay. The builtin should use the decayed type.
8791 if (Ty->isArrayType())
8792 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008793
Chris Lattnerecd79c62009-06-14 00:45:47 +00008794 ArgTypes.push_back(Ty);
8795 }
8796
David Majnemerba3e5ec2015-03-13 18:26:17 +00008797 if (Id == Builtin::BI__GetExceptionInfo)
8798 return QualType();
8799
Chris Lattnerecd79c62009-06-14 00:45:47 +00008800 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8801 "'.' should only occur at end of builtin type list!");
8802
Reid Kleckner78af0702013-08-27 23:08:25 +00008803 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008804 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8805
8806 bool Variadic = (TypeStr[0] == '.');
8807
Richard Smith836de6b2016-12-19 23:59:34 +00008808 // We really shouldn't be making a no-proto type here.
8809 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008810 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008811
John McCalldb40c7f2010-12-14 08:05:40 +00008812 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008813 EPI.ExtInfo = EI;
8814 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008815 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8816 EPI.ExceptionSpec.Type =
8817 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008818
Jordan Rose5c382722013-03-08 21:51:21 +00008819 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008820}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008821
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008822static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8823 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008824 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008825 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008826
Yaron Keren4cd211b2017-02-22 14:32:39 +00008827 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008828 switch (FD->getTemplateSpecializationKind()) {
8829 case TSK_Undeclared:
8830 case TSK_ExplicitSpecialization:
8831 External = GVA_StrongExternal;
8832 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008833
Rafael Espindola3ae00052013-05-13 00:12:11 +00008834 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008835 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008836
David Majnemerc3d07332014-05-15 06:25:57 +00008837 // C++11 [temp.explicit]p10:
8838 // [ Note: The intent is that an inline function that is the subject of
8839 // an explicit instantiation declaration will still be implicitly
8840 // instantiated when used so that the body can be considered for
8841 // inlining, but that no out-of-line copy of the inline function would be
8842 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008843 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008844 return GVA_AvailableExternally;
8845
Rafael Espindola3ae00052013-05-13 00:12:11 +00008846 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008847 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008848 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008849 }
8850
8851 if (!FD->isInlined())
8852 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008853
David Majnemer3f021502015-10-08 04:53:31 +00008854 if ((!Context.getLangOpts().CPlusPlus &&
8855 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008856 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008857 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008858 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8859
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008860 // GNU or C99 inline semantics. Determine whether this symbol should be
8861 // externally visible.
8862 if (FD->isInlineDefinitionExternallyVisible())
8863 return External;
8864
8865 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008866 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008867 }
8868
David Majnemer54e3ba52014-04-02 23:17:29 +00008869 // Functions specified with extern and inline in -fms-compatibility mode
8870 // forcibly get emitted. While the body of the function cannot be later
8871 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008872 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008873 return GVA_StrongODR;
8874
David Majnemer27d69db2014-04-28 22:17:59 +00008875 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008876}
8877
Artem Belevichca2b9512016-05-02 20:30:03 +00008878static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8879 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008880 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8881 // dllexport/dllimport on inline functions.
8882 if (D->hasAttr<DLLImportAttr>()) {
8883 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8884 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008885 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008886 if (L == GVA_DiscardableODR)
8887 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008888 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8889 D->hasAttr<CUDAGlobalAttr>()) {
8890 // Device-side functions with __global__ attribute must always be
8891 // visible externally so they can be launched from host.
8892 if (L == GVA_DiscardableODR || L == GVA_Internal)
8893 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008894 }
8895 return L;
8896}
8897
8898GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
David Blaikie9ffe5a32017-01-30 05:00:26 +00008899 auto L = adjustGVALinkageForAttributes(
Artem Belevichca2b9512016-05-02 20:30:03 +00008900 *this, basicGVALinkageForFunction(*this, FD), FD);
David Blaikie9ffe5a32017-01-30 05:00:26 +00008901 auto EK = ExternalASTSource::EK_ReplyHazy;
8902 if (auto *Ext = getExternalSource())
David Blaikiee6b7c282017-04-11 20:46:34 +00008903 EK = Ext->hasExternalDefinitions(FD);
David Blaikie9ffe5a32017-01-30 05:00:26 +00008904 switch (EK) {
8905 case ExternalASTSource::EK_Never:
8906 if (L == GVA_DiscardableODR)
8907 return GVA_StrongODR;
8908 break;
8909 case ExternalASTSource::EK_Always:
8910 return GVA_AvailableExternally;
8911 case ExternalASTSource::EK_ReplyHazy:
8912 break;
8913 }
8914 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008915}
8916
8917static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8918 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008919 if (!VD->isExternallyVisible())
8920 return GVA_Internal;
8921
David Majnemer27d69db2014-04-28 22:17:59 +00008922 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00008923 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8924 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8925 LexicalContext = LexicalContext->getLexicalParent();
8926
David Blaikieeb210012017-01-27 23:11:10 +00008927 // ObjC Blocks can create local variables that don't have a FunctionDecl
8928 // LexicalContext.
8929 if (!LexicalContext)
8930 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00008931
David Blaikieeb210012017-01-27 23:11:10 +00008932 // Otherwise, let the static local variable inherit its linkage from the
8933 // nearest enclosing function.
8934 auto StaticLocalLinkage =
8935 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8936
8937 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8938 // be emitted in any object with references to the symbol for the object it
8939 // contains, whether inline or out-of-line."
8940 // Similar behavior is observed with MSVC. An alternative ABI could use
8941 // StrongODR/AvailableExternally to match the function, but none are
8942 // known/supported currently.
8943 if (StaticLocalLinkage == GVA_StrongODR ||
8944 StaticLocalLinkage == GVA_AvailableExternally)
8945 return GVA_DiscardableODR;
8946 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00008947 }
8948
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008949 // MSVC treats in-class initialized static data members as definitions.
8950 // By giving them non-strong linkage, out-of-line definitions won't
8951 // cause link errors.
8952 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8953 return GVA_DiscardableODR;
8954
Richard Smithd9b90092016-07-02 01:32:16 +00008955 // Most non-template variables have strong linkage; inline variables are
8956 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8957 GVALinkage StrongLinkage;
8958 switch (Context.getInlineVariableDefinitionKind(VD)) {
8959 case ASTContext::InlineVariableDefinitionKind::None:
8960 StrongLinkage = GVA_StrongExternal;
8961 break;
8962 case ASTContext::InlineVariableDefinitionKind::Weak:
8963 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008964 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008965 break;
8966 case ASTContext::InlineVariableDefinitionKind::Strong:
8967 StrongLinkage = GVA_StrongODR;
8968 break;
8969 }
Richard Smith62f19e72016-06-25 00:15:56 +00008970
Richard Smith8809a0c2013-09-27 20:14:12 +00008971 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008972 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008973 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008974
David Majnemer6d1780c2015-07-17 23:36:49 +00008975 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008976 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8977 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008978 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008979 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008980
Rafael Espindola3ae00052013-05-13 00:12:11 +00008981 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008982 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008983
David Majnemer27d69db2014-04-28 22:17:59 +00008984 case TSK_ExplicitInstantiationDeclaration:
8985 return GVA_AvailableExternally;
8986
Rafael Espindola3ae00052013-05-13 00:12:11 +00008987 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008988 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008989 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008990
8991 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008992}
8993
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008994GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008995 return adjustGVALinkageForAttributes(
8996 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008997}
8998
David Blaikiee6b7c282017-04-11 20:46:34 +00008999bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009000 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9001 if (!VD->isFileVarDecl())
9002 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009003 // Global named register variables (GNU extension) are never emitted.
9004 if (VD->getStorageClass() == SC_Register)
9005 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009006 if (VD->getDescribedVarTemplate() ||
9007 isa<VarTemplatePartialSpecializationDecl>(VD))
9008 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009009 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9010 // We never need to emit an uninstantiated function template.
9011 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9012 return false;
Nico Weber66220292016-03-02 17:28:48 +00009013 } else if (isa<PragmaCommentDecl>(D))
9014 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009015 else if (isa<OMPThreadPrivateDecl>(D) ||
9016 D->hasAttr<OMPDeclareTargetDeclAttr>())
9017 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009018 else if (isa<PragmaDetectMismatchDecl>(D))
9019 return true;
Nico Weber66220292016-03-02 17:28:48 +00009020 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009021 return !D->getDeclContext()->isDependentContext();
9022 else if (isa<OMPDeclareReductionDecl>(D))
9023 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009024 else if (isa<ImportDecl>(D))
9025 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009026 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009027 return false;
9028
9029 // If this is a member of a class template, we do not need to emit it.
9030 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009031 return false;
9032
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009033 // Weak references don't produce any output by themselves.
9034 if (D->hasAttr<WeakRefAttr>())
9035 return false;
9036
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009037 // Aliases and used decls are required.
9038 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9039 return true;
9040
9041 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9042 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009043 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009044 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009045
9046 // Constructors and destructors are required.
9047 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9048 return true;
9049
John McCall6bd2a892013-01-25 22:31:03 +00009050 // The key function for a class is required. This rule only comes
9051 // into play when inline functions can be key functions, though.
9052 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9053 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9054 const CXXRecordDecl *RD = MD->getParent();
9055 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9056 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9057 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9058 return true;
9059 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009060 }
9061 }
9062
David Blaikie9ffe5a32017-01-30 05:00:26 +00009063 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9064
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009065 // static, static inline, always_inline, and extern inline functions can
9066 // always be deferred. Normal inline functions can be deferred in C99/C++.
9067 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009068 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009069 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009070
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009071 const VarDecl *VD = cast<VarDecl>(D);
9072 assert(VD->isFileVarDecl() && "Expected file scoped var");
9073
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009074 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9075 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009076 return false;
9077
Richard Smitha0e5e542012-11-12 21:38:00 +00009078 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00009079 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00009080 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009081
Richard Smitha0e5e542012-11-12 21:38:00 +00009082 // Variables that have destruction with side-effects are required.
9083 if (VD->getType().isDestructedType())
9084 return true;
9085
9086 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009087 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009088 // We can get a value-dependent initializer during error recovery.
9089 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009090 return true;
9091
Richard Smithda383632016-08-15 01:33:41 +00009092 // Likewise, variables with tuple-like bindings are required if their
9093 // bindings have side-effects.
9094 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9095 for (auto *BD : DD->bindings())
9096 if (auto *BindingVD = BD->getHoldingVar())
9097 if (DeclMustBeEmitted(BindingVD))
9098 return true;
9099
Richard Smitha0e5e542012-11-12 21:38:00 +00009100 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009101}
Charles Davis53c59df2010-08-16 03:33:14 +00009102
Reid Kleckner78af0702013-08-27 23:08:25 +00009103CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9104 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009105 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009106 if (IsCXXMethod)
9107 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009108
Alexey Bataeva7547182016-05-18 09:06:38 +00009109 switch (LangOpts.getDefaultCallingConv()) {
9110 case LangOptions::DCC_None:
9111 break;
9112 case LangOptions::DCC_CDecl:
9113 return CC_C;
9114 case LangOptions::DCC_FastCall:
9115 if (getTargetInfo().hasFeature("sse2"))
9116 return CC_X86FastCall;
9117 break;
9118 case LangOptions::DCC_StdCall:
9119 if (!IsVariadic)
9120 return CC_X86StdCall;
9121 break;
9122 case LangOptions::DCC_VectorCall:
9123 // __vectorcall cannot be applied to variadic functions.
9124 if (!IsVariadic)
9125 return CC_X86VectorCall;
9126 break;
9127 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009128 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009129}
9130
Jay Foad39c79802011-01-12 09:06:06 +00009131bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009132 // Pass through to the C++ ABI object
9133 return ABI->isNearlyEmpty(RD);
9134}
9135
Reid Kleckner96f8f932014-02-05 17:27:08 +00009136VTableContextBase *ASTContext::getVTableContext() {
9137 if (!VTContext.get()) {
9138 if (Target->getCXXABI().isMicrosoft())
9139 VTContext.reset(new MicrosoftVTableContext(*this));
9140 else
9141 VTContext.reset(new ItaniumVTableContext(*this));
9142 }
9143 return VTContext.get();
9144}
9145
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009146MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009147 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009148 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009149 case TargetCXXABI::GenericItanium:
9150 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009151 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009152 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009153 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009154 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009155 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009156 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009157 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009158 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009159 }
David Blaikie83d382b2011-09-23 05:06:16 +00009160 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009161}
9162
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009163CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009164
9165size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009166 return ASTRecordLayouts.getMemorySize() +
9167 llvm::capacity_in_bytes(ObjCLayouts) +
9168 llvm::capacity_in_bytes(KeyFunctions) +
9169 llvm::capacity_in_bytes(ObjCImpls) +
9170 llvm::capacity_in_bytes(BlockVarCopyInits) +
9171 llvm::capacity_in_bytes(DeclAttrs) +
9172 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9173 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9174 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9175 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9176 llvm::capacity_in_bytes(OverriddenMethods) +
9177 llvm::capacity_in_bytes(Types) +
9178 llvm::capacity_in_bytes(VariableArrayTypes) +
9179 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009180}
Ted Kremenek540017e2011-10-06 05:00:56 +00009181
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009182/// getIntTypeForBitwidth -
9183/// sets integer QualTy according to specified details:
9184/// bitwidth, signed/unsigned.
9185/// Returns empty type if there is no appropriate target types.
9186QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9187 unsigned Signed) const {
9188 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9189 CanQualType QualTy = getFromTargetType(Ty);
9190 if (!QualTy && DestWidth == 128)
9191 return Signed ? Int128Ty : UnsignedInt128Ty;
9192 return QualTy;
9193}
9194
9195/// getRealTypeForBitwidth -
9196/// sets floating point QualTy according to specified bitwidth.
9197/// Returns empty type if there is no appropriate target types.
9198QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9199 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9200 switch (Ty) {
9201 case TargetInfo::Float:
9202 return FloatTy;
9203 case TargetInfo::Double:
9204 return DoubleTy;
9205 case TargetInfo::LongDouble:
9206 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009207 case TargetInfo::Float128:
9208 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009209 case TargetInfo::NoFloat:
9210 return QualType();
9211 }
9212
9213 llvm_unreachable("Unhandled TargetInfo::RealType value");
9214}
9215
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009216void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9217 if (Number > 1)
9218 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009219}
9220
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009221unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009222 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009223 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009224}
9225
David Majnemer2206bf52014-03-05 08:57:59 +00009226void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9227 if (Number > 1)
9228 StaticLocalNumbers[VD] = Number;
9229}
9230
9231unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009232 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009233 return I != StaticLocalNumbers.end() ? I->second : 1;
9234}
9235
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009236MangleNumberingContext &
9237ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009238 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009239 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009240 if (!MCtx)
9241 MCtx = createMangleNumberingContext();
9242 return *MCtx;
9243}
9244
Justin Lebar20ebffc2016-10-10 16:26:19 +00009245std::unique_ptr<MangleNumberingContext>
9246ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009247 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009248}
9249
David Majnemere7a818f2015-03-06 18:53:55 +00009250const CXXConstructorDecl *
9251ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9252 return ABI->getCopyConstructorForExceptionObject(
9253 cast<CXXRecordDecl>(RD->getFirstDecl()));
9254}
9255
9256void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9257 CXXConstructorDecl *CD) {
9258 return ABI->addCopyConstructorForExceptionObject(
9259 cast<CXXRecordDecl>(RD->getFirstDecl()),
9260 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9261}
9262
David Majnemer00350522015-08-31 18:48:39 +00009263void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9264 TypedefNameDecl *DD) {
9265 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9266}
9267
9268TypedefNameDecl *
9269ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9270 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9271}
9272
9273void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9274 DeclaratorDecl *DD) {
9275 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9276}
9277
9278DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9279 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9280}
9281
Ted Kremenek540017e2011-10-06 05:00:56 +00009282void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9283 ParamIndices[D] = index;
9284}
9285
9286unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9287 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9288 assert(I != ParamIndices.end() &&
9289 "ParmIndices lacks entry set by ParmVarDecl");
9290 return I->second;
9291}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009292
Richard Smithe6c01442013-06-05 00:46:14 +00009293APValue *
9294ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9295 bool MayCreate) {
9296 assert(E && E->getStorageDuration() == SD_Static &&
9297 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009298 if (MayCreate) {
9299 APValue *&MTVI = MaterializedTemporaryValues[E];
9300 if (!MTVI)
9301 MTVI = new (*this) APValue;
9302 return MTVI;
9303 }
Richard Smithe6c01442013-06-05 00:46:14 +00009304
David Majnemer2dcef9e2015-08-13 23:50:15 +00009305 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009306}
9307
Fariborz Jahanian615de762013-05-28 17:37:39 +00009308bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9309 const llvm::Triple &T = getTargetInfo().getTriple();
9310 if (!T.isOSDarwin())
9311 return false;
9312
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009313 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9314 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9315 return false;
9316
Fariborz Jahanian615de762013-05-28 17:37:39 +00009317 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9318 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9319 uint64_t Size = sizeChars.getQuantity();
9320 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9321 unsigned Align = alignChars.getQuantity();
9322 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9323 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9324}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009325
9326namespace {
9327
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009328ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9329 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009330 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009331 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009332 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009333 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009334 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009335}
9336
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009337/// Template specializations to abstract away from pointers and TypeLocs.
9338/// @{
9339template <typename T>
9340ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9341 return ast_type_traits::DynTypedNode::create(*Node);
9342}
9343template <>
9344ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9345 return ast_type_traits::DynTypedNode::create(Node);
9346}
9347template <>
9348ast_type_traits::DynTypedNode
9349createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9350 return ast_type_traits::DynTypedNode::create(Node);
9351}
9352/// @}
9353
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009354 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9355 /// parents as defined by the \c RecursiveASTVisitor.
9356 ///
9357 /// Note that the relationship described here is purely in terms of AST
9358 /// traversal - there are other relationships (for example declaration context)
9359 /// in the AST that are better modeled by special matchers.
9360 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009361 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009362 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009363 public:
9364 /// \brief Builds and returns the translation unit's parent map.
9365 ///
9366 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009367 static std::pair<ASTContext::ParentMapPointers *,
9368 ASTContext::ParentMapOtherNodes *>
9369 buildMap(TranslationUnitDecl &TU) {
9370 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9371 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009372 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009373 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009374 }
9375
9376 private:
9377 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9378
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009379 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9380 ASTContext::ParentMapOtherNodes *OtherParents)
9381 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009382
9383 bool shouldVisitTemplateInstantiations() const {
9384 return true;
9385 }
9386 bool shouldVisitImplicitCode() const {
9387 return true;
9388 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009389
Richard Smith85838722015-11-24 03:09:01 +00009390 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9391 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009392 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009393 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009394 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009395 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009396 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009397 // FIXME: Currently we add the same parent multiple times, but only
9398 // when no memoization data is available for the type.
9399 // For example when we visit all subexpressions of template
9400 // instantiations; this is suboptimal, but benign: the only way to
9401 // visit those is with hasAncestor / hasParent, and those do not create
9402 // new matches.
9403 // The plan is to enable DynTypedNode to be storable in a map or hash
9404 // map. The main problem there is to implement hash functions /
9405 // comparison operators for all types that DynTypedNode supports that
9406 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009407 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009408 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009409 if (const auto *D = ParentStack.back().get<Decl>())
9410 NodeOrVector = D;
9411 else if (const auto *S = ParentStack.back().get<Stmt>())
9412 NodeOrVector = S;
9413 else
9414 NodeOrVector =
9415 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009416 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009417 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9418 auto *Vector = new ASTContext::ParentVector(
9419 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009420 delete NodeOrVector
9421 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009422 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009423 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009424
9425 auto *Vector =
9426 NodeOrVector.template get<ASTContext::ParentVector *>();
9427 // Skip duplicates for types that have memoization data.
9428 // We must check that the type has memoization data before calling
9429 // std::find() because DynTypedNode::operator== can't compare all
9430 // types.
9431 bool Found = ParentStack.back().getMemoizationData() &&
9432 std::find(Vector->begin(), Vector->end(),
9433 ParentStack.back()) != Vector->end();
9434 if (!Found)
9435 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009436 }
9437 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009438 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009439 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009440 ParentStack.pop_back();
9441 return Result;
9442 }
9443
9444 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009445 return TraverseNode(DeclNode, DeclNode,
9446 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009447 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009448 }
9449
9450 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009451 return TraverseNode(StmtNode, StmtNode,
9452 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009453 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009454 }
9455
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009456 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009457 return TraverseNode(
9458 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9459 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9460 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009461 }
9462
9463 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9464 return TraverseNode(
9465 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009466 [&] {
9467 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9468 },
9469 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009470 }
9471
9472 ASTContext::ParentMapPointers *Parents;
9473 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009474 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9475
9476 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9477 };
9478
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009479} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009480
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009481template <typename NodeTy, typename MapTy>
9482static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9483 const MapTy &Map) {
9484 auto I = Map.find(Node);
9485 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009486 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009487 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009488 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009489 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009490 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009491 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009492}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009493
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009494ASTContext::DynTypedNodeList
9495ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9496 if (!PointerParents) {
9497 // We always need to run over the whole translation unit, as
9498 // hasAncestor can escape any subtree.
9499 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9500 PointerParents.reset(Maps.first);
9501 OtherParents.reset(Maps.second);
9502 }
9503 if (Node.getNodeKind().hasPointerIdentity())
9504 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9505 return getDynNodeFromMap(Node, *OtherParents);
9506}
9507
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009508bool
9509ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9510 const ObjCMethodDecl *MethodImpl) {
9511 // No point trying to match an unavailable/deprecated mothod.
9512 if (MethodDecl->hasAttr<UnavailableAttr>()
9513 || MethodDecl->hasAttr<DeprecatedAttr>())
9514 return false;
9515 if (MethodDecl->getObjCDeclQualifier() !=
9516 MethodImpl->getObjCDeclQualifier())
9517 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009518 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009519 return false;
9520
9521 if (MethodDecl->param_size() != MethodImpl->param_size())
9522 return false;
9523
9524 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9525 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9526 EF = MethodDecl->param_end();
9527 IM != EM && IF != EF; ++IM, ++IF) {
9528 const ParmVarDecl *DeclVar = (*IF);
9529 const ParmVarDecl *ImplVar = (*IM);
9530 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9531 return false;
9532 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9533 return false;
9534 }
9535 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9536
9537}
Richard Smith053f6c62014-05-16 23:01:30 +00009538
Yaxun Liu402804b2016-12-15 08:09:08 +00009539uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9540 unsigned AS;
9541 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9542 AS = 0;
9543 else
9544 AS = QT->getPointeeType().getAddressSpace();
9545
9546 return getTargetInfo().getNullPointerValue(AS);
9547}
9548
Yaxun Liub34ec822017-04-11 17:24:23 +00009549unsigned ASTContext::getTargetAddressSpace(unsigned AS) const {
Yaxun Liu6d96f1632017-05-18 18:51:09 +00009550 if (AS >= LangAS::FirstTargetAddressSpace)
9551 return AS - LangAS::FirstTargetAddressSpace;
Yaxun Liub34ec822017-04-11 17:24:23 +00009552 else
9553 return (*AddrSpaceMap)[AS];
9554}
9555
Richard Smith053f6c62014-05-16 23:01:30 +00009556// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9557// doesn't include ASTContext.h
9558template
9559clang::LazyGenerationalUpdatePtr<
9560 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9561clang::LazyGenerationalUpdatePtr<
9562 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9563 const clang::ASTContext &Ctx, Decl *Value);