blob: d9b0d390808039963dad16ebf1e6cddeae1b5b04 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000635 ExpandedTypes,
636 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000656 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000657
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000661 TTP->getPosition(),
662 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000663 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000666 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000667 SourceLocation(),
668 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000672 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
Charles Davis53c59df2010-08-16 03:33:14 +0000681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000682 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000687 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000688 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000689 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000690 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000693 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000694 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000695 return CreateMicrosoftCXXABI(*this);
696 }
David Blaikie8a40f702012-01-17 06:56:22 +0000697 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000698}
699
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
706 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000707 3, // opencl_local
708 2, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000709 4, // opencl_generic
710 5, // cuda_device
711 6, // cuda_constant
712 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000715 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000717 }
718}
719
David Tweed31d09b02013-09-13 12:04:22 +0000720static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
721 const LangOptions &LangOpts) {
722 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000723 case LangOptions::ASMM_Target:
724 return TI.useAddressSpaceMapMangling();
725 case LangOptions::ASMM_On:
726 return true;
727 case LangOptions::ASMM_Off:
728 return false;
729 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000730 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000731}
732
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000733ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000734 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000735 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000736 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
737 DependentTemplateSpecializationTypes(this_()),
738 SubstTemplateTemplateParmPacks(this_()),
739 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000740 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
741 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
742 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000743 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
744 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
745 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
746 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
747 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000748 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
749 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000750 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000751 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
752 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
753 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
754 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000755 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000756 TUDecl = TranslationUnitDecl::Create(*this);
757}
758
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000759ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000760 ReleaseParentMapEntries();
761
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000762 // Release the DenseMaps associated with DeclContext objects.
763 // FIXME: Is this the ideal solution?
764 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000765
Manuel Klimeka7328992013-06-03 13:51:33 +0000766 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000767 for (auto &Pair : Deallocations)
768 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
David Majnemere694f3e2015-08-14 14:43:50 +0000791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
794
Richard Smith423f46f2016-07-20 21:38:26 +0000795 for (const auto &Value : ModuleInitializers)
796 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000797}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000798
Manuel Klimek95403e62014-05-21 13:28:59 +0000799void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000800 if (!PointerParents) return;
801 for (const auto &Entry : *PointerParents) {
802 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
803 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
804 } else if (Entry.second.is<ParentVector *>()) {
805 delete Entry.second.get<ParentVector *>();
806 }
807 }
808 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000809 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
810 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000811 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000812 delete Entry.second.get<ParentVector *>();
813 }
814 }
815}
816
Douglas Gregor1a809332010-05-23 18:26:36 +0000817void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000818 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000819}
820
Mike Stump11289f42009-09-09 15:08:12 +0000821void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000822ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000823 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000824}
825
Chris Lattner4eb445d2007-01-26 01:27:23 +0000826void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000827 llvm::errs() << "\n*** AST Context Stats:\n";
828 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000829
Douglas Gregora30d0462009-05-26 14:40:08 +0000830 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000831#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000832#define ABSTRACT_TYPE(Name, Parent)
833#include "clang/AST/TypeNodes.def"
834 0 // Extra
835 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000836
Chris Lattner4eb445d2007-01-26 01:27:23 +0000837 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
838 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000839 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000840 }
841
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 unsigned Idx = 0;
843 unsigned TotalBytes = 0;
844#define TYPE(Name, Parent) \
845 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << " " << counts[Idx] << " " << #Name \
847 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000848 TotalBytes += counts[Idx] * sizeof(Name##Type); \
849 ++Idx;
850#define ABSTRACT_TYPE(Name, Parent)
851#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
854
Douglas Gregor7454c562010-07-02 20:37:36 +0000855 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
857 << NumImplicitDefaultConstructors
858 << " implicit default constructors created\n";
859 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
860 << NumImplicitCopyConstructors
861 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000862 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000863 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
864 << NumImplicitMoveConstructors
865 << " implicit move constructors created\n";
866 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
867 << NumImplicitCopyAssignmentOperators
868 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000870 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
871 << NumImplicitMoveAssignmentOperators
872 << " implicit move assignment operators created\n";
873 llvm::errs() << NumImplicitDestructorsDeclared << "/"
874 << NumImplicitDestructors
875 << " implicit destructors created\n";
876
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000877 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000878 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000879 ExternalSource->PrintStats();
880 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000881
Douglas Gregor5b11d492010-07-25 17:53:33 +0000882 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000883}
884
Richard Smith42413142015-05-15 20:05:43 +0000885void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
886 bool NotifyListeners) {
887 if (NotifyListeners)
888 if (auto *Listener = getASTMutationListener())
889 Listener->RedefinedHiddenDefinition(ND, M);
890
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000891 if (getLangOpts().ModulesLocalVisibility)
892 MergedDefModules[ND].push_back(M);
893 else
Richard Smith42413142015-05-15 20:05:43 +0000894 ND->setHidden(false);
895}
896
897void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
898 auto It = MergedDefModules.find(ND);
899 if (It == MergedDefModules.end())
900 return;
901
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000902 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000903 llvm::DenseSet<Module*> Found;
904 for (Module *&M : Merged)
905 if (!Found.insert(M).second)
906 M = nullptr;
907 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
908}
909
Richard Smithdc1f0422016-07-20 19:10:16 +0000910void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
911 if (LazyInitializers.empty())
912 return;
913
914 auto *Source = Ctx.getExternalSource();
915 assert(Source && "lazy initializers but no external source");
916
917 auto LazyInits = std::move(LazyInitializers);
918 LazyInitializers.clear();
919
920 for (auto ID : LazyInits)
921 Initializers.push_back(Source->GetExternalDecl(ID));
922
923 assert(LazyInitializers.empty() &&
924 "GetExternalDecl for lazy module initializer added more inits");
925}
926
927void ASTContext::addModuleInitializer(Module *M, Decl *D) {
928 // One special case: if we add a module initializer that imports another
929 // module, and that module's only initializer is an ImportDecl, simplify.
930 if (auto *ID = dyn_cast<ImportDecl>(D)) {
931 auto It = ModuleInitializers.find(ID->getImportedModule());
932
933 // Maybe the ImportDecl does nothing at all. (Common case.)
934 if (It == ModuleInitializers.end())
935 return;
936
937 // Maybe the ImportDecl only imports another ImportDecl.
938 auto &Imported = *It->second;
939 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
940 Imported.resolve(*this);
941 auto *OnlyDecl = Imported.Initializers.front();
942 if (isa<ImportDecl>(OnlyDecl))
943 D = OnlyDecl;
944 }
945 }
946
947 auto *&Inits = ModuleInitializers[M];
948 if (!Inits)
949 Inits = new (*this) PerModuleInitializers;
950 Inits->Initializers.push_back(D);
951}
952
953void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
954 auto *&Inits = ModuleInitializers[M];
955 if (!Inits)
956 Inits = new (*this) PerModuleInitializers;
957 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
958 IDs.begin(), IDs.end());
959}
960
961ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
962 auto It = ModuleInitializers.find(M);
963 if (It == ModuleInitializers.end())
964 return None;
965
966 auto *Inits = It->second;
967 Inits->resolve(*this);
968 return Inits->Initializers;
969}
970
Richard Smithf19e1272015-03-07 00:04:49 +0000971ExternCContextDecl *ASTContext::getExternCContextDecl() const {
972 if (!ExternCContext)
973 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
974
975 return ExternCContext;
976}
977
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000978BuiltinTemplateDecl *
979ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
980 const IdentifierInfo *II) const {
981 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
982 BuiltinTemplate->setImplicit();
983 TUDecl->addDecl(BuiltinTemplate);
984
985 return BuiltinTemplate;
986}
987
988BuiltinTemplateDecl *
989ASTContext::getMakeIntegerSeqDecl() const {
990 if (!MakeIntegerSeqDecl)
991 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
992 getMakeIntegerSeqName());
993 return MakeIntegerSeqDecl;
994}
995
Eric Fiselier6ad68552016-07-01 01:24:09 +0000996BuiltinTemplateDecl *
997ASTContext::getTypePackElementDecl() const {
998 if (!TypePackElementDecl)
999 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1000 getTypePackElementName());
1001 return TypePackElementDecl;
1002}
1003
Alp Toker2dea15b2013-12-17 01:22:38 +00001004RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1005 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001006 SourceLocation Loc;
1007 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001008 if (getLangOpts().CPlusPlus)
1009 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1010 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001011 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001012 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1013 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001015 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1016 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001017 return NewDecl;
1018}
1019
1020TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1021 StringRef Name) const {
1022 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1023 TypedefDecl *NewDecl = TypedefDecl::Create(
1024 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1025 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1026 NewDecl->setImplicit();
1027 return NewDecl;
1028}
1029
Douglas Gregor801c99d2011-08-12 06:49:56 +00001030TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001031 if (!Int128Decl)
1032 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033 return Int128Decl;
1034}
1035
1036TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001037 if (!UInt128Decl)
1038 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001039 return UInt128Decl;
1040}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001041
John McCall48f2d582009-10-23 23:03:21 +00001042void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001043 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001044 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001045 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001046}
1047
Artem Belevichb5bc9232015-09-22 17:23:22 +00001048void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1049 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001050 assert((!this->Target || this->Target == &Target) &&
1051 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001052 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001053
Douglas Gregore8bbc122011-09-02 00:18:52 +00001054 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001055 this->AuxTarget = AuxTarget;
1056
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 ABI.reset(createCXXABI(Target));
1058 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001059 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060
Chris Lattner970e54e2006-11-12 00:37:36 +00001061 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001062 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner970e54e2006-11-12 00:37:36 +00001064 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001065 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001066 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001067 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001068 InitBuiltinType(CharTy, BuiltinType::Char_S);
1069 else
1070 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001071 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001072 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1073 InitBuiltinType(ShortTy, BuiltinType::Short);
1074 InitBuiltinType(IntTy, BuiltinType::Int);
1075 InitBuiltinType(LongTy, BuiltinType::Long);
1076 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattner970e54e2006-11-12 00:37:36 +00001078 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001079 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1080 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1081 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1082 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1083 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Chris Lattner970e54e2006-11-12 00:37:36 +00001085 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001086 InitBuiltinType(FloatTy, BuiltinType::Float);
1087 InitBuiltinType(DoubleTy, BuiltinType::Double);
1088 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001089
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001090 // GNU extension, __float128 for IEEE quadruple precision
1091 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1092
Chris Lattnerf122cef2009-04-30 02:43:43 +00001093 // GNU extension, 128-bit integers.
1094 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1095 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1096
Hans Wennborg0d81e012013-05-10 10:08:40 +00001097 // C++ 3.9.1p5
1098 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1099 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1100 else // -fshort-wchar makes wchar_t be unsigned.
1101 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1102 if (LangOpts.CPlusPlus && LangOpts.WChar)
1103 WideCharTy = WCharTy;
1104 else {
1105 // C99 (or C++ using -fno-wchar).
1106 WideCharTy = getFromTargetType(Target.getWCharType());
1107 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001108
James Molloy36365542012-05-04 10:55:22 +00001109 WIntTy = getFromTargetType(Target.getWIntType());
1110
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001111 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1112 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1113 else // C99
1114 Char16Ty = getFromTargetType(Target.getChar16Type());
1115
1116 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1117 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1118 else // C99
1119 Char32Ty = getFromTargetType(Target.getChar32Type());
1120
Douglas Gregor4619e432008-12-05 23:32:09 +00001121 // Placeholder type for type-dependent expressions whose type is
1122 // completely unknown. No code should ever check a type against
1123 // DependentTy and users should never see it; however, it is here to
1124 // help diagnose failures to properly check for type-dependent
1125 // expressions.
1126 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127
John McCall36e7fe32010-10-12 00:20:44 +00001128 // Placeholder type for functions.
1129 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1130
John McCall0009fcc2011-04-26 20:42:42 +00001131 // Placeholder type for bound members.
1132 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1133
John McCall526ab472011-10-25 17:37:35 +00001134 // Placeholder type for pseudo-objects.
1135 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1136
John McCall31996342011-04-07 08:22:57 +00001137 // "any" type; useful for debugger-like clients.
1138 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1139
John McCall8a6b59a2011-10-17 18:09:15 +00001140 // Placeholder type for unbridged ARC casts.
1141 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1142
Eli Friedman34866c72012-08-31 00:14:07 +00001143 // Placeholder type for builtin functions.
1144 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1145
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001146 // Placeholder type for OMP array sections.
1147 if (LangOpts.OpenMP)
1148 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1149
Chris Lattner970e54e2006-11-12 00:37:36 +00001150 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001151 FloatComplexTy = getComplexType(FloatTy);
1152 DoubleComplexTy = getComplexType(DoubleTy);
1153 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001154 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001155
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001156 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001157 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1158 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001159 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001160
Alexey Bader954ba212016-04-08 13:40:33 +00001161 if (LangOpts.OpenCL) {
1162#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1163 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001164#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001165
Guy Benyei61054192013-02-07 10:55:47 +00001166 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001167 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001168 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1169 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1170 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1171 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001172 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001173
1174 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001175 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1176 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001177
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001178 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001179
1180 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001181
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001182 // void * type
1183 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001184
1185 // nullptr type (C++0x 2.14.7)
1186 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001187
1188 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1189 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001190
1191 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001192 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001193}
1194
David Blaikie9c902b52011-09-25 23:23:43 +00001195DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001196 return SourceMgr.getDiagnostics();
1197}
1198
Douglas Gregor561eceb2010-08-30 16:49:28 +00001199AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1200 AttrVec *&Result = DeclAttrs[D];
1201 if (!Result) {
1202 void *Mem = Allocate(sizeof(AttrVec));
1203 Result = new (Mem) AttrVec;
1204 }
1205
1206 return *Result;
1207}
1208
1209/// \brief Erase the attributes corresponding to the given declaration.
1210void ASTContext::eraseDeclAttrs(const Decl *D) {
1211 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1212 if (Pos != DeclAttrs.end()) {
1213 Pos->second->~AttrVec();
1214 DeclAttrs.erase(Pos);
1215 }
1216}
1217
Larisse Voufo39a1e502013-08-06 01:03:05 +00001218// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001219MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001220ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001221 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001222 return getTemplateOrSpecializationInfo(Var)
1223 .dyn_cast<MemberSpecializationInfo *>();
1224}
1225
1226ASTContext::TemplateOrSpecializationInfo
1227ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1228 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1229 TemplateOrInstantiation.find(Var);
1230 if (Pos == TemplateOrInstantiation.end())
1231 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001232
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001233 return Pos->second;
1234}
1235
Mike Stump11289f42009-09-09 15:08:12 +00001236void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001237ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001238 TemplateSpecializationKind TSK,
1239 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001240 assert(Inst->isStaticDataMember() && "Not a static data member");
1241 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001242 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1243 Tmpl, TSK, PointOfInstantiation));
1244}
1245
1246void
1247ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1248 TemplateOrSpecializationInfo TSI) {
1249 assert(!TemplateOrInstantiation[Inst] &&
1250 "Already noted what the variable was instantiated from");
1251 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001252}
1253
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001254FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1255 const FunctionDecl *FD){
1256 assert(FD && "Specialization is 0");
1257 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001258 = ClassScopeSpecializationPattern.find(FD);
1259 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001260 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001261
1262 return Pos->second;
1263}
1264
1265void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1266 FunctionDecl *Pattern) {
1267 assert(FD && "Specialization is 0");
1268 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001269 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001270}
1271
John McCalle61f2ba2009-11-18 02:36:19 +00001272NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001273ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1274 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001275 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001276 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001277
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001278 return Pos->second;
1279}
1280
1281void
Richard Smithd8a9e372016-12-18 21:39:37 +00001282ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001283 assert((isa<UsingDecl>(Pattern) ||
1284 isa<UnresolvedUsingValueDecl>(Pattern) ||
1285 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1286 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001287 assert((isa<UsingDecl>(Inst) ||
1288 isa<UnresolvedUsingValueDecl>(Inst) ||
1289 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1290 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001291 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1292 InstantiatedFromUsingDecl[Inst] = Pattern;
1293}
1294
1295UsingShadowDecl *
1296ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1297 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1298 = InstantiatedFromUsingShadowDecl.find(Inst);
1299 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001300 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001301
1302 return Pos->second;
1303}
1304
1305void
1306ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1307 UsingShadowDecl *Pattern) {
1308 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1309 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001310}
1311
Anders Carlsson5da84842009-09-01 04:26:58 +00001312FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1313 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1314 = InstantiatedFromUnnamedFieldDecl.find(Field);
1315 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001316 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001317
Anders Carlsson5da84842009-09-01 04:26:58 +00001318 return Pos->second;
1319}
1320
1321void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1322 FieldDecl *Tmpl) {
1323 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1324 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1325 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1326 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001327
Anders Carlsson5da84842009-09-01 04:26:58 +00001328 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1329}
1330
Douglas Gregor832940b2010-03-02 23:58:15 +00001331ASTContext::overridden_cxx_method_iterator
1332ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001333 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1334 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001335 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001336 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001337 return Pos->second.begin();
1338}
1339
1340ASTContext::overridden_cxx_method_iterator
1341ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001342 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1343 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001344 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001345 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001346 return Pos->second.end();
1347}
1348
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001349unsigned
1350ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001351 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1352 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001353 if (Pos == OverriddenMethods.end())
1354 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001355 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001356}
1357
Clement Courbet6ecaec82016-07-05 07:49:31 +00001358ASTContext::overridden_method_range
1359ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1360 return overridden_method_range(overridden_methods_begin(Method),
1361 overridden_methods_end(Method));
1362}
1363
Douglas Gregor832940b2010-03-02 23:58:15 +00001364void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1365 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001366 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001367 OverriddenMethods[Method].push_back(Overridden);
1368}
1369
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001370void ASTContext::getOverriddenMethods(
1371 const NamedDecl *D,
1372 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001373 assert(D);
1374
1375 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001376 Overridden.append(overridden_methods_begin(CXXMethod),
1377 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001378 return;
1379 }
1380
1381 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1382 if (!Method)
1383 return;
1384
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001385 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1386 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001387 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001388}
1389
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001390void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1391 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1392 assert(!Import->isFromASTFile() && "Non-local import declaration");
1393 if (!FirstLocalImport) {
1394 FirstLocalImport = Import;
1395 LastLocalImport = Import;
1396 return;
1397 }
1398
1399 LastLocalImport->NextLocalImport = Import;
1400 LastLocalImport = Import;
1401}
1402
Chris Lattner53cfe802007-07-18 17:52:12 +00001403//===----------------------------------------------------------------------===//
1404// Type Sizing and Analysis
1405//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001406
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001407/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1408/// scalar floating point type.
1409const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001410 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001411 assert(BT && "Not a floating point type!");
1412 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001413 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001414 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001415 case BuiltinType::Float: return Target->getFloatFormat();
1416 case BuiltinType::Double: return Target->getDoubleFormat();
1417 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001418 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001419 }
1420}
1421
Rafael Espindola71eccb32013-08-08 19:53:46 +00001422CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001423 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001424
John McCall94268702010-10-08 18:24:19 +00001425 bool UseAlignAttrOnly = false;
1426 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1427 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001428
John McCall94268702010-10-08 18:24:19 +00001429 // __attribute__((aligned)) can increase or decrease alignment
1430 // *except* on a struct or struct member, where it only increases
1431 // alignment unless 'packed' is also specified.
1432 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001433 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001434 // ignore that possibility; Sema should diagnose it.
1435 if (isa<FieldDecl>(D)) {
1436 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1437 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1438 } else {
1439 UseAlignAttrOnly = true;
1440 }
1441 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001442 else if (isa<FieldDecl>(D))
1443 UseAlignAttrOnly =
1444 D->hasAttr<PackedAttr>() ||
1445 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001446
John McCall4e819612011-01-20 07:57:12 +00001447 // If we're using the align attribute only, just ignore everything
1448 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001449 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001450 // do nothing
1451
John McCall94268702010-10-08 18:24:19 +00001452 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001453 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001454 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001455 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001456 T = RT->getPointeeType();
1457 else
1458 T = getPointerType(RT->getPointeeType());
1459 }
Richard Smithf6d70302014-06-10 23:34:28 +00001460 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001461 if (T->isFunctionType())
1462 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1463 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001464 // Adjust alignments of declarations with array type by the
1465 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001466 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001467 unsigned MinWidth = Target->getLargeArrayMinWidth();
1468 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001469 if (isa<VariableArrayType>(arrayType))
1470 Align = std::max(Align, Target->getLargeArrayAlign());
1471 else if (isa<ConstantArrayType>(arrayType) &&
1472 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1473 Align = std::max(Align, Target->getLargeArrayAlign());
1474 }
John McCall33ddac02011-01-19 10:06:00 +00001475 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001476 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001477 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001478 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001479 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1480 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001481 }
John McCall4e819612011-01-20 07:57:12 +00001482
1483 // Fields can be subject to extra alignment constraints, like if
1484 // the field is packed, the struct is packed, or the struct has a
1485 // a max-field-alignment constraint (#pragma pack). So calculate
1486 // the actual alignment of the field within the struct, and then
1487 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001488 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1489 const RecordDecl *Parent = Field->getParent();
1490 // We can only produce a sensible answer if the record is valid.
1491 if (!Parent->isInvalidDecl()) {
1492 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001493
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001494 // Start with the record's overall alignment.
1495 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001496
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001497 // Use the GCD of that and the offset within the record.
1498 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1499 if (Offset > 0) {
1500 // Alignment is always a power of 2, so the GCD will be a power of 2,
1501 // which means we get to do this crazy thing instead of Euclid's.
1502 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1503 if (LowBitOfOffset < FieldAlign)
1504 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1505 }
1506
1507 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001508 }
Charles Davis3fc51072010-02-23 04:52:00 +00001509 }
Chris Lattner68061312009-01-24 21:53:27 +00001510 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001511
Ken Dyckcc56c542011-01-15 18:38:59 +00001512 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001513}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001514
John McCallf1249922012-08-21 04:10:00 +00001515// getTypeInfoDataSizeInChars - Return the size of a type, in
1516// chars. If the type is a record, its data size is returned. This is
1517// the size of the memcpy that's performed when assigning this type
1518// using a trivial copy/move assignment operator.
1519std::pair<CharUnits, CharUnits>
1520ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1521 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1522
1523 // In C++, objects can sometimes be allocated into the tail padding
1524 // of a base-class subobject. We decide whether that's possible
1525 // during class layout, so here we can just trust the layout results.
1526 if (getLangOpts().CPlusPlus) {
1527 if (const RecordType *RT = T->getAs<RecordType>()) {
1528 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1529 sizeAndAlign.first = layout.getDataSize();
1530 }
1531 }
1532
1533 return sizeAndAlign;
1534}
1535
Richard Trieu04d2d942013-05-14 21:59:17 +00001536/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1537/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1538std::pair<CharUnits, CharUnits>
1539static getConstantArrayInfoInChars(const ASTContext &Context,
1540 const ConstantArrayType *CAT) {
1541 std::pair<CharUnits, CharUnits> EltInfo =
1542 Context.getTypeInfoInChars(CAT->getElementType());
1543 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001544 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1545 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001546 "Overflow in array type char size evaluation");
1547 uint64_t Width = EltInfo.first.getQuantity() * Size;
1548 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001549 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1550 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001551 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001552 return std::make_pair(CharUnits::fromQuantity(Width),
1553 CharUnits::fromQuantity(Align));
1554}
1555
John McCall87fe5d52010-05-20 01:18:31 +00001556std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001557ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001558 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1559 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001560 TypeInfo Info = getTypeInfo(T);
1561 return std::make_pair(toCharUnitsFromBits(Info.Width),
1562 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001563}
1564
1565std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001566ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001567 return getTypeInfoInChars(T.getTypePtr());
1568}
1569
David Majnemer34b57492014-07-30 01:30:47 +00001570bool ASTContext::isAlignmentRequired(const Type *T) const {
1571 return getTypeInfo(T).AlignIsRequired;
1572}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001573
David Majnemer34b57492014-07-30 01:30:47 +00001574bool ASTContext::isAlignmentRequired(QualType T) const {
1575 return isAlignmentRequired(T.getTypePtr());
1576}
1577
Richard Smithb2f0f052016-10-10 18:54:32 +00001578unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1579 // An alignment on a typedef overrides anything else.
1580 if (auto *TT = T->getAs<TypedefType>())
1581 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1582 return Align;
1583
1584 // If we have an (array of) complete type, we're done.
1585 T = getBaseElementType(T);
1586 if (!T->isIncompleteType())
1587 return getTypeAlign(T);
1588
1589 // If we had an array type, its element type might be a typedef
1590 // type with an alignment attribute.
1591 if (auto *TT = T->getAs<TypedefType>())
1592 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1593 return Align;
1594
1595 // Otherwise, see if the declaration of the type had an attribute.
1596 if (auto *TT = T->getAs<TagType>())
1597 return TT->getDecl()->getMaxAlignment();
1598
1599 return 0;
1600}
1601
David Majnemer34b57492014-07-30 01:30:47 +00001602TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001603 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1604 if (I != MemoizedTypeInfo.end())
1605 return I->second;
1606
1607 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1608 TypeInfo TI = getTypeInfoImpl(T);
1609 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001610 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001611}
1612
1613/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1614/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001615///
1616/// FIXME: Pointers into different addr spaces could have different sizes and
1617/// alignment requirements: getPointerInfo should take an AddrSpace, this
1618/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001619TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1620 uint64_t Width = 0;
1621 unsigned Align = 8;
1622 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001623 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001624#define TYPE(Class, Base)
1625#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001626#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001627#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001628#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1629 case Type::Class: \
1630 assert(!T->isDependentType() && "should not see dependent types here"); \
1631 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001632#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001633 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001634
Chris Lattner355332d2007-07-13 22:27:08 +00001635 case Type::FunctionNoProto:
1636 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001637 // GCC extension: alignof(function) = 32 bits
1638 Width = 0;
1639 Align = 32;
1640 break;
1641
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001642 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001643 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001644 Width = 0;
1645 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1646 break;
1647
Steve Naroff5c131802007-08-30 01:06:46 +00001648 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001649 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001650
David Majnemer34b57492014-07-30 01:30:47 +00001651 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001652 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001653 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001654 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001655 Width = EltInfo.Width * Size;
1656 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001657 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1658 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001659 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001660 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001661 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001662 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001663 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001664 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001665 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1666 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001667 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001668 // If the alignment is not a power of 2, round up to the next power of 2.
1669 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001670 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001671 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001672 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001673 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001674 // Adjust the alignment based on the target max.
1675 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1676 if (TargetVectorAlign && TargetVectorAlign < Align)
1677 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001678 break;
1679 }
Chris Lattner647fb222007-07-18 18:26:58 +00001680
Chris Lattner7570e9c2008-03-08 08:52:55 +00001681 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001682 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001683 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001684 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001685 // GCC extension: alignof(void) = 8 bits.
1686 Width = 0;
1687 Align = 8;
1688 break;
1689
Chris Lattner6a4f7452007-12-19 19:23:28 +00001690 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001691 Width = Target->getBoolWidth();
1692 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001693 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001694 case BuiltinType::Char_S:
1695 case BuiltinType::Char_U:
1696 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001697 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001698 Width = Target->getCharWidth();
1699 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001700 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001701 case BuiltinType::WChar_S:
1702 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001703 Width = Target->getWCharWidth();
1704 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001705 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001706 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Width = Target->getChar16Width();
1708 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001709 break;
1710 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001711 Width = Target->getChar32Width();
1712 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001713 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001714 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001715 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001716 Width = Target->getShortWidth();
1717 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001718 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001719 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001720 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001721 Width = Target->getIntWidth();
1722 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001723 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001724 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001725 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001726 Width = Target->getLongWidth();
1727 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001728 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001729 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001730 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001731 Width = Target->getLongLongWidth();
1732 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001733 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001734 case BuiltinType::Int128:
1735 case BuiltinType::UInt128:
1736 Width = 128;
1737 Align = 128; // int128_t is 128-bit aligned on all targets.
1738 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001739 case BuiltinType::Half:
1740 Width = Target->getHalfWidth();
1741 Align = Target->getHalfAlign();
1742 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001743 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001744 Width = Target->getFloatWidth();
1745 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001746 break;
1747 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001748 Width = Target->getDoubleWidth();
1749 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001750 break;
1751 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001752 Width = Target->getLongDoubleWidth();
1753 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001754 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001755 case BuiltinType::Float128:
1756 Width = Target->getFloat128Width();
1757 Align = Target->getFloat128Align();
1758 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001759 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001760 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1761 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001762 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001763 case BuiltinType::ObjCId:
1764 case BuiltinType::ObjCClass:
1765 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001766 Width = Target->getPointerWidth(0);
1767 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001768 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001769 case BuiltinType::OCLSampler: {
1770 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1771 Width = Target->getPointerWidth(AS);
1772 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001773 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001774 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001775 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001776 case BuiltinType::OCLClkEvent:
1777 case BuiltinType::OCLQueue:
1778 case BuiltinType::OCLNDRange:
1779 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001780 // Currently these types are pointers to opaque types.
1781 Width = Target->getPointerWidth(0);
1782 Align = Target->getPointerAlign(0);
1783 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001784#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1785 case BuiltinType::Id:
1786#include "clang/Basic/OpenCLImageTypes.def"
1787 {
1788 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1789 Width = Target->getPointerWidth(AS);
1790 Align = Target->getPointerAlign(AS);
1791 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001792 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001793 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001794 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001795 Width = Target->getPointerWidth(0);
1796 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001797 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001798 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001799 unsigned AS = getTargetAddressSpace(
1800 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001801 Width = Target->getPointerWidth(AS);
1802 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001803 break;
1804 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001805 case Type::LValueReference:
1806 case Type::RValueReference: {
1807 // alignof and sizeof should never enter this code path here, so we go
1808 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001809 unsigned AS = getTargetAddressSpace(
1810 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001811 Width = Target->getPointerWidth(AS);
1812 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001813 break;
1814 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001815 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001816 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001817 Width = Target->getPointerWidth(AS);
1818 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001819 break;
1820 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001821 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001822 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001823 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001824 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001825 }
Chris Lattner647fb222007-07-18 18:26:58 +00001826 case Type::Complex: {
1827 // Complex types have the same alignment as their elements, but twice the
1828 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001829 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1830 Width = EltInfo.Width * 2;
1831 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001832 break;
1833 }
John McCall8b07ec22010-05-15 11:32:37 +00001834 case Type::ObjCObject:
1835 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001836 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001837 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001838 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001839 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001840 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001841 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001842 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001843 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001844 break;
1845 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001846 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001847 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001848 const TagType *TT = cast<TagType>(T);
1849
1850 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001851 Width = 8;
1852 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001853 break;
1854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
David Majnemer475b25e2015-01-21 10:54:38 +00001856 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1857 const EnumDecl *ED = ET->getDecl();
1858 TypeInfo Info =
1859 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1860 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1861 Info.Align = AttrAlign;
1862 Info.AlignIsRequired = true;
1863 }
1864 return Info;
1865 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001866
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001867 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001868 const RecordDecl *RD = RT->getDecl();
1869 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001870 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001871 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001872 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001873 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001874 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001875
Chris Lattner63d2b362009-10-22 05:17:15 +00001876 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001877 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1878 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001879
Richard Smith30482bc2011-02-20 03:19:35 +00001880 case Type::Auto: {
1881 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001882 assert(!A->getDeducedType().isNull() &&
1883 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001884 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001885 }
1886
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001887 case Type::Paren:
1888 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1889
Manman Rene6be26c2016-09-13 17:25:08 +00001890 case Type::ObjCTypeParam:
1891 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1892
Douglas Gregoref462e62009-04-30 17:32:17 +00001893 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001894 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001895 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001896 // If the typedef has an aligned attribute on it, it overrides any computed
1897 // alignment we have. This violates the GCC documentation (which says that
1898 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001899 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001900 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001901 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001902 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001903 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001904 AlignIsRequired = Info.AlignIsRequired;
1905 }
David Majnemer34b57492014-07-30 01:30:47 +00001906 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001907 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001908 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001909
Abramo Bagnara6150c882010-05-11 21:36:43 +00001910 case Type::Elaborated:
1911 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001912
John McCall81904512011-01-06 01:58:22 +00001913 case Type::Attributed:
1914 return getTypeInfo(
1915 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1916
Eli Friedman0dfb8892011-10-06 23:00:33 +00001917 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001918 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001919 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1920 Width = Info.Width;
1921 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001922
1923 // If the size of the type doesn't exceed the platform's max
1924 // atomic promotion width, make the size and alignment more
1925 // favorable to atomic operations:
1926 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1927 // Round the size up to a power of 2.
1928 if (!llvm::isPowerOf2_64(Width))
1929 Width = llvm::NextPowerOf2(Width);
1930
1931 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001932 Align = static_cast<unsigned>(Width);
1933 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001934 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001935 break;
1936
1937 case Type::Pipe: {
1938 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1939 Width = Info.Width;
1940 Align = Info.Align;
1941 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001942
Douglas Gregoref462e62009-04-30 17:32:17 +00001943 }
Mike Stump11289f42009-09-09 15:08:12 +00001944
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001945 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001946 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001947}
1948
Alexey Bataev00396512015-07-02 03:40:19 +00001949unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1950 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1951 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1952 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1953 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1954 getTargetInfo().getABI() == "elfv1-qpx" &&
1955 T->isSpecificBuiltinType(BuiltinType::Double))
1956 SimdAlign = 256;
1957 return SimdAlign;
1958}
1959
Ken Dyckcc56c542011-01-15 18:38:59 +00001960/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1961CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1962 return CharUnits::fromQuantity(BitSize / getCharWidth());
1963}
1964
Ken Dyckb0fcc592011-02-11 01:54:29 +00001965/// toBits - Convert a size in characters to a size in characters.
1966int64_t ASTContext::toBits(CharUnits CharSize) const {
1967 return CharSize.getQuantity() * getCharWidth();
1968}
1969
Ken Dyck8c89d592009-12-22 14:23:30 +00001970/// getTypeSizeInChars - Return the size of the specified type, in characters.
1971/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001972CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001973 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001974}
Jay Foad39c79802011-01-12 09:06:06 +00001975CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001976 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001977}
1978
Ken Dycka6046ab2010-01-26 17:25:18 +00001979/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001980/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001981CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001982 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001983}
Jay Foad39c79802011-01-12 09:06:06 +00001984CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001985 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001986}
1987
Chris Lattnera3402cd2009-01-27 18:08:34 +00001988/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1989/// type for the current target in bits. This can be different than the ABI
1990/// alignment in cases where it is beneficial for performance to overalign
1991/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001992unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001993 TypeInfo TI = getTypeInfo(T);
1994 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001995
David Majnemere1544562015-04-24 01:25:05 +00001996 T = T->getBaseElementTypeUnsafe();
1997
1998 // The preferred alignment of member pointers is that of a pointer.
1999 if (T->isMemberPointerType())
2000 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2001
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002002 if (!Target->allowsLargerPreferedTypeAlignment())
2003 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002004
Eli Friedman7ab09572009-05-25 21:27:19 +00002005 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002006 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002007 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002008 if (const EnumType *ET = T->getAs<EnumType>())
2009 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002010 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002011 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2012 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002013 // Don't increase the alignment if an alignment attribute was specified on a
2014 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002015 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002016 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002017
Chris Lattnera3402cd2009-01-27 18:08:34 +00002018 return ABIAlign;
2019}
2020
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002021/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2022/// for __attribute__((aligned)) on this target, to be used if no alignment
2023/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002024unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002025 return getTargetInfo().getDefaultAlignForAttributeAligned();
2026}
2027
Ulrich Weigandfa806422013-05-06 16:23:57 +00002028/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2029/// to a global variable of the specified type.
2030unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2031 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2032}
2033
2034/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2035/// should be given to a global variable of the specified type.
2036CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2037 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2038}
2039
David Majnemer08ef2ba2015-06-23 20:34:18 +00002040CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2041 CharUnits Offset = CharUnits::Zero();
2042 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2043 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2044 Offset += Layout->getBaseClassOffset(Base);
2045 Layout = &getASTRecordLayout(Base);
2046 }
2047 return Offset;
2048}
2049
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002050/// DeepCollectObjCIvars -
2051/// This routine first collects all declared, but not synthesized, ivars in
2052/// super class and then collects all ivars, including those synthesized for
2053/// current class. This routine is used for implementation of current class
2054/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002055///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002056void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2057 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002058 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002059 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2060 DeepCollectObjCIvars(SuperClass, false, Ivars);
2061 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002062 for (const auto *I : OI->ivars())
2063 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002064 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002065 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002066 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002067 Iv= Iv->getNextIvar())
2068 Ivars.push_back(Iv);
2069 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002070}
2071
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002072/// CollectInheritedProtocols - Collect all protocols in current class and
2073/// those inherited by it.
2074void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002075 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002076 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002077 // We can use protocol_iterator here instead of
2078 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002079 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002080 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002081 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002082
2083 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002084 for (const auto *Cat : OI->visible_categories())
2085 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002086
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002087 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2088 while (SD) {
2089 CollectInheritedProtocols(SD, Protocols);
2090 SD = SD->getSuperClass();
2091 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002092 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002093 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002094 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002095 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002096 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002097 // Insert the protocol.
2098 if (!Protocols.insert(
2099 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2100 return;
2101
2102 for (auto *Proto : OP->protocols())
2103 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002104 }
2105}
2106
Jay Foad39c79802011-01-12 09:06:06 +00002107unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002108 unsigned count = 0;
2109 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002110 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002111 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002112
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002113 // Count ivar defined in this class's implementation. This
2114 // includes synthesized ivars.
2115 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002116 count += ImplDecl->ivar_size();
2117
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002118 return count;
2119}
2120
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002121bool ASTContext::isSentinelNullExpr(const Expr *E) {
2122 if (!E)
2123 return false;
2124
2125 // nullptr_t is always treated as null.
2126 if (E->getType()->isNullPtrType()) return true;
2127
2128 if (E->getType()->isAnyPointerType() &&
2129 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2130 Expr::NPC_ValueDependentIsNull))
2131 return true;
2132
2133 // Unfortunately, __null has type 'int'.
2134 if (isa<GNUNullExpr>(E)) return true;
2135
2136 return false;
2137}
2138
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002139/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2140ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2141 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2142 I = ObjCImpls.find(D);
2143 if (I != ObjCImpls.end())
2144 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002145 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002146}
2147/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2148ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2149 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2150 I = ObjCImpls.find(D);
2151 if (I != ObjCImpls.end())
2152 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002153 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002154}
2155
2156/// \brief Set the implementation of ObjCInterfaceDecl.
2157void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2158 ObjCImplementationDecl *ImplD) {
2159 assert(IFaceD && ImplD && "Passed null params");
2160 ObjCImpls[IFaceD] = ImplD;
2161}
2162/// \brief Set the implementation of ObjCCategoryDecl.
2163void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2164 ObjCCategoryImplDecl *ImplD) {
2165 assert(CatD && ImplD && "Passed null params");
2166 ObjCImpls[CatD] = ImplD;
2167}
2168
Chandler Carruth21c90602015-12-30 03:24:14 +00002169const ObjCMethodDecl *
2170ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2171 return ObjCMethodRedecls.lookup(MD);
2172}
2173
2174void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2175 const ObjCMethodDecl *Redecl) {
2176 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2177 ObjCMethodRedecls[MD] = Redecl;
2178}
2179
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002180const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2181 const NamedDecl *ND) const {
2182 if (const ObjCInterfaceDecl *ID =
2183 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002184 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002185 if (const ObjCCategoryDecl *CD =
2186 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002187 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002188 if (const ObjCImplDecl *IMD =
2189 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002190 return IMD->getClassInterface();
2191
Craig Topper36250ad2014-05-12 05:36:57 +00002192 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002193}
2194
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002195/// \brief Get the copy initialization expression of VarDecl,or NULL if
2196/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002197Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002198 assert(VD && "Passed null params");
2199 assert(VD->hasAttr<BlocksAttr>() &&
2200 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002201 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002202 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002203 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002204}
2205
2206/// \brief Set the copy inialization expression of a block var decl.
2207void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2208 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002209 assert(VD->hasAttr<BlocksAttr>() &&
2210 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002211 BlockVarCopyInits[VD] = Init;
2212}
2213
John McCallbcd03502009-12-07 02:54:59 +00002214TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002215 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002216 if (!DataSize)
2217 DataSize = TypeLoc::getFullDataSizeForType(T);
2218 else
2219 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002220 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002221
John McCallbcd03502009-12-07 02:54:59 +00002222 TypeSourceInfo *TInfo =
2223 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2224 new (TInfo) TypeSourceInfo(T);
2225 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002226}
2227
John McCallbcd03502009-12-07 02:54:59 +00002228TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002229 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002230 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002231 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002232 return DI;
2233}
2234
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002235const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002236ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002237 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002238}
2239
2240const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002241ASTContext::getASTObjCImplementationLayout(
2242 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002243 return getObjCLayout(D->getClassInterface(), D);
2244}
2245
Chris Lattner983a8bb2007-07-13 22:13:22 +00002246//===----------------------------------------------------------------------===//
2247// Type creation/memoization methods
2248//===----------------------------------------------------------------------===//
2249
Jay Foad39c79802011-01-12 09:06:06 +00002250QualType
John McCall33ddac02011-01-19 10:06:00 +00002251ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2252 unsigned fastQuals = quals.getFastQualifiers();
2253 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002254
2255 // Check if we've already instantiated this type.
2256 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002257 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002258 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002259 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2260 assert(eq->getQualifiers() == quals);
2261 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002262 }
2263
John McCall33ddac02011-01-19 10:06:00 +00002264 // If the base type is not canonical, make the appropriate canonical type.
2265 QualType canon;
2266 if (!baseType->isCanonicalUnqualified()) {
2267 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002268 canonSplit.Quals.addConsistentQualifiers(quals);
2269 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002270
2271 // Re-find the insert position.
2272 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2273 }
2274
2275 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2276 ExtQualNodes.InsertNode(eq, insertPos);
2277 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002278}
2279
Jay Foad39c79802011-01-12 09:06:06 +00002280QualType
2281ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002282 QualType CanT = getCanonicalType(T);
2283 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002284 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002285
John McCall8ccfcb52009-09-24 19:53:00 +00002286 // If we are composing extended qualifiers together, merge together
2287 // into one ExtQuals node.
2288 QualifierCollector Quals;
2289 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002290
John McCall8ccfcb52009-09-24 19:53:00 +00002291 // If this type already has an address space specified, it cannot get
2292 // another one.
2293 assert(!Quals.hasAddressSpace() &&
2294 "Type cannot be in multiple addr spaces!");
2295 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002296
John McCall8ccfcb52009-09-24 19:53:00 +00002297 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002298}
2299
Chris Lattnerd60183d2009-02-18 22:53:11 +00002300QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002301 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002302 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002303 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002304 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002305
John McCall53fa7142010-12-24 02:08:15 +00002306 if (const PointerType *ptr = T->getAs<PointerType>()) {
2307 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002308 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002309 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2310 return getPointerType(ResultType);
2311 }
2312 }
Mike Stump11289f42009-09-09 15:08:12 +00002313
John McCall8ccfcb52009-09-24 19:53:00 +00002314 // If we are composing extended qualifiers together, merge together
2315 // into one ExtQuals node.
2316 QualifierCollector Quals;
2317 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002318
John McCall8ccfcb52009-09-24 19:53:00 +00002319 // If this type already has an ObjCGC specified, it cannot get
2320 // another one.
2321 assert(!Quals.hasObjCGCAttr() &&
2322 "Type cannot have multiple ObjCGCs!");
2323 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002324
John McCall8ccfcb52009-09-24 19:53:00 +00002325 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002326}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002327
John McCall4f5019e2010-12-19 02:44:49 +00002328const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2329 FunctionType::ExtInfo Info) {
2330 if (T->getExtInfo() == Info)
2331 return T;
2332
2333 QualType Result;
2334 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002335 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002336 } else {
2337 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2338 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2339 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002340 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002341 }
2342
2343 return cast<FunctionType>(Result.getTypePtr());
2344}
2345
Richard Smith2a7d4812013-05-04 07:00:32 +00002346void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2347 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002348 FD = FD->getMostRecentDecl();
2349 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002350 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2351 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002352 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002353 if (FunctionDecl *Next = FD->getPreviousDecl())
2354 FD = Next;
2355 else
2356 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002357 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002358 if (ASTMutationListener *L = getASTMutationListener())
2359 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002360}
2361
Richard Smith0b3a4622014-11-13 20:01:57 +00002362/// Get a function type and produce the equivalent function type with the
2363/// specified exception specification. Type sugar that can be present on a
2364/// declaration of a function with an exception specification is permitted
2365/// and preserved. Other type sugar (for instance, typedefs) is not.
2366static QualType getFunctionTypeWithExceptionSpec(
2367 ASTContext &Context, QualType Orig,
2368 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2369 // Might have some parens.
2370 if (auto *PT = dyn_cast<ParenType>(Orig))
2371 return Context.getParenType(
2372 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2373
2374 // Might have a calling-convention attribute.
2375 if (auto *AT = dyn_cast<AttributedType>(Orig))
2376 return Context.getAttributedType(
2377 AT->getAttrKind(),
2378 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2379 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2380 ESI));
2381
2382 // Anything else must be a function type. Rebuild it with the new exception
2383 // specification.
2384 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2385 return Context.getFunctionType(
2386 Proto->getReturnType(), Proto->getParamTypes(),
2387 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2388}
2389
Richard Smithdfe85e22016-12-15 02:35:39 +00002390bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2391 QualType U) {
2392 return hasSameType(T, U) ||
2393 (getLangOpts().CPlusPlus1z &&
2394 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2395 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2396}
2397
Richard Smith0b3a4622014-11-13 20:01:57 +00002398void ASTContext::adjustExceptionSpec(
2399 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2400 bool AsWritten) {
2401 // Update the type.
2402 QualType Updated =
2403 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2404 FD->setType(Updated);
2405
2406 if (!AsWritten)
2407 return;
2408
2409 // Update the type in the type source information too.
2410 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2411 // If the type and the type-as-written differ, we may need to update
2412 // the type-as-written too.
2413 if (TSInfo->getType() != FD->getType())
2414 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2415
2416 // FIXME: When we get proper type location information for exceptions,
2417 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2418 // up the TypeSourceInfo;
2419 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2420 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2421 "TypeLoc size mismatch from updating exception specification");
2422 TSInfo->overrideType(Updated);
2423 }
2424}
2425
Chris Lattnerc6395932007-06-22 20:56:16 +00002426/// getComplexType - Return the uniqued reference to the type for a complex
2427/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002428QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002429 // Unique pointers, to guarantee there is only one pointer of a particular
2430 // structure.
2431 llvm::FoldingSetNodeID ID;
2432 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002433
Craig Topper36250ad2014-05-12 05:36:57 +00002434 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002435 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2436 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002437
Chris Lattnerc6395932007-06-22 20:56:16 +00002438 // If the pointee type isn't canonical, this won't be a canonical type either,
2439 // so fill in the canonical type field.
2440 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002441 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002442 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002443
Chris Lattnerc6395932007-06-22 20:56:16 +00002444 // Get the new insert position for the node we care about.
2445 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002446 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002447 }
John McCall90d1c2d2009-09-24 23:30:46 +00002448 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002449 Types.push_back(New);
2450 ComplexTypes.InsertNode(New, InsertPos);
2451 return QualType(New, 0);
2452}
2453
Chris Lattner970e54e2006-11-12 00:37:36 +00002454/// getPointerType - Return the uniqued reference to the type for a pointer to
2455/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002456QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002457 // Unique pointers, to guarantee there is only one pointer of a particular
2458 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002459 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002460 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002461
Craig Topper36250ad2014-05-12 05:36:57 +00002462 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002463 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002464 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002465
Chris Lattner7ccecb92006-11-12 08:50:50 +00002466 // If the pointee type isn't canonical, this won't be a canonical type either,
2467 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002468 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002469 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002470 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002471
Bob Wilsonc8541f22013-03-15 17:12:43 +00002472 // Get the new insert position for the node we care about.
2473 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002474 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002475 }
John McCall90d1c2d2009-09-24 23:30:46 +00002476 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002477 Types.push_back(New);
2478 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002479 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002480}
2481
Reid Kleckner0503a872013-12-05 01:23:43 +00002482QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2483 llvm::FoldingSetNodeID ID;
2484 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002485 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002486 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2487 if (AT)
2488 return QualType(AT, 0);
2489
2490 QualType Canonical = getCanonicalType(New);
2491
2492 // Get the new insert position for the node we care about.
2493 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002494 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002495
2496 AT = new (*this, TypeAlignment)
2497 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2498 Types.push_back(AT);
2499 AdjustedTypes.InsertNode(AT, InsertPos);
2500 return QualType(AT, 0);
2501}
2502
Reid Kleckner8a365022013-06-24 17:51:48 +00002503QualType ASTContext::getDecayedType(QualType T) const {
2504 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2505
Reid Kleckner8a365022013-06-24 17:51:48 +00002506 QualType Decayed;
2507
2508 // C99 6.7.5.3p7:
2509 // A declaration of a parameter as "array of type" shall be
2510 // adjusted to "qualified pointer to type", where the type
2511 // qualifiers (if any) are those specified within the [ and ] of
2512 // the array type derivation.
2513 if (T->isArrayType())
2514 Decayed = getArrayDecayedType(T);
2515
2516 // C99 6.7.5.3p8:
2517 // A declaration of a parameter as "function returning type"
2518 // shall be adjusted to "pointer to function returning type", as
2519 // in 6.3.2.1.
2520 if (T->isFunctionType())
2521 Decayed = getPointerType(T);
2522
Reid Kleckner0503a872013-12-05 01:23:43 +00002523 llvm::FoldingSetNodeID ID;
2524 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002525 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002526 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2527 if (AT)
2528 return QualType(AT, 0);
2529
Reid Kleckner8a365022013-06-24 17:51:48 +00002530 QualType Canonical = getCanonicalType(Decayed);
2531
2532 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002533 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002534 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002535
Reid Kleckner0503a872013-12-05 01:23:43 +00002536 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2537 Types.push_back(AT);
2538 AdjustedTypes.InsertNode(AT, InsertPos);
2539 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002540}
2541
Mike Stump11289f42009-09-09 15:08:12 +00002542/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002543/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002544QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002545 assert(T->isFunctionType() && "block of function types only");
2546 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002547 // structure.
2548 llvm::FoldingSetNodeID ID;
2549 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002550
Craig Topper36250ad2014-05-12 05:36:57 +00002551 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002552 if (BlockPointerType *PT =
2553 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2554 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002555
2556 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002557 // type either so fill in the canonical type field.
2558 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002559 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002560 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002561
Steve Naroffec33ed92008-08-27 16:04:49 +00002562 // Get the new insert position for the node we care about.
2563 BlockPointerType *NewIP =
2564 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002565 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002566 }
John McCall90d1c2d2009-09-24 23:30:46 +00002567 BlockPointerType *New
2568 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002569 Types.push_back(New);
2570 BlockPointerTypes.InsertNode(New, InsertPos);
2571 return QualType(New, 0);
2572}
2573
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002574/// getLValueReferenceType - Return the uniqued reference to the type for an
2575/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002576QualType
2577ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002578 assert(getCanonicalType(T) != OverloadTy &&
2579 "Unresolved overloaded function type");
2580
Bill Wendling3708c182007-05-27 10:15:43 +00002581 // Unique pointers, to guarantee there is only one pointer of a particular
2582 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002583 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002584 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002585
Craig Topper36250ad2014-05-12 05:36:57 +00002586 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002587 if (LValueReferenceType *RT =
2588 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002589 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002590
John McCallfc93cf92009-10-22 22:37:11 +00002591 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2592
Bill Wendling3708c182007-05-27 10:15:43 +00002593 // If the referencee type isn't canonical, this won't be a canonical type
2594 // either, so fill in the canonical type field.
2595 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002596 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2597 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2598 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002599
Bill Wendling3708c182007-05-27 10:15:43 +00002600 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002601 LValueReferenceType *NewIP =
2602 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002603 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002604 }
2605
John McCall90d1c2d2009-09-24 23:30:46 +00002606 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002607 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2608 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002609 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002610 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002611
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002612 return QualType(New, 0);
2613}
2614
2615/// getRValueReferenceType - Return the uniqued reference to the type for an
2616/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002617QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002618 // Unique pointers, to guarantee there is only one pointer of a particular
2619 // structure.
2620 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002621 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002622
Craig Topper36250ad2014-05-12 05:36:57 +00002623 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002624 if (RValueReferenceType *RT =
2625 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2626 return QualType(RT, 0);
2627
John McCallfc93cf92009-10-22 22:37:11 +00002628 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2629
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002630 // If the referencee type isn't canonical, this won't be a canonical type
2631 // either, so fill in the canonical type field.
2632 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002633 if (InnerRef || !T.isCanonical()) {
2634 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2635 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002636
2637 // Get the new insert position for the node we care about.
2638 RValueReferenceType *NewIP =
2639 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002640 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002641 }
2642
John McCall90d1c2d2009-09-24 23:30:46 +00002643 RValueReferenceType *New
2644 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002645 Types.push_back(New);
2646 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002647 return QualType(New, 0);
2648}
2649
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002650/// getMemberPointerType - Return the uniqued reference to the type for a
2651/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002652QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002653 // Unique pointers, to guarantee there is only one pointer of a particular
2654 // structure.
2655 llvm::FoldingSetNodeID ID;
2656 MemberPointerType::Profile(ID, T, Cls);
2657
Craig Topper36250ad2014-05-12 05:36:57 +00002658 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002659 if (MemberPointerType *PT =
2660 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2661 return QualType(PT, 0);
2662
2663 // If the pointee or class type isn't canonical, this won't be a canonical
2664 // type either, so fill in the canonical type field.
2665 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002666 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002667 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2668
2669 // Get the new insert position for the node we care about.
2670 MemberPointerType *NewIP =
2671 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002672 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002673 }
John McCall90d1c2d2009-09-24 23:30:46 +00002674 MemberPointerType *New
2675 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002676 Types.push_back(New);
2677 MemberPointerTypes.InsertNode(New, InsertPos);
2678 return QualType(New, 0);
2679}
2680
Mike Stump11289f42009-09-09 15:08:12 +00002681/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002682/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002683QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002684 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002685 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002686 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002687 assert((EltTy->isDependentType() ||
2688 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002689 "Constant array of VLAs is illegal!");
2690
Chris Lattnere2df3f92009-05-13 04:12:56 +00002691 // Convert the array size into a canonical width matching the pointer size for
2692 // the target.
2693 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002694 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002695 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002696
Chris Lattner23b7eb62007-06-15 23:05:46 +00002697 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002698 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002699
Craig Topper36250ad2014-05-12 05:36:57 +00002700 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002701 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002702 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002703 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002704
John McCall33ddac02011-01-19 10:06:00 +00002705 // If the element type isn't canonical or has qualifiers, this won't
2706 // be a canonical type either, so fill in the canonical type field.
2707 QualType Canon;
2708 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2709 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002710 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002711 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002712 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002713
Chris Lattner36f8e652007-01-27 08:31:04 +00002714 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002715 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002716 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002717 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002718 }
Mike Stump11289f42009-09-09 15:08:12 +00002719
John McCall90d1c2d2009-09-24 23:30:46 +00002720 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002721 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002722 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002723 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002724 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002725}
2726
John McCall06549462011-01-18 08:40:38 +00002727/// getVariableArrayDecayedType - Turns the given type, which may be
2728/// variably-modified, into the corresponding type with all the known
2729/// sizes replaced with [*].
2730QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2731 // Vastly most common case.
2732 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002733
John McCall06549462011-01-18 08:40:38 +00002734 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002735
John McCall06549462011-01-18 08:40:38 +00002736 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002737 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002738 switch (ty->getTypeClass()) {
2739#define TYPE(Class, Base)
2740#define ABSTRACT_TYPE(Class, Base)
2741#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2742#include "clang/AST/TypeNodes.def"
2743 llvm_unreachable("didn't desugar past all non-canonical types?");
2744
2745 // These types should never be variably-modified.
2746 case Type::Builtin:
2747 case Type::Complex:
2748 case Type::Vector:
2749 case Type::ExtVector:
2750 case Type::DependentSizedExtVector:
2751 case Type::ObjCObject:
2752 case Type::ObjCInterface:
2753 case Type::ObjCObjectPointer:
2754 case Type::Record:
2755 case Type::Enum:
2756 case Type::UnresolvedUsing:
2757 case Type::TypeOfExpr:
2758 case Type::TypeOf:
2759 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002760 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002761 case Type::DependentName:
2762 case Type::InjectedClassName:
2763 case Type::TemplateSpecialization:
2764 case Type::DependentTemplateSpecialization:
2765 case Type::TemplateTypeParm:
2766 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002767 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002768 case Type::PackExpansion:
2769 llvm_unreachable("type should never be variably-modified");
2770
2771 // These types can be variably-modified but should never need to
2772 // further decay.
2773 case Type::FunctionNoProto:
2774 case Type::FunctionProto:
2775 case Type::BlockPointer:
2776 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002777 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002778 return type;
2779
2780 // These types can be variably-modified. All these modifications
2781 // preserve structure except as noted by comments.
2782 // TODO: if we ever care about optimizing VLAs, there are no-op
2783 // optimizations available here.
2784 case Type::Pointer:
2785 result = getPointerType(getVariableArrayDecayedType(
2786 cast<PointerType>(ty)->getPointeeType()));
2787 break;
2788
2789 case Type::LValueReference: {
2790 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2791 result = getLValueReferenceType(
2792 getVariableArrayDecayedType(lv->getPointeeType()),
2793 lv->isSpelledAsLValue());
2794 break;
2795 }
2796
2797 case Type::RValueReference: {
2798 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2799 result = getRValueReferenceType(
2800 getVariableArrayDecayedType(lv->getPointeeType()));
2801 break;
2802 }
2803
Eli Friedman0dfb8892011-10-06 23:00:33 +00002804 case Type::Atomic: {
2805 const AtomicType *at = cast<AtomicType>(ty);
2806 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2807 break;
2808 }
2809
John McCall06549462011-01-18 08:40:38 +00002810 case Type::ConstantArray: {
2811 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2812 result = getConstantArrayType(
2813 getVariableArrayDecayedType(cat->getElementType()),
2814 cat->getSize(),
2815 cat->getSizeModifier(),
2816 cat->getIndexTypeCVRQualifiers());
2817 break;
2818 }
2819
2820 case Type::DependentSizedArray: {
2821 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2822 result = getDependentSizedArrayType(
2823 getVariableArrayDecayedType(dat->getElementType()),
2824 dat->getSizeExpr(),
2825 dat->getSizeModifier(),
2826 dat->getIndexTypeCVRQualifiers(),
2827 dat->getBracketsRange());
2828 break;
2829 }
2830
2831 // Turn incomplete types into [*] types.
2832 case Type::IncompleteArray: {
2833 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2834 result = getVariableArrayType(
2835 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002836 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002837 ArrayType::Normal,
2838 iat->getIndexTypeCVRQualifiers(),
2839 SourceRange());
2840 break;
2841 }
2842
2843 // Turn VLA types into [*] types.
2844 case Type::VariableArray: {
2845 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2846 result = getVariableArrayType(
2847 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002848 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002849 ArrayType::Star,
2850 vat->getIndexTypeCVRQualifiers(),
2851 vat->getBracketsRange());
2852 break;
2853 }
2854 }
2855
2856 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002857 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002858}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002859
Steve Naroffcadebd02007-08-30 18:14:25 +00002860/// getVariableArrayType - Returns a non-unique reference to the type for a
2861/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002862QualType ASTContext::getVariableArrayType(QualType EltTy,
2863 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002864 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002865 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002866 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002867 // Since we don't unique expressions, it isn't possible to unique VLA's
2868 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002869 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002870
John McCall33ddac02011-01-19 10:06:00 +00002871 // Be sure to pull qualifiers off the element type.
2872 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2873 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002874 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002875 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002876 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002877 }
2878
John McCall90d1c2d2009-09-24 23:30:46 +00002879 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002880 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002881
2882 VariableArrayTypes.push_back(New);
2883 Types.push_back(New);
2884 return QualType(New, 0);
2885}
2886
Douglas Gregor4619e432008-12-05 23:32:09 +00002887/// getDependentSizedArrayType - Returns a non-unique reference to
2888/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002889/// type.
John McCall33ddac02011-01-19 10:06:00 +00002890QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2891 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002892 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002893 unsigned elementTypeQuals,
2894 SourceRange brackets) const {
2895 assert((!numElements || numElements->isTypeDependent() ||
2896 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002897 "Size must be type- or value-dependent!");
2898
John McCall33ddac02011-01-19 10:06:00 +00002899 // Dependently-sized array types that do not have a specified number
2900 // of elements will have their sizes deduced from a dependent
2901 // initializer. We do no canonicalization here at all, which is okay
2902 // because they can't be used in most locations.
2903 if (!numElements) {
2904 DependentSizedArrayType *newType
2905 = new (*this, TypeAlignment)
2906 DependentSizedArrayType(*this, elementType, QualType(),
2907 numElements, ASM, elementTypeQuals,
2908 brackets);
2909 Types.push_back(newType);
2910 return QualType(newType, 0);
2911 }
2912
2913 // Otherwise, we actually build a new type every time, but we
2914 // also build a canonical type.
2915
2916 SplitQualType canonElementType = getCanonicalType(elementType).split();
2917
Craig Topper36250ad2014-05-12 05:36:57 +00002918 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002919 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002920 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002921 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002922 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002923
John McCall33ddac02011-01-19 10:06:00 +00002924 // Look for an existing type with these properties.
2925 DependentSizedArrayType *canonTy =
2926 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002927
John McCall33ddac02011-01-19 10:06:00 +00002928 // If we don't have one, build one.
2929 if (!canonTy) {
2930 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002931 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002932 QualType(), numElements, ASM, elementTypeQuals,
2933 brackets);
2934 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2935 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002936 }
2937
John McCall33ddac02011-01-19 10:06:00 +00002938 // Apply qualifiers from the element type to the array.
2939 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002940 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002941
David Majnemer16a74702015-07-24 05:54:19 +00002942 // If we didn't need extra canonicalization for the element type or the size
2943 // expression, then just use that as our result.
2944 if (QualType(canonElementType.Ty, 0) == elementType &&
2945 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002946 return canon;
2947
2948 // Otherwise, we need to build a type which follows the spelling
2949 // of the element type.
2950 DependentSizedArrayType *sugaredType
2951 = new (*this, TypeAlignment)
2952 DependentSizedArrayType(*this, elementType, canon, numElements,
2953 ASM, elementTypeQuals, brackets);
2954 Types.push_back(sugaredType);
2955 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002956}
2957
John McCall33ddac02011-01-19 10:06:00 +00002958QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002959 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002960 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002961 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002962 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002963
Craig Topper36250ad2014-05-12 05:36:57 +00002964 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002965 if (IncompleteArrayType *iat =
2966 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2967 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002968
2969 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002970 // either, so fill in the canonical type field. We also have to pull
2971 // qualifiers off the element type.
2972 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002973
John McCall33ddac02011-01-19 10:06:00 +00002974 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2975 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002976 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002977 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002978 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002979
2980 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002981 IncompleteArrayType *existing =
2982 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2983 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002984 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002985
John McCall33ddac02011-01-19 10:06:00 +00002986 IncompleteArrayType *newType = new (*this, TypeAlignment)
2987 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002988
John McCall33ddac02011-01-19 10:06:00 +00002989 IncompleteArrayTypes.InsertNode(newType, insertPos);
2990 Types.push_back(newType);
2991 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002992}
2993
Steve Naroff91fcddb2007-07-18 18:00:27 +00002994/// getVectorType - Return the unique reference to a vector type of
2995/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002996QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002997 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002998 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002999
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003000 // Check if we've already instantiated a vector of this type.
3001 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003002 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003003
Craig Topper36250ad2014-05-12 05:36:57 +00003004 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003005 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3006 return QualType(VTP, 0);
3007
3008 // If the element type isn't canonical, this won't be a canonical type either,
3009 // so fill in the canonical type field.
3010 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003011 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003012 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003013
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003014 // Get the new insert position for the node we care about.
3015 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003016 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003017 }
John McCall90d1c2d2009-09-24 23:30:46 +00003018 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003019 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003020 VectorTypes.InsertNode(New, InsertPos);
3021 Types.push_back(New);
3022 return QualType(New, 0);
3023}
3024
Nate Begemance4d7fc2008-04-18 23:10:10 +00003025/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003026/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003027QualType
3028ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003029 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003030
Steve Naroff91fcddb2007-07-18 18:00:27 +00003031 // Check if we've already instantiated a vector of this type.
3032 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003033 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003034 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003035 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003036 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3037 return QualType(VTP, 0);
3038
3039 // If the element type isn't canonical, this won't be a canonical type either,
3040 // so fill in the canonical type field.
3041 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003042 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003043 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003044
Steve Naroff91fcddb2007-07-18 18:00:27 +00003045 // Get the new insert position for the node we care about.
3046 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003047 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003048 }
John McCall90d1c2d2009-09-24 23:30:46 +00003049 ExtVectorType *New = new (*this, TypeAlignment)
3050 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003051 VectorTypes.InsertNode(New, InsertPos);
3052 Types.push_back(New);
3053 return QualType(New, 0);
3054}
3055
Jay Foad39c79802011-01-12 09:06:06 +00003056QualType
3057ASTContext::getDependentSizedExtVectorType(QualType vecType,
3058 Expr *SizeExpr,
3059 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003060 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003061 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003062 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003063
Craig Topper36250ad2014-05-12 05:36:57 +00003064 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003065 DependentSizedExtVectorType *Canon
3066 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3067 DependentSizedExtVectorType *New;
3068 if (Canon) {
3069 // We already have a canonical version of this array type; use it as
3070 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003071 New = new (*this, TypeAlignment)
3072 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3073 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003074 } else {
3075 QualType CanonVecTy = getCanonicalType(vecType);
3076 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003077 New = new (*this, TypeAlignment)
3078 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3079 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003080
3081 DependentSizedExtVectorType *CanonCheck
3082 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3083 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3084 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003085 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3086 } else {
3087 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3088 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003089 New = new (*this, TypeAlignment)
3090 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003091 }
3092 }
Mike Stump11289f42009-09-09 15:08:12 +00003093
Douglas Gregor758a8692009-06-17 21:51:59 +00003094 Types.push_back(New);
3095 return QualType(New, 0);
3096}
3097
John McCall18afab72016-03-01 00:49:02 +00003098/// \brief Determine whether \p T is canonical as the result type of a function.
3099static bool isCanonicalResultType(QualType T) {
3100 return T.isCanonical() &&
3101 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3102 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3103}
3104
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003105/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003106///
Jay Foad39c79802011-01-12 09:06:06 +00003107QualType
3108ASTContext::getFunctionNoProtoType(QualType ResultTy,
3109 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003110 // Unique functions, to guarantee there is only one function of a particular
3111 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003112 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003113 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003114
Craig Topper36250ad2014-05-12 05:36:57 +00003115 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003116 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003117 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003118 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003119
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003120 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003121 if (!isCanonicalResultType(ResultTy)) {
3122 Canonical =
3123 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003124
Chris Lattner47955de2007-01-27 08:37:20 +00003125 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003126 FunctionNoProtoType *NewIP =
3127 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003128 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003129 }
Mike Stump11289f42009-09-09 15:08:12 +00003130
John McCall90d1c2d2009-09-24 23:30:46 +00003131 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003132 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003133 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003134 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003135 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003136}
3137
Douglas Gregora602a152015-10-01 20:20:47 +00003138CanQualType
3139ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3140 CanQualType CanResultType = getCanonicalType(ResultType);
3141
3142 // Canonical result types do not have ARC lifetime qualifiers.
3143 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3144 Qualifiers Qs = CanResultType.getQualifiers();
3145 Qs.removeObjCLifetime();
3146 return CanQualType::CreateUnsafe(
3147 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3148 }
3149
3150 return CanResultType;
3151}
3152
Richard Smith3c4f8d22016-10-16 17:54:23 +00003153static bool isCanonicalExceptionSpecification(
3154 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3155 if (ESI.Type == EST_None)
3156 return true;
3157 if (!NoexceptInType)
3158 return false;
3159
3160 // C++17 onwards: exception specification is part of the type, as a simple
3161 // boolean "can this function type throw".
3162 if (ESI.Type == EST_BasicNoexcept)
3163 return true;
3164
3165 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003166 // expansions (so we can't tell whether it's non-throwing) and all its
3167 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003168 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003169 bool AnyPackExpansions = false;
3170 for (QualType ET : ESI.Exceptions) {
3171 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003172 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003173 if (ET->getAs<PackExpansionType>())
3174 AnyPackExpansions = true;
3175 }
3176 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003177 }
3178
Richard Smith2a2cda52016-10-18 19:29:18 +00003179 // A noexcept(expr) specification is (possibly) canonical if expr is
3180 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003181 if (ESI.Type == EST_ComputedNoexcept)
3182 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3183
3184 return false;
3185}
3186
Richard Smith304b1242016-10-18 20:13:25 +00003187QualType ASTContext::getFunctionTypeInternal(
3188 QualType ResultTy, ArrayRef<QualType> ArgArray,
3189 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003190 size_t NumArgs = ArgArray.size();
3191
Richard Smith2a2cda52016-10-18 19:29:18 +00003192 // Unique functions, to guarantee there is only one function of a particular
3193 // structure.
3194 llvm::FoldingSetNodeID ID;
3195 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3196 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003197
Richard Smith2a2cda52016-10-18 19:29:18 +00003198 QualType Canonical;
3199 bool Unique = false;
3200
3201 void *InsertPos = nullptr;
3202 if (FunctionProtoType *FPT =
3203 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3204 QualType Existing = QualType(FPT, 0);
3205
3206 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3207 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003208 // noexcept expression, or we're just looking for a canonical type.
3209 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003210 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003211 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003212 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3213 return Existing;
3214
3215 // We need a new type sugar node for this one, to hold the new noexcept
3216 // expression. We do no canonicalization here, but that's OK since we don't
3217 // expect to see the same noexcept expression much more than once.
3218 Canonical = getCanonicalType(Existing);
3219 Unique = true;
3220 }
3221
3222 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003223 bool IsCanonicalExceptionSpec =
3224 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3225
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003226 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003227 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003228 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003229 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003230 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003231 isCanonical = false;
3232
Richard Smith304b1242016-10-18 20:13:25 +00003233 if (OnlyWantCanonical)
3234 assert(isCanonical &&
3235 "given non-canonical parameters constructing canonical type");
3236
Richard Smith2a2cda52016-10-18 19:29:18 +00003237 // If this type isn't canonical, get the canonical version of it if we don't
3238 // already have it. The exception spec is only partially part of the
3239 // canonical type, and only in C++17 onwards.
3240 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003241 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003242 CanonicalArgs.reserve(NumArgs);
3243 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003244 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003245
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003246 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003247 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003248 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003249
3250 if (IsCanonicalExceptionSpec) {
3251 // Exception spec is already OK.
3252 } else if (NoexceptInType) {
3253 switch (EPI.ExceptionSpec.Type) {
3254 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3255 // We don't know yet. It shouldn't matter what we pick here; no-one
3256 // should ever look at this.
3257 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003258 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003259 CanonicalEPI.ExceptionSpec.Type = EST_None;
3260 break;
3261
Richard Smith2a2cda52016-10-18 19:29:18 +00003262 // A dynamic exception specification is almost always "not noexcept",
3263 // with the exception that a pack expansion might expand to no types.
3264 case EST_Dynamic: {
3265 bool AnyPacks = false;
3266 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3267 if (ET->getAs<PackExpansionType>())
3268 AnyPacks = true;
3269 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3270 }
3271 if (!AnyPacks)
3272 CanonicalEPI.ExceptionSpec.Type = EST_None;
3273 else {
3274 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3275 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3276 }
3277 break;
3278 }
3279
Richard Smith3c4f8d22016-10-16 17:54:23 +00003280 case EST_DynamicNone: case EST_BasicNoexcept:
3281 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3282 break;
3283
3284 case EST_ComputedNoexcept:
3285 llvm::APSInt Value(1);
3286 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3287 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3288 /*IsEvaluated*/false)) {
3289 // This noexcept specification is invalid.
3290 // FIXME: Should this be able to happen?
3291 CanonicalEPI.ExceptionSpec.Type = EST_None;
3292 break;
3293 }
3294
3295 CanonicalEPI.ExceptionSpec.Type =
3296 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3297 break;
3298 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003299 } else {
3300 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3301 }
John McCalldb40c7f2010-12-14 08:05:40 +00003302
Douglas Gregora602a152015-10-01 20:20:47 +00003303 // Adjust the canonical function result type.
3304 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003305 Canonical =
3306 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003307
Chris Lattnerfd4de792007-01-27 01:15:32 +00003308 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003309 FunctionProtoType *NewIP =
3310 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003311 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003312 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003313
John McCall31168b02011-06-15 23:02:42 +00003314 // FunctionProtoType objects are allocated with extra bytes after
3315 // them for three variable size arrays at the end:
3316 // - parameter types
3317 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003318 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003319 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003320 // expression, or information used to resolve the exception
3321 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003322 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003323 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003324
Richard Smith8acb4282014-07-31 21:57:55 +00003325 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3326 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3327 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003328 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003329 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003330 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003331 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003332 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003333 }
John McCall18afab72016-03-01 00:49:02 +00003334
3335 // Put the ExtParameterInfos last. If all were equal, it would make
3336 // more sense to put these before the exception specification, because
3337 // it's much easier to skip past them compared to the elaborate switch
3338 // required to skip the exception specification. However, all is not
3339 // equal; ExtParameterInfos are used to model very uncommon features,
3340 // and it's better not to burden the more common paths.
3341 if (EPI.ExtParameterInfos) {
3342 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3343 }
John McCall31168b02011-06-15 23:02:42 +00003344
John McCalldb40c7f2010-12-14 08:05:40 +00003345 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003346 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003347 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003348 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003349 if (!Unique)
3350 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003351 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003352}
Chris Lattneref51c202006-11-10 07:17:23 +00003353
Joey Goulye3c85de2016-12-01 11:30:49 +00003354QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003355 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003356 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003357
3358 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003359 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003360 return QualType(PT, 0);
3361
3362 // If the pipe element type isn't canonical, this won't be a canonical type
3363 // either, so fill in the canonical type field.
3364 QualType Canonical;
3365 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003366 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003367
3368 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003369 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003370 assert(!NewIP && "Shouldn't be in the map!");
3371 (void)NewIP;
3372 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003373 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003374 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003375 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003376 return QualType(New, 0);
3377}
3378
Joey Goulye3c85de2016-12-01 11:30:49 +00003379QualType ASTContext::getReadPipeType(QualType T) const {
3380 return getPipeType(T, true);
3381}
3382
Joey Gouly5788b782016-11-18 14:10:54 +00003383QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003384 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003385}
3386
John McCalle78aac42010-03-10 03:28:59 +00003387#ifndef NDEBUG
3388static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3389 if (!isa<CXXRecordDecl>(D)) return false;
3390 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3391 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3392 return true;
3393 if (RD->getDescribedClassTemplate() &&
3394 !isa<ClassTemplateSpecializationDecl>(RD))
3395 return true;
3396 return false;
3397}
3398#endif
3399
3400/// getInjectedClassNameType - Return the unique reference to the
3401/// injected class name type for the specified templated declaration.
3402QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003403 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003404 assert(NeedsInjectedClassNameType(Decl));
3405 if (Decl->TypeForDecl) {
3406 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003407 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003408 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3409 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3410 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3411 } else {
John McCall424cec92011-01-19 06:33:43 +00003412 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003413 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003414 Decl->TypeForDecl = newType;
3415 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003416 }
3417 return QualType(Decl->TypeForDecl, 0);
3418}
3419
Douglas Gregor83a586e2008-04-13 21:07:44 +00003420/// getTypeDeclType - Return the unique reference to the type for the
3421/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003422QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003423 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003424 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003425
Richard Smithdda56e42011-04-15 14:24:37 +00003426 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003427 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003428
John McCall96f0b5f2010-03-10 06:48:02 +00003429 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3430 "Template type parameter types are always available.");
3431
John McCall81e38502010-02-16 03:57:14 +00003432 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003433 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003434 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003435 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003436 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003437 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003438 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003439 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003440 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003441 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3442 Decl->TypeForDecl = newType;
3443 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003444 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003445 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003446
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003447 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003448}
3449
Chris Lattner32d920b2007-01-26 02:01:53 +00003450/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003451/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003452QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003453ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3454 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003455 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003456
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003457 if (Canonical.isNull())
3458 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003459 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003460 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003461 Decl->TypeForDecl = newType;
3462 Types.push_back(newType);
3463 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003464}
3465
Jay Foad39c79802011-01-12 09:06:06 +00003466QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003467 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3468
Douglas Gregorec9fd132012-01-14 16:38:05 +00003469 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003470 if (PrevDecl->TypeForDecl)
3471 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3472
John McCall424cec92011-01-19 06:33:43 +00003473 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3474 Decl->TypeForDecl = newType;
3475 Types.push_back(newType);
3476 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003477}
3478
Jay Foad39c79802011-01-12 09:06:06 +00003479QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003480 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3481
Douglas Gregorec9fd132012-01-14 16:38:05 +00003482 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003483 if (PrevDecl->TypeForDecl)
3484 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3485
John McCall424cec92011-01-19 06:33:43 +00003486 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3487 Decl->TypeForDecl = newType;
3488 Types.push_back(newType);
3489 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003490}
3491
John McCall81904512011-01-06 01:58:22 +00003492QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3493 QualType modifiedType,
3494 QualType equivalentType) {
3495 llvm::FoldingSetNodeID id;
3496 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3497
Craig Topper36250ad2014-05-12 05:36:57 +00003498 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003499 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3500 if (type) return QualType(type, 0);
3501
3502 QualType canon = getCanonicalType(equivalentType);
3503 type = new (*this, TypeAlignment)
3504 AttributedType(canon, attrKind, modifiedType, equivalentType);
3505
3506 Types.push_back(type);
3507 AttributedTypes.InsertNode(type, insertPos);
3508
3509 return QualType(type, 0);
3510}
3511
John McCallcebee162009-10-18 09:09:24 +00003512/// \brief Retrieve a substitution-result type.
3513QualType
3514ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003515 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003516 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003517 && "replacement types must always be canonical");
3518
3519 llvm::FoldingSetNodeID ID;
3520 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003521 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003522 SubstTemplateTypeParmType *SubstParm
3523 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3524
3525 if (!SubstParm) {
3526 SubstParm = new (*this, TypeAlignment)
3527 SubstTemplateTypeParmType(Parm, Replacement);
3528 Types.push_back(SubstParm);
3529 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3530 }
3531
3532 return QualType(SubstParm, 0);
3533}
3534
Douglas Gregorada4b792011-01-14 02:55:32 +00003535/// \brief Retrieve a
3536QualType ASTContext::getSubstTemplateTypeParmPackType(
3537 const TemplateTypeParmType *Parm,
3538 const TemplateArgument &ArgPack) {
3539#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003540 for (const auto &P : ArgPack.pack_elements()) {
3541 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3542 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003543 }
3544#endif
3545
3546 llvm::FoldingSetNodeID ID;
3547 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003548 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003549 if (SubstTemplateTypeParmPackType *SubstParm
3550 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3551 return QualType(SubstParm, 0);
3552
3553 QualType Canon;
3554 if (!Parm->isCanonicalUnqualified()) {
3555 Canon = getCanonicalType(QualType(Parm, 0));
3556 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3557 ArgPack);
3558 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3559 }
3560
3561 SubstTemplateTypeParmPackType *SubstParm
3562 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3563 ArgPack);
3564 Types.push_back(SubstParm);
3565 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3566 return QualType(SubstParm, 0);
3567}
3568
Douglas Gregoreff93e02009-02-05 23:33:38 +00003569/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003570/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003571/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003572QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003573 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003574 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003575 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003576 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003577 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003578 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003579 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3580
3581 if (TypeParm)
3582 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003583
Chandler Carruth08836322011-05-01 00:51:33 +00003584 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003585 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003586 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003587
3588 TemplateTypeParmType *TypeCheck
3589 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3590 assert(!TypeCheck && "Template type parameter canonical type broken");
3591 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003592 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003593 TypeParm = new (*this, TypeAlignment)
3594 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003595
3596 Types.push_back(TypeParm);
3597 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3598
3599 return QualType(TypeParm, 0);
3600}
3601
John McCalle78aac42010-03-10 03:28:59 +00003602TypeSourceInfo *
3603ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3604 SourceLocation NameLoc,
3605 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003606 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003607 assert(!Name.getAsDependentTemplateName() &&
3608 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003609 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003610
3611 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003612 TemplateSpecializationTypeLoc TL =
3613 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003614 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003615 TL.setTemplateNameLoc(NameLoc);
3616 TL.setLAngleLoc(Args.getLAngleLoc());
3617 TL.setRAngleLoc(Args.getRAngleLoc());
3618 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3619 TL.setArgLocInfo(i, Args[i].getLocInfo());
3620 return DI;
3621}
3622
Mike Stump11289f42009-09-09 15:08:12 +00003623QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003624ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003625 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003626 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003627 assert(!Template.getAsDependentTemplateName() &&
3628 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003629
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003630 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003631 ArgVec.reserve(Args.size());
3632 for (const TemplateArgumentLoc &Arg : Args.arguments())
3633 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003634
David Majnemer6fbeee32016-07-07 04:43:07 +00003635 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003636}
3637
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003638#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003639static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3640 for (const TemplateArgument &Arg : Args)
3641 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003642 return true;
3643
3644 return true;
3645}
3646#endif
3647
John McCall0ad16662009-10-29 08:12:44 +00003648QualType
3649ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003650 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003651 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003652 assert(!Template.getAsDependentTemplateName() &&
3653 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003654 // Look through qualified template names.
3655 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3656 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003657
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003658 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003659 Template.getAsTemplateDecl() &&
3660 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003661 QualType CanonType;
3662 if (!Underlying.isNull())
3663 CanonType = getCanonicalType(Underlying);
3664 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003665 // We can get here with an alias template when the specialization contains
3666 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003667 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003668 "Caller must compute aliased type");
3669 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003670 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003671 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003672
Douglas Gregora8e02e72009-07-28 23:00:59 +00003673 // Allocate the (non-canonical) template specialization type, but don't
3674 // try to unique it: these types typically have location information that
3675 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003676 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003677 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003678 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003679 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003680 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003681 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003682 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003683
Douglas Gregor8bf42052009-02-09 18:46:07 +00003684 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003685 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003686}
3687
David Majnemer6fbeee32016-07-07 04:43:07 +00003688QualType ASTContext::getCanonicalTemplateSpecializationType(
3689 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003690 assert(!Template.getAsDependentTemplateName() &&
3691 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003692
Douglas Gregore29139c2011-03-03 17:04:51 +00003693 // Look through qualified template names.
3694 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3695 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003696
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003697 // Build the canonical template specialization type.
3698 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003699 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003700 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003701 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003702 for (const TemplateArgument &Arg : Args)
3703 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003704
3705 // Determine whether this canonical template specialization type already
3706 // exists.
3707 llvm::FoldingSetNodeID ID;
3708 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003709 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003710
Craig Topper36250ad2014-05-12 05:36:57 +00003711 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003712 TemplateSpecializationType *Spec
3713 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3714
3715 if (!Spec) {
3716 // Allocate a new canonical template specialization type.
3717 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3718 sizeof(TemplateArgument) * NumArgs),
3719 TypeAlignment);
3720 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003721 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003722 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003723 Types.push_back(Spec);
3724 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3725 }
3726
3727 assert(Spec->isDependentType() &&
3728 "Non-dependent template-id type must have a canonical type");
3729 return QualType(Spec, 0);
3730}
3731
3732QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003733ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3734 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003735 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003736 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003737 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003738
Craig Topper36250ad2014-05-12 05:36:57 +00003739 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003740 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003741 if (T)
3742 return QualType(T, 0);
3743
Douglas Gregorc42075a2010-02-04 18:10:26 +00003744 QualType Canon = NamedType;
3745 if (!Canon.isCanonical()) {
3746 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003747 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3748 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003749 (void)CheckT;
3750 }
3751
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003752 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003753 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003754 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003755 return QualType(T, 0);
3756}
3757
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003758QualType
Jay Foad39c79802011-01-12 09:06:06 +00003759ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003760 llvm::FoldingSetNodeID ID;
3761 ParenType::Profile(ID, InnerType);
3762
Craig Topper36250ad2014-05-12 05:36:57 +00003763 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003764 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3765 if (T)
3766 return QualType(T, 0);
3767
3768 QualType Canon = InnerType;
3769 if (!Canon.isCanonical()) {
3770 Canon = getCanonicalType(InnerType);
3771 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3772 assert(!CheckT && "Paren canonical type broken");
3773 (void)CheckT;
3774 }
3775
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003776 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003777 Types.push_back(T);
3778 ParenTypes.InsertNode(T, InsertPos);
3779 return QualType(T, 0);
3780}
3781
Douglas Gregor02085352010-03-31 20:19:30 +00003782QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3783 NestedNameSpecifier *NNS,
3784 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003785 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003786 if (Canon.isNull()) {
3787 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00003788 if (CanonNNS != NNS)
3789 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003790 }
3791
3792 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003793 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003794
Craig Topper36250ad2014-05-12 05:36:57 +00003795 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003796 DependentNameType *T
3797 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003798 if (T)
3799 return QualType(T, 0);
3800
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003801 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003802 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003803 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003804 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003805}
3806
Mike Stump11289f42009-09-09 15:08:12 +00003807QualType
John McCallc392f372010-06-11 00:33:02 +00003808ASTContext::getDependentTemplateSpecializationType(
3809 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003810 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003811 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003812 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003813 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003814 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003815 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3816 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003817 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003818}
3819
3820QualType
3821ASTContext::getDependentTemplateSpecializationType(
3822 ElaboratedTypeKeyword Keyword,
3823 NestedNameSpecifier *NNS,
3824 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003825 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003826 assert((!NNS || NNS->isDependent()) &&
3827 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003828
Douglas Gregorc42075a2010-02-04 18:10:26 +00003829 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003830 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003831 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003832
Craig Topper36250ad2014-05-12 05:36:57 +00003833 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003834 DependentTemplateSpecializationType *T
3835 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003836 if (T)
3837 return QualType(T, 0);
3838
John McCallc392f372010-06-11 00:33:02 +00003839 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003840
John McCallc392f372010-06-11 00:33:02 +00003841 ElaboratedTypeKeyword CanonKeyword = Keyword;
3842 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3843
3844 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003845 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003846 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003847 for (unsigned I = 0; I != NumArgs; ++I) {
3848 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3849 if (!CanonArgs[I].structurallyEquals(Args[I]))
3850 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003851 }
3852
John McCallc392f372010-06-11 00:33:02 +00003853 QualType Canon;
3854 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3855 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003856 Name,
3857 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003858
3859 // Find the insert position again.
3860 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3861 }
3862
3863 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3864 sizeof(TemplateArgument) * NumArgs),
3865 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003866 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003867 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003868 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003869 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003870 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003871}
3872
Richard Smith43e14d22016-12-23 02:10:11 +00003873void
3874ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3875 SmallVectorImpl<TemplateArgument> &Args) {
3876 Args.reserve(Args.size() + Params->size());
3877
3878 for (NamedDecl *Param : *Params) {
3879 TemplateArgument Arg;
3880 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3881 QualType ArgType = getTypeDeclType(TTP);
3882 if (TTP->isParameterPack())
3883 ArgType = getPackExpansionType(ArgType, None);
3884
3885 Arg = TemplateArgument(ArgType);
3886 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3887 Expr *E = new (*this) DeclRefExpr(
3888 NTTP, /*enclosing*/false,
3889 NTTP->getType().getNonLValueExprType(*this),
3890 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3891
3892 if (NTTP->isParameterPack())
3893 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3894 None);
3895 Arg = TemplateArgument(E);
3896 } else {
3897 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3898 if (TTP->isParameterPack())
3899 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3900 else
3901 Arg = TemplateArgument(TemplateName(TTP));
3902 }
3903
3904 if (Param->isTemplateParameterPack())
3905 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3906
3907 Args.push_back(Arg);
3908 }
3909}
3910
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003911QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003912 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003913 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003914 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003915
3916 assert(Pattern->containsUnexpandedParameterPack() &&
3917 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003918 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003919 PackExpansionType *T
3920 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3921 if (T)
3922 return QualType(T, 0);
3923
3924 QualType Canon;
3925 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003926 Canon = getCanonicalType(Pattern);
3927 // The canonical type might not contain an unexpanded parameter pack, if it
3928 // contains an alias template specialization which ignores one of its
3929 // parameters.
3930 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003931 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003932
Richard Smith68eea502012-07-16 00:20:35 +00003933 // Find the insert position again, in case we inserted an element into
3934 // PackExpansionTypes and invalidated our insert position.
3935 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3936 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003937 }
3938
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003939 T = new (*this, TypeAlignment)
3940 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003941 Types.push_back(T);
3942 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003943 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003944}
3945
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003946/// CmpProtocolNames - Comparison predicate for sorting protocols
3947/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003948static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3949 ObjCProtocolDecl *const *RHS) {
3950 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003951}
3952
Craig Topper1f26d5b2016-01-03 19:43:23 +00003953static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3954 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003955
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003956 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3957 return false;
3958
Craig Topper1f26d5b2016-01-03 19:43:23 +00003959 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003960 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003961 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003962 return false;
3963 return true;
3964}
3965
Craig Topper6a8c1512015-10-22 01:56:18 +00003966static void
3967SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003968 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003969 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003970
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003971 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003972 for (ObjCProtocolDecl *&P : Protocols)
3973 P = P->getCanonicalDecl();
3974
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003975 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003976 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3977 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003978}
3979
John McCall8b07ec22010-05-15 11:32:37 +00003980QualType ASTContext::getObjCObjectType(QualType BaseType,
3981 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003982 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003983 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003984 llvm::makeArrayRef(Protocols, NumProtocols),
3985 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003986}
3987
3988QualType ASTContext::getObjCObjectType(
3989 QualType baseType,
3990 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003991 ArrayRef<ObjCProtocolDecl *> protocols,
3992 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003993 // If the base type is an interface and there aren't any protocols or
3994 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003995 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3996 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003997 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003998
3999 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004000 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004001 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004002 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004003 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4004 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004005
Douglas Gregore9d95f12015-07-07 03:57:35 +00004006 // Determine the type arguments to be used for canonicalization,
4007 // which may be explicitly specified here or written on the base
4008 // type.
4009 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4010 if (effectiveTypeArgs.empty()) {
4011 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4012 effectiveTypeArgs = baseObject->getTypeArgs();
4013 }
John McCallfc93cf92009-10-22 22:37:11 +00004014
Douglas Gregore9d95f12015-07-07 03:57:35 +00004015 // Build the canonical type, which has the canonical base type and a
4016 // sorted-and-uniqued list of protocols and the type arguments
4017 // canonicalized.
4018 QualType canonical;
4019 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4020 effectiveTypeArgs.end(),
4021 [&](QualType type) {
4022 return type.isCanonical();
4023 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004024 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004025 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4026 // Determine the canonical type arguments.
4027 ArrayRef<QualType> canonTypeArgs;
4028 SmallVector<QualType, 4> canonTypeArgsVec;
4029 if (!typeArgsAreCanonical) {
4030 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4031 for (auto typeArg : effectiveTypeArgs)
4032 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4033 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004034 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004035 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004036 }
4037
Douglas Gregore9d95f12015-07-07 03:57:35 +00004038 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4039 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4040 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004041 canonProtocolsVec.append(protocols.begin(), protocols.end());
4042 SortAndUniqueProtocols(canonProtocolsVec);
4043 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004044 } else {
4045 canonProtocols = protocols;
4046 }
4047
4048 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004049 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004050
John McCallfc93cf92009-10-22 22:37:11 +00004051 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004052 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4053 }
4054
Douglas Gregore9d95f12015-07-07 03:57:35 +00004055 unsigned size = sizeof(ObjCObjectTypeImpl);
4056 size += typeArgs.size() * sizeof(QualType);
4057 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4058 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004059 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004060 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4061 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004062
4063 Types.push_back(T);
4064 ObjCObjectTypes.InsertNode(T, InsertPos);
4065 return QualType(T, 0);
4066}
4067
Manman Ren3569eb52016-09-13 17:03:12 +00004068/// Apply Objective-C protocol qualifiers to the given type.
4069/// If this is for the canonical type of a type parameter, we can apply
4070/// protocol qualifiers on the ObjCObjectPointerType.
4071QualType
4072ASTContext::applyObjCProtocolQualifiers(QualType type,
4073 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4074 bool allowOnPointerType) const {
4075 hasError = false;
4076
Manman Renc5705ba2016-09-13 17:41:05 +00004077 if (const ObjCTypeParamType *objT =
4078 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4079 return getObjCTypeParamType(objT->getDecl(), protocols);
4080 }
4081
Manman Ren3569eb52016-09-13 17:03:12 +00004082 // Apply protocol qualifiers to ObjCObjectPointerType.
4083 if (allowOnPointerType) {
4084 if (const ObjCObjectPointerType *objPtr =
4085 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4086 const ObjCObjectType *objT = objPtr->getObjectType();
4087 // Merge protocol lists and construct ObjCObjectType.
4088 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4089 protocolsVec.append(objT->qual_begin(),
4090 objT->qual_end());
4091 protocolsVec.append(protocols.begin(), protocols.end());
4092 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4093 type = getObjCObjectType(
4094 objT->getBaseType(),
4095 objT->getTypeArgsAsWritten(),
4096 protocols,
4097 objT->isKindOfTypeAsWritten());
4098 return getObjCObjectPointerType(type);
4099 }
4100 }
4101
4102 // Apply protocol qualifiers to ObjCObjectType.
4103 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4104 // FIXME: Check for protocols to which the class type is already
4105 // known to conform.
4106
4107 return getObjCObjectType(objT->getBaseType(),
4108 objT->getTypeArgsAsWritten(),
4109 protocols,
4110 objT->isKindOfTypeAsWritten());
4111 }
4112
4113 // If the canonical type is ObjCObjectType, ...
4114 if (type->isObjCObjectType()) {
4115 // Silently overwrite any existing protocol qualifiers.
4116 // TODO: determine whether that's the right thing to do.
4117
4118 // FIXME: Check for protocols to which the class type is already
4119 // known to conform.
4120 return getObjCObjectType(type, { }, protocols, false);
4121 }
4122
4123 // id<protocol-list>
4124 if (type->isObjCIdType()) {
4125 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4126 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4127 objPtr->isKindOfType());
4128 return getObjCObjectPointerType(type);
4129 }
4130
4131 // Class<protocol-list>
4132 if (type->isObjCClassType()) {
4133 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4134 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4135 objPtr->isKindOfType());
4136 return getObjCObjectPointerType(type);
4137 }
4138
4139 hasError = true;
4140 return type;
4141}
4142
Manman Rene6be26c2016-09-13 17:25:08 +00004143QualType
4144ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4145 ArrayRef<ObjCProtocolDecl *> protocols,
4146 QualType Canonical) const {
4147 // Look in the folding set for an existing type.
4148 llvm::FoldingSetNodeID ID;
4149 ObjCTypeParamType::Profile(ID, Decl, protocols);
4150 void *InsertPos = nullptr;
4151 if (ObjCTypeParamType *TypeParam =
4152 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4153 return QualType(TypeParam, 0);
4154
4155 if (Canonical.isNull()) {
4156 // We canonicalize to the underlying type.
4157 Canonical = getCanonicalType(Decl->getUnderlyingType());
4158 if (!protocols.empty()) {
4159 // Apply the protocol qualifers.
4160 bool hasError;
4161 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4162 true/*allowOnPointerType*/);
4163 assert(!hasError && "Error when apply protocol qualifier to bound type");
4164 }
4165 }
4166
4167 unsigned size = sizeof(ObjCTypeParamType);
4168 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4169 void *mem = Allocate(size, TypeAlignment);
4170 ObjCTypeParamType *newType = new (mem)
4171 ObjCTypeParamType(Decl, Canonical, protocols);
4172
4173 Types.push_back(newType);
4174 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4175 return QualType(newType, 0);
4176}
4177
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004178/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4179/// protocol list adopt all protocols in QT's qualified-id protocol
4180/// list.
4181bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4182 ObjCInterfaceDecl *IC) {
4183 if (!QT->isObjCQualifiedIdType())
4184 return false;
4185
4186 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4187 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004188 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004189 if (!IC->ClassImplementsProtocol(Proto, false))
4190 return false;
4191 }
4192 return true;
4193 }
4194 return false;
4195}
4196
4197/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4198/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4199/// of protocols.
4200bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4201 ObjCInterfaceDecl *IDecl) {
4202 if (!QT->isObjCQualifiedIdType())
4203 return false;
4204 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4205 if (!OPT)
4206 return false;
4207 if (!IDecl->hasDefinition())
4208 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004209 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4210 CollectInheritedProtocols(IDecl, InheritedProtocols);
4211 if (InheritedProtocols.empty())
4212 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004213 // Check that if every protocol in list of id<plist> conforms to a protcol
4214 // of IDecl's, then bridge casting is ok.
4215 bool Conforms = false;
4216 for (auto *Proto : OPT->quals()) {
4217 Conforms = false;
4218 for (auto *PI : InheritedProtocols) {
4219 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4220 Conforms = true;
4221 break;
4222 }
4223 }
4224 if (!Conforms)
4225 break;
4226 }
4227 if (Conforms)
4228 return true;
4229
Aaron Ballman83731462014-03-17 16:14:00 +00004230 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004231 // If both the right and left sides have qualifiers.
4232 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004233 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004234 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004235 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004236 break;
4237 }
4238 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004239 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004240 }
4241 return true;
4242}
4243
John McCall8b07ec22010-05-15 11:32:37 +00004244/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4245/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004246QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004247 llvm::FoldingSetNodeID ID;
4248 ObjCObjectPointerType::Profile(ID, ObjectT);
4249
Craig Topper36250ad2014-05-12 05:36:57 +00004250 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004251 if (ObjCObjectPointerType *QT =
4252 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4253 return QualType(QT, 0);
4254
4255 // Find the canonical object type.
4256 QualType Canonical;
4257 if (!ObjectT.isCanonical()) {
4258 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4259
4260 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004261 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4262 }
4263
Douglas Gregorf85bee62010-02-08 22:59:26 +00004264 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004265 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4266 ObjCObjectPointerType *QType =
4267 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004268
Steve Narofffb4330f2009-06-17 22:40:22 +00004269 Types.push_back(QType);
4270 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004271 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004272}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004273
Douglas Gregor1c283312010-08-11 12:19:30 +00004274/// getObjCInterfaceType - Return the unique reference to the type for the
4275/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004276QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4277 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004278 if (Decl->TypeForDecl)
4279 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004280
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004281 if (PrevDecl) {
4282 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4283 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4284 return QualType(PrevDecl->TypeForDecl, 0);
4285 }
4286
Douglas Gregor7671e532011-12-16 16:34:57 +00004287 // Prefer the definition, if there is one.
4288 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4289 Decl = Def;
4290
Douglas Gregor1c283312010-08-11 12:19:30 +00004291 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4292 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4293 Decl->TypeForDecl = T;
4294 Types.push_back(T);
4295 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004296}
4297
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004298/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4299/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004300/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004301/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004302/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004303QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004304 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004305 if (tofExpr->isTypeDependent()) {
4306 llvm::FoldingSetNodeID ID;
4307 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004308
Craig Topper36250ad2014-05-12 05:36:57 +00004309 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004310 DependentTypeOfExprType *Canon
4311 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4312 if (Canon) {
4313 // We already have a "canonical" version of an identical, dependent
4314 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004315 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004316 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004317 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004318 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004319 Canon
4320 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004321 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4322 toe = Canon;
4323 }
4324 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004325 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004326 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004327 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004328 Types.push_back(toe);
4329 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004330}
4331
Steve Naroffa773cd52007-08-01 18:02:17 +00004332/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004333/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004334/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004335/// an issue. This doesn't affect the type checker, since it operates
4336/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004337QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004338 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004339 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004340 Types.push_back(tot);
4341 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004342}
4343
Richard Smith8eb1d322014-06-05 20:13:13 +00004344/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4345/// nodes. This would never be helpful, since each such type has its own
4346/// expression, and would not give a significant memory saving, since there
4347/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004348QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004349 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004350
4351 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004352 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004353 // unique dependent type. Two such decltype-specifiers refer to the same
4354 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004355 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004356 llvm::FoldingSetNodeID ID;
4357 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004358
Craig Topper36250ad2014-05-12 05:36:57 +00004359 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004360 DependentDecltypeType *Canon
4361 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004362 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004363 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004364 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004365 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004366 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004367 dt = new (*this, TypeAlignment)
4368 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004369 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004370 dt = new (*this, TypeAlignment)
4371 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004372 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004373 Types.push_back(dt);
4374 return QualType(dt, 0);
4375}
4376
Alexis Hunte852b102011-05-24 22:41:36 +00004377/// getUnaryTransformationType - We don't unique these, since the memory
4378/// savings are minimal and these are rare.
4379QualType ASTContext::getUnaryTransformType(QualType BaseType,
4380 QualType UnderlyingType,
4381 UnaryTransformType::UTTKind Kind)
4382 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004383 UnaryTransformType *ut = nullptr;
4384
4385 if (BaseType->isDependentType()) {
4386 // Look in the folding set for an existing type.
4387 llvm::FoldingSetNodeID ID;
4388 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4389
4390 void *InsertPos = nullptr;
4391 DependentUnaryTransformType *Canon
4392 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4393
4394 if (!Canon) {
4395 // Build a new, canonical __underlying_type(type) type.
4396 Canon = new (*this, TypeAlignment)
4397 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4398 Kind);
4399 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4400 }
4401 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4402 QualType(), Kind,
4403 QualType(Canon, 0));
4404 } else {
4405 QualType CanonType = getCanonicalType(UnderlyingType);
4406 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4407 UnderlyingType, Kind,
4408 CanonType);
4409 }
4410 Types.push_back(ut);
4411 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004412}
4413
Richard Smith2a7d4812013-05-04 07:00:32 +00004414/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4415/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4416/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004417QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004418 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004419 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004420 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004421
Richard Smith2a7d4812013-05-04 07:00:32 +00004422 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004423 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004424 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004425 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004426 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4427 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004428
Richard Smith74aeef52013-04-26 16:15:35 +00004429 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004430 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004431 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004432 Types.push_back(AT);
4433 if (InsertPos)
4434 AutoTypes.InsertNode(AT, InsertPos);
4435 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004436}
4437
Eli Friedman0dfb8892011-10-06 23:00:33 +00004438/// getAtomicType - Return the uniqued reference to the atomic type for
4439/// the given value type.
4440QualType ASTContext::getAtomicType(QualType T) const {
4441 // Unique pointers, to guarantee there is only one pointer of a particular
4442 // structure.
4443 llvm::FoldingSetNodeID ID;
4444 AtomicType::Profile(ID, T);
4445
Craig Topper36250ad2014-05-12 05:36:57 +00004446 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004447 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4448 return QualType(AT, 0);
4449
4450 // If the atomic value type isn't canonical, this won't be a canonical type
4451 // either, so fill in the canonical type field.
4452 QualType Canonical;
4453 if (!T.isCanonical()) {
4454 Canonical = getAtomicType(getCanonicalType(T));
4455
4456 // Get the new insert position for the node we care about.
4457 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004458 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004459 }
4460 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4461 Types.push_back(New);
4462 AtomicTypes.InsertNode(New, InsertPos);
4463 return QualType(New, 0);
4464}
4465
Richard Smith02e85f32011-04-14 22:09:26 +00004466/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4467QualType ASTContext::getAutoDeductType() const {
4468 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004469 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004470 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004471 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004472 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004473 return AutoDeductTy;
4474}
4475
4476/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4477QualType ASTContext::getAutoRRefDeductType() const {
4478 if (AutoRRefDeductTy.isNull())
4479 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4480 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4481 return AutoRRefDeductTy;
4482}
4483
Chris Lattnerfb072462007-01-23 05:45:31 +00004484/// getTagDeclType - Return the unique reference to the type for the
4485/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004486QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004487 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004488 // FIXME: What is the design on getTagDeclType when it requires casting
4489 // away const? mutable?
4490 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004491}
4492
Mike Stump11289f42009-09-09 15:08:12 +00004493/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4494/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4495/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004496CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004497 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004498}
Chris Lattnerfb072462007-01-23 05:45:31 +00004499
Hans Wennborg27541db2011-10-27 08:29:09 +00004500/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4501CanQualType ASTContext::getIntMaxType() const {
4502 return getFromTargetType(Target->getIntMaxType());
4503}
4504
4505/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4506CanQualType ASTContext::getUIntMaxType() const {
4507 return getFromTargetType(Target->getUIntMaxType());
4508}
4509
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004510/// getSignedWCharType - Return the type of "signed wchar_t".
4511/// Used when in C++, as a GCC extension.
4512QualType ASTContext::getSignedWCharType() const {
4513 // FIXME: derive from "Target" ?
4514 return WCharTy;
4515}
4516
4517/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4518/// Used when in C++, as a GCC extension.
4519QualType ASTContext::getUnsignedWCharType() const {
4520 // FIXME: derive from "Target" ?
4521 return UnsignedIntTy;
4522}
4523
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004524QualType ASTContext::getIntPtrType() const {
4525 return getFromTargetType(Target->getIntPtrType());
4526}
4527
4528QualType ASTContext::getUIntPtrType() const {
4529 return getCorrespondingUnsignedType(getIntPtrType());
4530}
4531
Hans Wennborg27541db2011-10-27 08:29:09 +00004532/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004533/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4534QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004535 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004536}
4537
Eli Friedman4e91899e2012-11-27 02:58:24 +00004538/// \brief Return the unique type for "pid_t" defined in
4539/// <sys/types.h>. We need this to compute the correct type for vfork().
4540QualType ASTContext::getProcessIDType() const {
4541 return getFromTargetType(Target->getProcessIDType());
4542}
4543
Chris Lattnera21ad802008-04-02 05:18:44 +00004544//===----------------------------------------------------------------------===//
4545// Type Operators
4546//===----------------------------------------------------------------------===//
4547
Jay Foad39c79802011-01-12 09:06:06 +00004548CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004549 // Push qualifiers into arrays, and then discard any remaining
4550 // qualifiers.
4551 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004552 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004553 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004554 QualType Result;
4555 if (isa<ArrayType>(Ty)) {
4556 Result = getArrayDecayedType(QualType(Ty,0));
4557 } else if (isa<FunctionType>(Ty)) {
4558 Result = getPointerType(QualType(Ty, 0));
4559 } else {
4560 Result = QualType(Ty, 0);
4561 }
4562
4563 return CanQualType::CreateUnsafe(Result);
4564}
4565
John McCall6c9dd522011-01-18 07:41:22 +00004566QualType ASTContext::getUnqualifiedArrayType(QualType type,
4567 Qualifiers &quals) {
4568 SplitQualType splitType = type.getSplitUnqualifiedType();
4569
4570 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4571 // the unqualified desugared type and then drops it on the floor.
4572 // We then have to strip that sugar back off with
4573 // getUnqualifiedDesugaredType(), which is silly.
4574 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004575 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004576
4577 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004578 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004579 quals = splitType.Quals;
4580 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004581 }
4582
John McCall6c9dd522011-01-18 07:41:22 +00004583 // Otherwise, recurse on the array's element type.
4584 QualType elementType = AT->getElementType();
4585 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4586
4587 // If that didn't change the element type, AT has no qualifiers, so we
4588 // can just use the results in splitType.
4589 if (elementType == unqualElementType) {
4590 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004591 quals = splitType.Quals;
4592 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004593 }
4594
4595 // Otherwise, add in the qualifiers from the outermost type, then
4596 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004597 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004598
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004599 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004600 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004601 CAT->getSizeModifier(), 0);
4602 }
4603
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004604 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004605 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004606 }
4607
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004608 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004609 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004610 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004611 VAT->getSizeModifier(),
4612 VAT->getIndexTypeCVRQualifiers(),
4613 VAT->getBracketsRange());
4614 }
4615
4616 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004617 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004618 DSAT->getSizeModifier(), 0,
4619 SourceRange());
4620}
4621
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004622/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4623/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4624/// they point to and return true. If T1 and T2 aren't pointer types
4625/// or pointer-to-member types, or if they are not similar at this
4626/// level, returns false and leaves T1 and T2 unchanged. Top-level
4627/// qualifiers on T1 and T2 are ignored. This function will typically
4628/// be called in a loop that successively "unwraps" pointer and
4629/// pointer-to-member types to compare them at each level.
4630bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4631 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4632 *T2PtrType = T2->getAs<PointerType>();
4633 if (T1PtrType && T2PtrType) {
4634 T1 = T1PtrType->getPointeeType();
4635 T2 = T2PtrType->getPointeeType();
4636 return true;
4637 }
4638
4639 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4640 *T2MPType = T2->getAs<MemberPointerType>();
4641 if (T1MPType && T2MPType &&
4642 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4643 QualType(T2MPType->getClass(), 0))) {
4644 T1 = T1MPType->getPointeeType();
4645 T2 = T2MPType->getPointeeType();
4646 return true;
4647 }
4648
David Blaikiebbafb8a2012-03-11 07:00:24 +00004649 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004650 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4651 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4652 if (T1OPType && T2OPType) {
4653 T1 = T1OPType->getPointeeType();
4654 T2 = T2OPType->getPointeeType();
4655 return true;
4656 }
4657 }
4658
4659 // FIXME: Block pointers, too?
4660
4661 return false;
4662}
4663
Jay Foad39c79802011-01-12 09:06:06 +00004664DeclarationNameInfo
4665ASTContext::getNameForTemplate(TemplateName Name,
4666 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004667 switch (Name.getKind()) {
4668 case TemplateName::QualifiedTemplate:
4669 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004670 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004671 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4672 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004673
John McCalld9dfe3a2011-06-30 08:33:18 +00004674 case TemplateName::OverloadedTemplate: {
4675 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4676 // DNInfo work in progress: CHECKME: what about DNLoc?
4677 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4678 }
4679
4680 case TemplateName::DependentTemplate: {
4681 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004682 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004683 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004684 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4685 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004686 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004687 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4688 // DNInfo work in progress: FIXME: source locations?
4689 DeclarationNameLoc DNLoc;
4690 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4691 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4692 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004693 }
4694 }
4695
John McCalld9dfe3a2011-06-30 08:33:18 +00004696 case TemplateName::SubstTemplateTemplateParm: {
4697 SubstTemplateTemplateParmStorage *subst
4698 = Name.getAsSubstTemplateTemplateParm();
4699 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4700 NameLoc);
4701 }
4702
4703 case TemplateName::SubstTemplateTemplateParmPack: {
4704 SubstTemplateTemplateParmPackStorage *subst
4705 = Name.getAsSubstTemplateTemplateParmPack();
4706 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4707 NameLoc);
4708 }
4709 }
4710
4711 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004712}
4713
Jay Foad39c79802011-01-12 09:06:06 +00004714TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004715 switch (Name.getKind()) {
4716 case TemplateName::QualifiedTemplate:
4717 case TemplateName::Template: {
4718 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004719 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004720 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004721 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4722
4723 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004724 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004725 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004726
John McCalld9dfe3a2011-06-30 08:33:18 +00004727 case TemplateName::OverloadedTemplate:
4728 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004729
John McCalld9dfe3a2011-06-30 08:33:18 +00004730 case TemplateName::DependentTemplate: {
4731 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4732 assert(DTN && "Non-dependent template names must refer to template decls.");
4733 return DTN->CanonicalTemplateName;
4734 }
4735
4736 case TemplateName::SubstTemplateTemplateParm: {
4737 SubstTemplateTemplateParmStorage *subst
4738 = Name.getAsSubstTemplateTemplateParm();
4739 return getCanonicalTemplateName(subst->getReplacement());
4740 }
4741
4742 case TemplateName::SubstTemplateTemplateParmPack: {
4743 SubstTemplateTemplateParmPackStorage *subst
4744 = Name.getAsSubstTemplateTemplateParmPack();
4745 TemplateTemplateParmDecl *canonParameter
4746 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4747 TemplateArgument canonArgPack
4748 = getCanonicalTemplateArgument(subst->getArgumentPack());
4749 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4750 }
4751 }
4752
4753 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004754}
4755
Douglas Gregoradee3e32009-11-11 23:06:43 +00004756bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4757 X = getCanonicalTemplateName(X);
4758 Y = getCanonicalTemplateName(Y);
4759 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4760}
4761
Mike Stump11289f42009-09-09 15:08:12 +00004762TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004763ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004764 switch (Arg.getKind()) {
4765 case TemplateArgument::Null:
4766 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004767
Douglas Gregora8e02e72009-07-28 23:00:59 +00004768 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004769 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004770
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004771 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004772 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004773 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004774 }
Mike Stump11289f42009-09-09 15:08:12 +00004775
Eli Friedmanb826a002012-09-26 02:36:12 +00004776 case TemplateArgument::NullPtr:
4777 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4778 /*isNullPtr*/true);
4779
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004780 case TemplateArgument::Template:
4781 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004782
4783 case TemplateArgument::TemplateExpansion:
4784 return TemplateArgument(getCanonicalTemplateName(
4785 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004786 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004787
Douglas Gregora8e02e72009-07-28 23:00:59 +00004788 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004789 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004790
Douglas Gregora8e02e72009-07-28 23:00:59 +00004791 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004792 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004793
Douglas Gregora8e02e72009-07-28 23:00:59 +00004794 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004795 if (Arg.pack_size() == 0)
4796 return Arg;
4797
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004798 TemplateArgument *CanonArgs
4799 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004800 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004801 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004802 AEnd = Arg.pack_end();
4803 A != AEnd; (void)++A, ++Idx)
4804 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004805
Benjamin Kramercce63472015-08-05 09:40:22 +00004806 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004807 }
4808 }
4809
4810 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004811 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004812}
4813
Douglas Gregor333489b2009-03-27 23:10:48 +00004814NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004815ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004816 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004817 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004818
4819 switch (NNS->getKind()) {
4820 case NestedNameSpecifier::Identifier:
4821 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004822 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004823 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4824 NNS->getAsIdentifier());
4825
4826 case NestedNameSpecifier::Namespace:
4827 // A namespace is canonical; build a nested-name-specifier with
4828 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004829 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004830 NNS->getAsNamespace()->getOriginalNamespace());
4831
4832 case NestedNameSpecifier::NamespaceAlias:
4833 // A namespace is canonical; build a nested-name-specifier with
4834 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004835 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004836 NNS->getAsNamespaceAlias()->getNamespace()
4837 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004838
4839 case NestedNameSpecifier::TypeSpec:
4840 case NestedNameSpecifier::TypeSpecWithTemplate: {
4841 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004842
4843 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4844 // break it apart into its prefix and identifier, then reconsititute those
4845 // as the canonical nested-name-specifier. This is required to canonicalize
4846 // a dependent nested-name-specifier involving typedefs of dependent-name
4847 // types, e.g.,
4848 // typedef typename T::type T1;
4849 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004850 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4851 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004852 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004853
Eli Friedman5358a0a2012-03-03 04:09:56 +00004854 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4855 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4856 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004857 return NestedNameSpecifier::Create(*this, nullptr, false,
4858 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004859 }
4860
4861 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004862 case NestedNameSpecifier::Super:
4863 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004864 return NNS;
4865 }
4866
David Blaikie8a40f702012-01-17 06:56:22 +00004867 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004868}
4869
Jay Foad39c79802011-01-12 09:06:06 +00004870const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004871 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004872 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004873 // Handle the common positive case fast.
4874 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4875 return AT;
4876 }
Mike Stump11289f42009-09-09 15:08:12 +00004877
John McCall8ccfcb52009-09-24 19:53:00 +00004878 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004879 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004880 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004881
John McCall8ccfcb52009-09-24 19:53:00 +00004882 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004883 // implements C99 6.7.3p8: "If the specification of an array type includes
4884 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004885
Chris Lattner7adf0762008-08-04 07:31:14 +00004886 // If we get here, we either have type qualifiers on the type, or we have
4887 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004888 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004889
John McCall33ddac02011-01-19 10:06:00 +00004890 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004891 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004892
Chris Lattner7adf0762008-08-04 07:31:14 +00004893 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004894 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004895 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004896 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004897
Chris Lattner7adf0762008-08-04 07:31:14 +00004898 // Otherwise, we have an array and we have qualifiers on it. Push the
4899 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004900 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004901
Chris Lattner7adf0762008-08-04 07:31:14 +00004902 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4903 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4904 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004905 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004906 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4907 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4908 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004909 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004910
Mike Stump11289f42009-09-09 15:08:12 +00004911 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004912 = dyn_cast<DependentSizedArrayType>(ATy))
4913 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004914 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004915 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004916 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004917 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004918 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004919
Chris Lattner7adf0762008-08-04 07:31:14 +00004920 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004921 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004922 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004923 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004924 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004925 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004926}
4927
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004928QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004929 if (T->isArrayType() || T->isFunctionType())
4930 return getDecayedType(T);
4931 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004932}
4933
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004934QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004935 T = getVariableArrayDecayedType(T);
4936 T = getAdjustedParameterType(T);
4937 return T.getUnqualifiedType();
4938}
4939
David Majnemerd09a51c2015-03-03 01:50:05 +00004940QualType ASTContext::getExceptionObjectType(QualType T) const {
4941 // C++ [except.throw]p3:
4942 // A throw-expression initializes a temporary object, called the exception
4943 // object, the type of which is determined by removing any top-level
4944 // cv-qualifiers from the static type of the operand of throw and adjusting
4945 // the type from "array of T" or "function returning T" to "pointer to T"
4946 // or "pointer to function returning T", [...]
4947 T = getVariableArrayDecayedType(T);
4948 if (T->isArrayType() || T->isFunctionType())
4949 T = getDecayedType(T);
4950 return T.getUnqualifiedType();
4951}
4952
Chris Lattnera21ad802008-04-02 05:18:44 +00004953/// getArrayDecayedType - Return the properly qualified result of decaying the
4954/// specified array type to a pointer. This operation is non-trivial when
4955/// handling typedefs etc. The canonical type of "T" must be an array type,
4956/// this returns a pointer to a properly qualified element of the array.
4957///
4958/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004959QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004960 // Get the element type with 'getAsArrayType' so that we don't lose any
4961 // typedefs in the element type of the array. This also handles propagation
4962 // of type qualifiers from the array type into the element type if present
4963 // (C99 6.7.3p8).
4964 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4965 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004966
Chris Lattner7adf0762008-08-04 07:31:14 +00004967 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004968
4969 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00004970 QualType Result = getQualifiedType(PtrTy,
4971 PrettyArrayType->getIndexTypeQualifiers());
4972
4973 // int x[_Nullable] -> int * _Nullable
4974 if (auto Nullability = Ty->getNullability(*this)) {
4975 Result = const_cast<ASTContext *>(this)->getAttributedType(
4976 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
4977 }
4978 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00004979}
4980
John McCall33ddac02011-01-19 10:06:00 +00004981QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4982 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004983}
4984
John McCall33ddac02011-01-19 10:06:00 +00004985QualType ASTContext::getBaseElementType(QualType type) const {
4986 Qualifiers qs;
4987 while (true) {
4988 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004989 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004990 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004991
John McCall33ddac02011-01-19 10:06:00 +00004992 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004993 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004994 }
Mike Stump11289f42009-09-09 15:08:12 +00004995
John McCall33ddac02011-01-19 10:06:00 +00004996 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004997}
4998
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004999/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005000uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005001ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5002 uint64_t ElementCount = 1;
5003 do {
5004 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005005 CA = dyn_cast_or_null<ConstantArrayType>(
5006 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005007 } while (CA);
5008 return ElementCount;
5009}
5010
Steve Naroff0af91202007-04-27 21:51:21 +00005011/// getFloatingRank - Return a relative rank for floating point types.
5012/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005013static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005014 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005015 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005016
John McCall9dd450b2009-09-21 23:43:11 +00005017 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5018 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005019 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005020 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005021 case BuiltinType::Float: return FloatRank;
5022 case BuiltinType::Double: return DoubleRank;
5023 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005024 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005025 }
5026}
5027
Mike Stump11289f42009-09-09 15:08:12 +00005028/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5029/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005030/// 'typeDomain' is a real floating point or complex type.
5031/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005032QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5033 QualType Domain) const {
5034 FloatingRank EltRank = getFloatingRank(Size);
5035 if (Domain->isComplexType()) {
5036 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00005037 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005038 case FloatRank: return FloatComplexTy;
5039 case DoubleRank: return DoubleComplexTy;
5040 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005041 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005042 }
Steve Naroff0af91202007-04-27 21:51:21 +00005043 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005044
5045 assert(Domain->isRealFloatingType() && "Unknown domain!");
5046 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00005047 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005048 case FloatRank: return FloatTy;
5049 case DoubleRank: return DoubleTy;
5050 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005051 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005052 }
David Blaikief47fa302012-01-17 02:30:50 +00005053 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005054}
5055
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005056/// getFloatingTypeOrder - Compare the rank of the two specified floating
5057/// point types, ignoring the domain of the type (i.e. 'double' ==
5058/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005059/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005060int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005061 FloatingRank LHSR = getFloatingRank(LHS);
5062 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005063
Chris Lattnerb90739d2008-04-06 23:38:49 +00005064 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005065 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005066 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005067 return 1;
5068 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005069}
5070
Chris Lattner76a00cf2008-04-06 22:59:24 +00005071/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5072/// routine will assert if passed a built-in type that isn't an integer or enum,
5073/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005074unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005075 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005076
Chris Lattner76a00cf2008-04-06 22:59:24 +00005077 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005078 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005079 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005080 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005081 case BuiltinType::Char_S:
5082 case BuiltinType::Char_U:
5083 case BuiltinType::SChar:
5084 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005085 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005086 case BuiltinType::Short:
5087 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005088 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005089 case BuiltinType::Int:
5090 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005091 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005092 case BuiltinType::Long:
5093 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005094 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005095 case BuiltinType::LongLong:
5096 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005097 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005098 case BuiltinType::Int128:
5099 case BuiltinType::UInt128:
5100 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005101 }
5102}
5103
Eli Friedman629ffb92009-08-20 04:21:42 +00005104/// \brief Whether this is a promotable bitfield reference according
5105/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5106///
5107/// \returns the type this bit-field will promote to, or NULL if no
5108/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005109QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005110 if (E->isTypeDependent() || E->isValueDependent())
5111 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005112
5113 // FIXME: We should not do this unless E->refersToBitField() is true. This
5114 // matters in C where getSourceBitField() will find bit-fields for various
5115 // cases where the source expression is not a bit-field designator.
5116
John McCalld25db7e2013-05-06 21:39:12 +00005117 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005118 if (!Field)
5119 return QualType();
5120
5121 QualType FT = Field->getType();
5122
Richard Smithcaf33902011-10-10 18:28:20 +00005123 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005124 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005125 // C++ [conv.prom]p5:
5126 // A prvalue for an integral bit-field can be converted to a prvalue of type
5127 // int if int can represent all the values of the bit-field; otherwise, it
5128 // can be converted to unsigned int if unsigned int can represent all the
5129 // values of the bit-field. If the bit-field is larger yet, no integral
5130 // promotion applies to it.
5131 // C11 6.3.1.1/2:
5132 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5133 // If an int can represent all values of the original type (as restricted by
5134 // the width, for a bit-field), the value is converted to an int; otherwise,
5135 // it is converted to an unsigned int.
5136 //
5137 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5138 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005139 if (BitWidth < IntSize)
5140 return IntTy;
5141
5142 if (BitWidth == IntSize)
5143 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5144
5145 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005146 // like the base type. GCC has some weird bugs in this area that we
5147 // deliberately do not follow (GCC follows a pre-standard resolution to
5148 // C's DR315 which treats bit-width as being part of the type, and this leaks
5149 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005150 return QualType();
5151}
5152
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005153/// getPromotedIntegerType - Returns the type that Promotable will
5154/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5155/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005156QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005157 assert(!Promotable.isNull());
5158 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005159 if (const EnumType *ET = Promotable->getAs<EnumType>())
5160 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005161
5162 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5163 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5164 // (3.9.1) can be converted to a prvalue of the first of the following
5165 // types that can represent all the values of its underlying type:
5166 // int, unsigned int, long int, unsigned long int, long long int, or
5167 // unsigned long long int [...]
5168 // FIXME: Is there some better way to compute this?
5169 if (BT->getKind() == BuiltinType::WChar_S ||
5170 BT->getKind() == BuiltinType::WChar_U ||
5171 BT->getKind() == BuiltinType::Char16 ||
5172 BT->getKind() == BuiltinType::Char32) {
5173 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5174 uint64_t FromSize = getTypeSize(BT);
5175 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5176 LongLongTy, UnsignedLongLongTy };
5177 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5178 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5179 if (FromSize < ToSize ||
5180 (FromSize == ToSize &&
5181 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5182 return PromoteTypes[Idx];
5183 }
5184 llvm_unreachable("char type should fit into long long");
5185 }
5186 }
5187
5188 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005189 if (Promotable->isSignedIntegerType())
5190 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005191 uint64_t PromotableSize = getIntWidth(Promotable);
5192 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005193 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5194 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5195}
5196
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005197/// \brief Recurses in pointer/array types until it finds an objc retainable
5198/// type and returns its ownership.
5199Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5200 while (!T.isNull()) {
5201 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5202 return T.getObjCLifetime();
5203 if (T->isArrayType())
5204 T = getBaseElementType(T);
5205 else if (const PointerType *PT = T->getAs<PointerType>())
5206 T = PT->getPointeeType();
5207 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005208 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005209 else
5210 break;
5211 }
5212
5213 return Qualifiers::OCL_None;
5214}
5215
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005216static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5217 // Incomplete enum types are not treated as integer types.
5218 // FIXME: In C++, enum types are never integer types.
5219 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5220 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005221 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005222}
5223
Mike Stump11289f42009-09-09 15:08:12 +00005224/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005225/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005226/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005227int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005228 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5229 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005230
5231 // Unwrap enums to their underlying type.
5232 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5233 LHSC = getIntegerTypeForEnum(ET);
5234 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5235 RHSC = getIntegerTypeForEnum(ET);
5236
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005237 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005238
Chris Lattner76a00cf2008-04-06 22:59:24 +00005239 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5240 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005241
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005242 unsigned LHSRank = getIntegerRank(LHSC);
5243 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005244
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005245 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5246 if (LHSRank == RHSRank) return 0;
5247 return LHSRank > RHSRank ? 1 : -1;
5248 }
Mike Stump11289f42009-09-09 15:08:12 +00005249
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005250 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5251 if (LHSUnsigned) {
5252 // If the unsigned [LHS] type is larger, return it.
5253 if (LHSRank >= RHSRank)
5254 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005255
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005256 // If the signed type can represent all values of the unsigned type, it
5257 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005258 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005259 return -1;
5260 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005261
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005262 // If the unsigned [RHS] type is larger, return it.
5263 if (RHSRank >= LHSRank)
5264 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005265
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005266 // If the signed type can represent all values of the unsigned type, it
5267 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005268 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005269 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005270}
Anders Carlsson98f07902007-08-17 05:31:46 +00005271
Ben Langmuirf5416742016-02-04 00:55:24 +00005272TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005273 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005274 assert(!CFConstantStringTagDecl &&
5275 "tag and typedef should be initialized together");
5276 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5277 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005278
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005279 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005280 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005281
Anders Carlsson98f07902007-08-17 05:31:46 +00005282 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005283 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005284 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005285 // int flags;
5286 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005287 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005288 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005289 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005290 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005291 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005292 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005293 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005294
Anders Carlsson98f07902007-08-17 05:31:46 +00005295 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005296 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005297 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005298 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005299 SourceLocation(),
5300 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005301 FieldTypes[i], /*TInfo=*/nullptr,
5302 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005303 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005304 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005305 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005306 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005307 }
5308
Ben Langmuirf5416742016-02-04 00:55:24 +00005309 CFConstantStringTagDecl->completeDefinition();
5310 // This type is designed to be compatible with NSConstantString, but cannot
5311 // use the same name, since NSConstantString is an interface.
5312 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5313 CFConstantStringTypeDecl =
5314 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005315 }
Mike Stump11289f42009-09-09 15:08:12 +00005316
Quentin Colombet043406b2016-02-03 22:41:00 +00005317 return CFConstantStringTypeDecl;
5318}
5319
Ben Langmuirf5416742016-02-04 00:55:24 +00005320RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5321 if (!CFConstantStringTagDecl)
5322 getCFConstantStringDecl(); // Build the tag and the typedef.
5323 return CFConstantStringTagDecl;
5324}
5325
Quentin Colombet043406b2016-02-03 22:41:00 +00005326// getCFConstantStringType - Return the type used for constant CFStrings.
5327QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005328 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005329}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005330
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005331QualType ASTContext::getObjCSuperType() const {
5332 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005333 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005334 TUDecl->addDecl(ObjCSuperTypeDecl);
5335 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5336 }
5337 return ObjCSuperType;
5338}
5339
Douglas Gregor512b0772009-04-23 22:29:11 +00005340void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005341 const TypedefType *TD = T->getAs<TypedefType>();
5342 assert(TD && "Invalid CFConstantStringType");
5343 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5344 auto TagType =
5345 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5346 assert(TagType && "Invalid CFConstantStringType");
5347 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005348}
5349
Jay Foad39c79802011-01-12 09:06:06 +00005350QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005351 if (BlockDescriptorType)
5352 return getTagDeclType(BlockDescriptorType);
5353
Alp Toker2dea15b2013-12-17 01:22:38 +00005354 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005355 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005356 RD = buildImplicitRecord("__block_descriptor");
5357 RD->startDefinition();
5358
Mike Stumpd0153282009-10-20 02:12:22 +00005359 QualType FieldTypes[] = {
5360 UnsignedLongTy,
5361 UnsignedLongTy,
5362 };
5363
Craig Topperd6d31ac2013-07-15 08:24:27 +00005364 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005365 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005366 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005367 };
5368
5369 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005370 FieldDecl *Field = FieldDecl::Create(
5371 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005372 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5373 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005374 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005375 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005376 }
5377
Alp Toker2dea15b2013-12-17 01:22:38 +00005378 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005379
Alp Toker2dea15b2013-12-17 01:22:38 +00005380 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005381
5382 return getTagDeclType(BlockDescriptorType);
5383}
5384
Jay Foad39c79802011-01-12 09:06:06 +00005385QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005386 if (BlockDescriptorExtendedType)
5387 return getTagDeclType(BlockDescriptorExtendedType);
5388
Alp Toker2dea15b2013-12-17 01:22:38 +00005389 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005390 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005391 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5392 RD->startDefinition();
5393
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005394 QualType FieldTypes[] = {
5395 UnsignedLongTy,
5396 UnsignedLongTy,
5397 getPointerType(VoidPtrTy),
5398 getPointerType(VoidPtrTy)
5399 };
5400
Craig Topperd6d31ac2013-07-15 08:24:27 +00005401 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005402 "reserved",
5403 "Size",
5404 "CopyFuncPtr",
5405 "DestroyFuncPtr"
5406 };
5407
5408 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005409 FieldDecl *Field = FieldDecl::Create(
5410 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005411 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5412 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005413 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005414 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005415 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005416 }
5417
Alp Toker2dea15b2013-12-17 01:22:38 +00005418 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005419
Alp Toker2dea15b2013-12-17 01:22:38 +00005420 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005421 return getTagDeclType(BlockDescriptorExtendedType);
5422}
5423
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005424/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5425/// requires copy/dispose. Note that this must match the logic
5426/// in buildByrefHelpers.
5427bool ASTContext::BlockRequiresCopying(QualType Ty,
5428 const VarDecl *D) {
5429 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5430 const Expr *copyExpr = getBlockVarCopyInits(D);
5431 if (!copyExpr && record->hasTrivialDestructor()) return false;
5432
Mike Stump94967902009-10-21 18:16:27 +00005433 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005434 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005435
5436 if (!Ty->isObjCRetainableType()) return false;
5437
5438 Qualifiers qs = Ty.getQualifiers();
5439
5440 // If we have lifetime, that dominates.
5441 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005442 switch (lifetime) {
5443 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5444
5445 // These are just bits as far as the runtime is concerned.
5446 case Qualifiers::OCL_ExplicitNone:
5447 case Qualifiers::OCL_Autoreleasing:
5448 return false;
5449
5450 // Tell the runtime that this is ARC __weak, called by the
5451 // byref routines.
5452 case Qualifiers::OCL_Weak:
5453 // ARC __strong __block variables need to be retained.
5454 case Qualifiers::OCL_Strong:
5455 return true;
5456 }
5457 llvm_unreachable("fell out of lifetime switch!");
5458 }
5459 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5460 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005461}
5462
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005463bool ASTContext::getByrefLifetime(QualType Ty,
5464 Qualifiers::ObjCLifetime &LifeTime,
5465 bool &HasByrefExtendedLayout) const {
5466
5467 if (!getLangOpts().ObjC1 ||
5468 getLangOpts().getGC() != LangOptions::NonGC)
5469 return false;
5470
5471 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005472 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005473 HasByrefExtendedLayout = true;
5474 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005475 } else if ((LifeTime = Ty.getObjCLifetime())) {
5476 // Honor the ARC qualifiers.
5477 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5478 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005479 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005480 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005481 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005482 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005483 return true;
5484}
5485
Douglas Gregorbab8a962011-09-08 01:46:34 +00005486TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5487 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005488 ObjCInstanceTypeDecl =
5489 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005490 return ObjCInstanceTypeDecl;
5491}
5492
Anders Carlsson18acd442007-10-29 06:33:42 +00005493// This returns true if a type has been typedefed to BOOL:
5494// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005495static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005496 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005497 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5498 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005499
Anders Carlssond8499822007-10-29 05:01:08 +00005500 return false;
5501}
5502
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005503/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005504/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005505CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005506 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5507 return CharUnits::Zero();
5508
Ken Dyck40775002010-01-11 17:06:35 +00005509 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005510
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005511 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005512 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005513 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005514 // Treat arrays as pointers, since that's how they're passed in.
5515 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005516 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005517 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005518}
5519
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005520bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005521 return getTargetInfo().getCXXABI().isMicrosoft() &&
5522 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005523 VD->getType()->isIntegralOrEnumerationType() &&
5524 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005525}
5526
Richard Smithd9b90092016-07-02 01:32:16 +00005527ASTContext::InlineVariableDefinitionKind
5528ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5529 if (!VD->isInline())
5530 return InlineVariableDefinitionKind::None;
5531
5532 // In almost all cases, it's a weak definition.
5533 auto *First = VD->getFirstDecl();
5534 if (!First->isConstexpr() || First->isInlineSpecified() ||
5535 !VD->isStaticDataMember())
5536 return InlineVariableDefinitionKind::Weak;
5537
5538 // If there's a file-context declaration in this translation unit, it's a
5539 // non-discardable definition.
5540 for (auto *D : VD->redecls())
5541 if (D->getLexicalDeclContext()->isFileContext())
5542 return InlineVariableDefinitionKind::Strong;
5543
5544 // If we've not seen one yet, we don't know.
5545 return InlineVariableDefinitionKind::WeakUnknown;
5546}
5547
Ken Dyck40775002010-01-11 17:06:35 +00005548static inline
5549std::string charUnitsToString(const CharUnits &CU) {
5550 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005551}
5552
John McCall351762c2011-02-07 10:33:21 +00005553/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005554/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005555std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5556 std::string S;
5557
David Chisnall950a9512009-11-17 19:33:30 +00005558 const BlockDecl *Decl = Expr->getBlockDecl();
5559 QualType BlockTy =
5560 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5561 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005562 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005563 getObjCEncodingForMethodParameter(
5564 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5565 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005566 else
Alp Toker314cc812014-01-25 16:55:45 +00005567 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005568 // Compute size of all parameters.
5569 // Start with computing size of a pointer in number of bytes.
5570 // FIXME: There might(should) be a better way of doing this computation!
5571 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005572 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5573 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005574 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005575 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005576 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005577 if (sz.isZero())
5578 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005579 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005580 ParmOffset += sz;
5581 }
5582 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005583 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005584 // Block pointer and offset.
5585 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005586
5587 // Argument types.
5588 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005589 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005590 QualType PType = PVDecl->getOriginalType();
5591 if (const ArrayType *AT =
5592 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5593 // Use array's original type only if it has known number of
5594 // elements.
5595 if (!isa<ConstantArrayType>(AT))
5596 PType = PVDecl->getType();
5597 } else if (PType->isFunctionType())
5598 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005599 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005600 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5601 S, true /*Extended*/);
5602 else
5603 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005604 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005605 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005606 }
John McCall351762c2011-02-07 10:33:21 +00005607
5608 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005609}
5610
John McCall843dfcc2016-11-29 21:57:00 +00005611std::string
5612ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5613 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005614 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005615 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005616 CharUnits ParmOffset;
5617 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005618 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005619 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005620 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005621 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005622 continue;
5623
John McCall843dfcc2016-11-29 21:57:00 +00005624 assert(sz.isPositive() &&
5625 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005626 ParmOffset += sz;
5627 }
5628 S += charUnitsToString(ParmOffset);
5629 ParmOffset = CharUnits::Zero();
5630
5631 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005632 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005633 QualType PType = PVDecl->getOriginalType();
5634 if (const ArrayType *AT =
5635 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5636 // Use array's original type only if it has known number of
5637 // elements.
5638 if (!isa<ConstantArrayType>(AT))
5639 PType = PVDecl->getType();
5640 } else if (PType->isFunctionType())
5641 PType = PVDecl->getType();
5642 getObjCEncodingForType(PType, S);
5643 S += charUnitsToString(ParmOffset);
5644 ParmOffset += getObjCEncodingTypeSize(PType);
5645 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005646
John McCall843dfcc2016-11-29 21:57:00 +00005647 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005648}
5649
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005650/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5651/// method parameter or return type. If Extended, include class names and
5652/// block object types.
5653void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5654 QualType T, std::string& S,
5655 bool Extended) const {
5656 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5657 getObjCEncodingForTypeQualifier(QT, S);
5658 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005659 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005660 true /*OutermostType*/,
5661 false /*EncodingProperty*/,
5662 false /*StructField*/,
5663 Extended /*EncodeBlockParameters*/,
5664 Extended /*EncodeClassNames*/);
5665}
5666
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005667/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005668/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005669std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5670 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005671 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005672 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005673 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005674 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5675 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005676 // Compute size of all parameters.
5677 // Start with computing size of a pointer in number of bytes.
5678 // FIXME: There might(should) be a better way of doing this computation!
5679 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005680 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005681 // The first two arguments (self and _cmd) are pointers; account for
5682 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005683 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005684 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005685 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005686 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005687 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005688 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005689 continue;
5690
Ken Dyck40775002010-01-11 17:06:35 +00005691 assert (sz.isPositive() &&
5692 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005693 ParmOffset += sz;
5694 }
Ken Dyck40775002010-01-11 17:06:35 +00005695 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005696 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005697 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005698
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005699 // Argument types.
5700 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005701 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005702 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005703 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005704 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005705 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005706 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5707 // Use array's original type only if it has known number of
5708 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005709 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005710 PType = PVDecl->getType();
5711 } else if (PType->isFunctionType())
5712 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005713 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5714 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005715 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005716 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005717 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005718
John McCall843dfcc2016-11-29 21:57:00 +00005719 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005720}
5721
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005722ObjCPropertyImplDecl *
5723ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5724 const ObjCPropertyDecl *PD,
5725 const Decl *Container) const {
5726 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005727 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005728 if (const ObjCCategoryImplDecl *CID =
5729 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005730 for (auto *PID : CID->property_impls())
5731 if (PID->getPropertyDecl() == PD)
5732 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005733 } else {
5734 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5735 for (auto *PID : OID->property_impls())
5736 if (PID->getPropertyDecl() == PD)
5737 return PID;
5738 }
5739 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005740}
5741
Daniel Dunbar4932b362008-08-28 04:38:10 +00005742/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005743/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005744/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5745/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005746/// Property attributes are stored as a comma-delimited C string. The simple
5747/// attributes readonly and bycopy are encoded as single characters. The
5748/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5749/// encoded as single characters, followed by an identifier. Property types
5750/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005751/// these attributes are defined by the following enumeration:
5752/// @code
5753/// enum PropertyAttributes {
5754/// kPropertyReadOnly = 'R', // property is read-only.
5755/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5756/// kPropertyByref = '&', // property is a reference to the value last assigned
5757/// kPropertyDynamic = 'D', // property is dynamic
5758/// kPropertyGetter = 'G', // followed by getter selector name
5759/// kPropertySetter = 'S', // followed by setter selector name
5760/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005761/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005762/// kPropertyWeak = 'W' // 'weak' property
5763/// kPropertyStrong = 'P' // property GC'able
5764/// kPropertyNonAtomic = 'N' // property non-atomic
5765/// };
5766/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005767std::string
5768ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5769 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005770 // Collect information from the property implementation decl(s).
5771 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005772 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005773
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005774 if (ObjCPropertyImplDecl *PropertyImpDecl =
5775 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5776 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5777 Dynamic = true;
5778 else
5779 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005780 }
5781
5782 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005783 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005784
5785 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005786 // GCC has some special rules regarding encoding of properties which
5787 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005788 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005789
5790 if (PD->isReadOnly()) {
5791 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005792 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5793 S += ",C";
5794 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5795 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005796 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5797 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005798 } else {
5799 switch (PD->getSetterKind()) {
5800 case ObjCPropertyDecl::Assign: break;
5801 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005802 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005803 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005804 }
5805 }
5806
5807 // It really isn't clear at all what this means, since properties
5808 // are "dynamic by default".
5809 if (Dynamic)
5810 S += ",D";
5811
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005812 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5813 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005814
Daniel Dunbar4932b362008-08-28 04:38:10 +00005815 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5816 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005817 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005818 }
5819
5820 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5821 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005822 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005823 }
5824
5825 if (SynthesizePID) {
5826 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5827 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005828 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005829 }
5830
5831 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005832 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005833}
5834
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005835/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005836/// Another legacy compatibility encoding: 32-bit longs are encoded as
5837/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005838/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5839///
5840void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005841 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005842 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005843 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005844 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005845 else
Jay Foad39c79802011-01-12 09:06:06 +00005846 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005847 PointeeTy = IntTy;
5848 }
5849 }
5850}
5851
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005852void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005853 const FieldDecl *Field,
5854 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005855 // We follow the behavior of gcc, expanding structures which are
5856 // directly pointed to, and expanding embedded structures. Note that
5857 // these rules are sufficient to prevent recursive encoding of the
5858 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005859 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005860 true /* outermost type */, false, false,
5861 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005862}
5863
Joe Groff98ac7d22014-07-07 22:25:15 +00005864void ASTContext::getObjCEncodingForPropertyType(QualType T,
5865 std::string& S) const {
5866 // Encode result type.
5867 // GCC has some special rules regarding encoding of properties which
5868 // closely resembles encoding of ivars.
5869 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5870 true /* outermost type */,
5871 true /* encoding property */);
5872}
5873
John McCall393a78d2012-12-20 02:45:14 +00005874static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5875 BuiltinType::Kind kind) {
5876 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005877 case BuiltinType::Void: return 'v';
5878 case BuiltinType::Bool: return 'B';
5879 case BuiltinType::Char_U:
5880 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005881 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005882 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005883 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005884 case BuiltinType::UInt: return 'I';
5885 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005886 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005887 case BuiltinType::UInt128: return 'T';
5888 case BuiltinType::ULongLong: return 'Q';
5889 case BuiltinType::Char_S:
5890 case BuiltinType::SChar: return 'c';
5891 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005892 case BuiltinType::WChar_S:
5893 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005894 case BuiltinType::Int: return 'i';
5895 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005896 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005897 case BuiltinType::LongLong: return 'q';
5898 case BuiltinType::Int128: return 't';
5899 case BuiltinType::Float: return 'f';
5900 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005901 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005902 case BuiltinType::NullPtr: return '*'; // like char*
5903
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005904 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005905 case BuiltinType::Half:
5906 // FIXME: potentially need @encodes for these!
5907 return ' ';
5908
5909 case BuiltinType::ObjCId:
5910 case BuiltinType::ObjCClass:
5911 case BuiltinType::ObjCSel:
5912 llvm_unreachable("@encoding ObjC primitive type");
5913
5914 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005915#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5916 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005917#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005918 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005919 case BuiltinType::OCLClkEvent:
5920 case BuiltinType::OCLQueue:
5921 case BuiltinType::OCLNDRange:
5922 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005923 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005924 case BuiltinType::Dependent:
5925#define BUILTIN_TYPE(KIND, ID)
5926#define PLACEHOLDER_TYPE(KIND, ID) \
5927 case BuiltinType::KIND:
5928#include "clang/AST/BuiltinTypes.def"
5929 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005930 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005931 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005932}
5933
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005934static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5935 EnumDecl *Enum = ET->getDecl();
5936
5937 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5938 if (!Enum->isFixed())
5939 return 'i';
5940
5941 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005942 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5943 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005944}
5945
Jay Foad39c79802011-01-12 09:06:06 +00005946static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005947 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005948 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005949 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005950 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5951 // The GNU runtime requires more information; bitfields are encoded as b,
5952 // then the offset (in bits) of the first element, then the type of the
5953 // bitfield, then the size in bits. For example, in this structure:
5954 //
5955 // struct
5956 // {
5957 // int integer;
5958 // int flags:2;
5959 // };
5960 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5961 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5962 // information is not especially sensible, but we're stuck with it for
5963 // compatibility with GCC, although providing it breaks anything that
5964 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005965 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005966 const RecordDecl *RD = FD->getParent();
5967 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005968 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005969 if (const EnumType *ET = T->getAs<EnumType>())
5970 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005971 else {
5972 const BuiltinType *BT = T->castAs<BuiltinType>();
5973 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5974 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005975 }
Richard Smithcaf33902011-10-10 18:28:20 +00005976 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005977}
5978
Daniel Dunbar07d07852009-10-18 21:17:35 +00005979// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005980void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5981 bool ExpandPointedToStructures,
5982 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005983 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005984 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005985 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005986 bool StructField,
5987 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005988 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005989 bool EncodePointerToObjCTypedef,
5990 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005991 CanQualType CT = getCanonicalType(T);
5992 switch (CT->getTypeClass()) {
5993 case Type::Builtin:
5994 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005995 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005996 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005997 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5998 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5999 else
6000 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006001 return;
Mike Stump11289f42009-09-09 15:08:12 +00006002
John McCall393a78d2012-12-20 02:45:14 +00006003 case Type::Complex: {
6004 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006005 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006006 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006007 return;
6008 }
John McCall393a78d2012-12-20 02:45:14 +00006009
6010 case Type::Atomic: {
6011 const AtomicType *AT = T->castAs<AtomicType>();
6012 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006013 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006014 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006015 }
John McCall393a78d2012-12-20 02:45:14 +00006016
6017 // encoding for pointer or reference types.
6018 case Type::Pointer:
6019 case Type::LValueReference:
6020 case Type::RValueReference: {
6021 QualType PointeeTy;
6022 if (isa<PointerType>(CT)) {
6023 const PointerType *PT = T->castAs<PointerType>();
6024 if (PT->isObjCSelType()) {
6025 S += ':';
6026 return;
6027 }
6028 PointeeTy = PT->getPointeeType();
6029 } else {
6030 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6031 }
6032
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006033 bool isReadOnly = false;
6034 // For historical/compatibility reasons, the read-only qualifier of the
6035 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6036 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006037 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006038 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006039 if (OutermostType && T.isConstQualified()) {
6040 isReadOnly = true;
6041 S += 'r';
6042 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006043 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006044 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006045 while (P->getAs<PointerType>())
6046 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006047 if (P.isConstQualified()) {
6048 isReadOnly = true;
6049 S += 'r';
6050 }
6051 }
6052 if (isReadOnly) {
6053 // Another legacy compatibility encoding. Some ObjC qualifier and type
6054 // combinations need to be rearranged.
6055 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006056 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006057 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006058 }
Mike Stump11289f42009-09-09 15:08:12 +00006059
Anders Carlssond8499822007-10-29 05:01:08 +00006060 if (PointeeTy->isCharType()) {
6061 // char pointer types should be encoded as '*' unless it is a
6062 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006063 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006064 S += '*';
6065 return;
6066 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006067 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006068 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6069 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6070 S += '#';
6071 return;
6072 }
6073 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6074 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6075 S += '@';
6076 return;
6077 }
6078 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006079 }
Anders Carlssond8499822007-10-29 05:01:08 +00006080 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006081 getLegacyIntegralTypeEncoding(PointeeTy);
6082
Mike Stump11289f42009-09-09 15:08:12 +00006083 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006084 nullptr, false, false, false, false, false, false,
6085 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006086 return;
6087 }
John McCall393a78d2012-12-20 02:45:14 +00006088
6089 case Type::ConstantArray:
6090 case Type::IncompleteArray:
6091 case Type::VariableArray: {
6092 const ArrayType *AT = cast<ArrayType>(CT);
6093
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006094 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006095 // Incomplete arrays are encoded as a pointer to the array element.
6096 S += '^';
6097
Mike Stump11289f42009-09-09 15:08:12 +00006098 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006099 false, ExpandStructures, FD);
6100 } else {
6101 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006102
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006103 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6104 S += llvm::utostr(CAT->getSize().getZExtValue());
6105 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006106 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006107 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6108 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006109 S += '0';
6110 }
Mike Stump11289f42009-09-09 15:08:12 +00006111
6112 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006113 false, ExpandStructures, FD,
6114 false, false, false, false, false, false,
6115 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006116 S += ']';
6117 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006118 return;
6119 }
Mike Stump11289f42009-09-09 15:08:12 +00006120
John McCall393a78d2012-12-20 02:45:14 +00006121 case Type::FunctionNoProto:
6122 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006123 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006124 return;
Mike Stump11289f42009-09-09 15:08:12 +00006125
John McCall393a78d2012-12-20 02:45:14 +00006126 case Type::Record: {
6127 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006128 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006129 // Anonymous structures print as '?'
6130 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6131 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006132 if (ClassTemplateSpecializationDecl *Spec
6133 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6134 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006135 llvm::raw_string_ostream OS(S);
6136 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006137 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006138 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006139 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006140 } else {
6141 S += '?';
6142 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006143 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006144 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006145 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006146 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006147 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006148 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006149 if (FD) {
6150 S += '"';
6151 S += Field->getNameAsString();
6152 S += '"';
6153 }
Mike Stump11289f42009-09-09 15:08:12 +00006154
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006155 // Special case bit-fields.
6156 if (Field->isBitField()) {
6157 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006158 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006159 } else {
6160 QualType qt = Field->getType();
6161 getLegacyIntegralTypeEncoding(qt);
6162 getObjCEncodingForTypeImpl(qt, S, false, true,
6163 FD, /*OutermostType*/false,
6164 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006165 /*StructField*/true,
6166 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006167 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006168 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006169 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006170 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006171 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006172 return;
6173 }
Mike Stump11289f42009-09-09 15:08:12 +00006174
John McCall393a78d2012-12-20 02:45:14 +00006175 case Type::BlockPointer: {
6176 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006177 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006178 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006179 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006180
6181 S += '<';
6182 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006183 getObjCEncodingForTypeImpl(
6184 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6185 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006186 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6187 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006188 // Block self
6189 S += "@?";
6190 // Block parameters
6191 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006192 for (const auto &I : FPT->param_types())
6193 getObjCEncodingForTypeImpl(
6194 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6195 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006196 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6197 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006198 }
6199 S += '>';
6200 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006201 return;
6202 }
Mike Stump11289f42009-09-09 15:08:12 +00006203
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006204 case Type::ObjCObject: {
6205 // hack to match legacy encoding of *id and *Class
6206 QualType Ty = getObjCObjectPointerType(CT);
6207 if (Ty->isObjCIdType()) {
6208 S += "{objc_object=}";
6209 return;
6210 }
6211 else if (Ty->isObjCClassType()) {
6212 S += "{objc_class=}";
6213 return;
6214 }
6215 }
6216
John McCall393a78d2012-12-20 02:45:14 +00006217 case Type::ObjCInterface: {
6218 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006219 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006220 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006221 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006222 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006223 if (ExpandStructures) {
6224 S += '=';
6225 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6226 DeepCollectObjCIvars(OI, true, Ivars);
6227 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6228 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6229 if (Field->isBitField())
6230 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6231 else
6232 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6233 false, false, false, false, false,
6234 EncodePointerToObjCTypedef,
6235 NotEncodedT);
6236 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006237 }
6238 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006239 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006240 }
Mike Stump11289f42009-09-09 15:08:12 +00006241
John McCall393a78d2012-12-20 02:45:14 +00006242 case Type::ObjCObjectPointer: {
6243 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006244 if (OPT->isObjCIdType()) {
6245 S += '@';
6246 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006247 }
Mike Stump11289f42009-09-09 15:08:12 +00006248
Steve Narofff0c86112009-10-28 22:03:49 +00006249 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6250 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6251 // Since this is a binary compatibility issue, need to consult with runtime
6252 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006253 S += '#';
6254 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006255 }
Mike Stump11289f42009-09-09 15:08:12 +00006256
Chris Lattnere7cabb92009-07-13 00:10:46 +00006257 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006258 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006259 ExpandPointedToStructures,
6260 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006261 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006262 // Note that we do extended encoding of protocol qualifer list
6263 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006264 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006265 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006266 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006267 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006268 S += '>';
6269 }
6270 S += '"';
6271 }
6272 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006273 }
Mike Stump11289f42009-09-09 15:08:12 +00006274
Chris Lattnere7cabb92009-07-13 00:10:46 +00006275 QualType PointeeTy = OPT->getPointeeType();
6276 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006277 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6278 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006279 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006280 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006281 // {...};
6282 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006283 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006284 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006285 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6286 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6287 DeepCollectObjCIvars(OI, true, Ivars);
6288 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6289 if (cast<FieldDecl>(Ivars[i]) == FD) {
6290 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006291 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006292 S += '}';
6293 return;
6294 }
6295 }
6296 }
Mike Stump11289f42009-09-09 15:08:12 +00006297 getObjCEncodingForTypeImpl(PointeeTy, S,
6298 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006299 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006300 false, false, false, false, false,
6301 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006302 return;
6303 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006304
6305 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006306 if (OPT->getInterfaceDecl() &&
6307 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006308 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006309 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006310 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006311 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006312 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006313 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006314 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006315 S += '"';
6316 }
6317 return;
6318 }
Mike Stump11289f42009-09-09 15:08:12 +00006319
John McCalla9e6e8d2010-05-17 23:56:34 +00006320 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006321 // FIXME: we shoul do better than that. 'M' is available.
6322 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006323 // This matches gcc's encoding, even though technically it is insufficient.
6324 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006325 case Type::Vector:
6326 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006327 // Until we have a coherent encoding of these three types, issue warning.
6328 { if (NotEncodedT)
6329 *NotEncodedT = T;
6330 return;
6331 }
6332
6333 // We could see an undeduced auto type here during error recovery.
6334 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006335 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00006336 return;
6337
Xiuli Pan9c14e282016-01-09 12:53:17 +00006338 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006339#define ABSTRACT_TYPE(KIND, BASE)
6340#define TYPE(KIND, BASE)
6341#define DEPENDENT_TYPE(KIND, BASE) \
6342 case Type::KIND:
6343#define NON_CANONICAL_TYPE(KIND, BASE) \
6344 case Type::KIND:
6345#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6346 case Type::KIND:
6347#include "clang/AST/TypeNodes.def"
6348 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006349 }
John McCall393a78d2012-12-20 02:45:14 +00006350 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006351}
6352
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006353void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6354 std::string &S,
6355 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006356 bool includeVBases,
6357 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006358 assert(RDecl && "Expected non-null RecordDecl");
6359 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006360 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006361 return;
6362
6363 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6364 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6365 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6366
6367 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006368 for (const auto &BI : CXXRec->bases()) {
6369 if (!BI.isVirtual()) {
6370 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006371 if (base->isEmpty())
6372 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006373 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006374 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6375 std::make_pair(offs, base));
6376 }
6377 }
6378 }
6379
6380 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006381 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006382 uint64_t offs = layout.getFieldOffset(i);
6383 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006384 std::make_pair(offs, Field));
6385 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006386 }
6387
6388 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006389 for (const auto &BI : CXXRec->vbases()) {
6390 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006391 if (base->isEmpty())
6392 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006393 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006394 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6395 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006396 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6397 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006398 }
6399 }
6400
6401 CharUnits size;
6402 if (CXXRec) {
6403 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6404 } else {
6405 size = layout.getSize();
6406 }
6407
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006408#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006409 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006410#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006411 std::multimap<uint64_t, NamedDecl *>::iterator
6412 CurLayObj = FieldOrBaseOffsets.begin();
6413
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006414 if (CXXRec && CXXRec->isDynamicClass() &&
6415 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006416 if (FD) {
6417 S += "\"_vptr$";
6418 std::string recname = CXXRec->getNameAsString();
6419 if (recname.empty()) recname = "?";
6420 S += recname;
6421 S += '"';
6422 }
6423 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006424#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006425 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006426#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006427 }
6428
6429 if (!RDecl->hasFlexibleArrayMember()) {
6430 // Mark the end of the structure.
6431 uint64_t offs = toBits(size);
6432 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006433 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006434 }
6435
6436 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006437#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006438 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006439 if (CurOffs < CurLayObj->first) {
6440 uint64_t padding = CurLayObj->first - CurOffs;
6441 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6442 // packing/alignment of members is different that normal, in which case
6443 // the encoding will be out-of-sync with the real layout.
6444 // If the runtime switches to just consider the size of types without
6445 // taking into account alignment, we could make padding explicit in the
6446 // encoding (e.g. using arrays of chars). The encoding strings would be
6447 // longer then though.
6448 CurOffs += padding;
6449 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006450#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006451
6452 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006453 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006454 break; // reached end of structure.
6455
6456 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6457 // We expand the bases without their virtual bases since those are going
6458 // in the initial structure. Note that this differs from gcc which
6459 // expands virtual bases each time one is encountered in the hierarchy,
6460 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006461 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6462 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006463 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006464#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006465 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006466#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006467 } else {
6468 FieldDecl *field = cast<FieldDecl>(dcl);
6469 if (FD) {
6470 S += '"';
6471 S += field->getNameAsString();
6472 S += '"';
6473 }
6474
6475 if (field->isBitField()) {
6476 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006477#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006478 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006479#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006480 } else {
6481 QualType qt = field->getType();
6482 getLegacyIntegralTypeEncoding(qt);
6483 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6484 /*OutermostType*/false,
6485 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006486 /*StructField*/true,
6487 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006488#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006489 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006490#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006491 }
6492 }
6493 }
6494}
6495
Mike Stump11289f42009-09-09 15:08:12 +00006496void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006497 std::string& S) const {
6498 if (QT & Decl::OBJC_TQ_In)
6499 S += 'n';
6500 if (QT & Decl::OBJC_TQ_Inout)
6501 S += 'N';
6502 if (QT & Decl::OBJC_TQ_Out)
6503 S += 'o';
6504 if (QT & Decl::OBJC_TQ_Bycopy)
6505 S += 'O';
6506 if (QT & Decl::OBJC_TQ_Byref)
6507 S += 'R';
6508 if (QT & Decl::OBJC_TQ_Oneway)
6509 S += 'V';
6510}
6511
Douglas Gregor3ea72692011-08-12 05:46:01 +00006512TypedefDecl *ASTContext::getObjCIdDecl() const {
6513 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006514 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006515 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006516 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006517 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006518 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006519}
6520
Douglas Gregor52e02802011-08-12 06:17:30 +00006521TypedefDecl *ASTContext::getObjCSelDecl() const {
6522 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006523 QualType T = getPointerType(ObjCBuiltinSelTy);
6524 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006525 }
6526 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006527}
6528
Douglas Gregor0a586182011-08-12 05:59:41 +00006529TypedefDecl *ASTContext::getObjCClassDecl() const {
6530 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006531 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006532 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006533 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006534 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006535 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006536}
6537
Douglas Gregord53ae832012-01-17 18:09:05 +00006538ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6539 if (!ObjCProtocolClassDecl) {
6540 ObjCProtocolClassDecl
6541 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6542 SourceLocation(),
6543 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006544 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006545 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006546 SourceLocation(), true);
6547 }
6548
6549 return ObjCProtocolClassDecl;
6550}
6551
Meador Inge5d3fb222012-06-16 03:34:49 +00006552//===----------------------------------------------------------------------===//
6553// __builtin_va_list Construction Functions
6554//===----------------------------------------------------------------------===//
6555
Charles Davisc7d5c942015-09-17 20:55:33 +00006556static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6557 StringRef Name) {
6558 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006559 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006560 return Context->buildImplicitTypedef(T, Name);
6561}
6562
6563static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6564 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6565}
6566
6567static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6568 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006569}
6570
6571static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6572 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006573 QualType T = Context->getPointerType(Context->VoidTy);
6574 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006575}
6576
Tim Northover9bb857a2013-01-31 12:13:10 +00006577static TypedefDecl *
6578CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006579 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006580 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006581 if (Context->getLangOpts().CPlusPlus) {
6582 // namespace std { struct __va_list {
6583 NamespaceDecl *NS;
6584 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6585 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006586 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006587 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006588 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006589 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006590 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006591 }
6592
6593 VaListTagDecl->startDefinition();
6594
6595 const size_t NumFields = 5;
6596 QualType FieldTypes[NumFields];
6597 const char *FieldNames[NumFields];
6598
6599 // void *__stack;
6600 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6601 FieldNames[0] = "__stack";
6602
6603 // void *__gr_top;
6604 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6605 FieldNames[1] = "__gr_top";
6606
6607 // void *__vr_top;
6608 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6609 FieldNames[2] = "__vr_top";
6610
6611 // int __gr_offs;
6612 FieldTypes[3] = Context->IntTy;
6613 FieldNames[3] = "__gr_offs";
6614
6615 // int __vr_offs;
6616 FieldTypes[4] = Context->IntTy;
6617 FieldNames[4] = "__vr_offs";
6618
6619 // Create fields
6620 for (unsigned i = 0; i < NumFields; ++i) {
6621 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6622 VaListTagDecl,
6623 SourceLocation(),
6624 SourceLocation(),
6625 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006626 FieldTypes[i], /*TInfo=*/nullptr,
6627 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006628 /*Mutable=*/false,
6629 ICIS_NoInit);
6630 Field->setAccess(AS_public);
6631 VaListTagDecl->addDecl(Field);
6632 }
6633 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006634 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006635 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006636
6637 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006638 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006639}
6640
Meador Inge5d3fb222012-06-16 03:34:49 +00006641static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6642 // typedef struct __va_list_tag {
6643 RecordDecl *VaListTagDecl;
6644
Alp Toker2dea15b2013-12-17 01:22:38 +00006645 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006646 VaListTagDecl->startDefinition();
6647
6648 const size_t NumFields = 5;
6649 QualType FieldTypes[NumFields];
6650 const char *FieldNames[NumFields];
6651
6652 // unsigned char gpr;
6653 FieldTypes[0] = Context->UnsignedCharTy;
6654 FieldNames[0] = "gpr";
6655
6656 // unsigned char fpr;
6657 FieldTypes[1] = Context->UnsignedCharTy;
6658 FieldNames[1] = "fpr";
6659
6660 // unsigned short reserved;
6661 FieldTypes[2] = Context->UnsignedShortTy;
6662 FieldNames[2] = "reserved";
6663
6664 // void* overflow_arg_area;
6665 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6666 FieldNames[3] = "overflow_arg_area";
6667
6668 // void* reg_save_area;
6669 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6670 FieldNames[4] = "reg_save_area";
6671
6672 // Create fields
6673 for (unsigned i = 0; i < NumFields; ++i) {
6674 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6675 SourceLocation(),
6676 SourceLocation(),
6677 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006678 FieldTypes[i], /*TInfo=*/nullptr,
6679 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006680 /*Mutable=*/false,
6681 ICIS_NoInit);
6682 Field->setAccess(AS_public);
6683 VaListTagDecl->addDecl(Field);
6684 }
6685 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006686 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006687 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6688
6689 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006690 TypedefDecl *VaListTagTypedefDecl =
6691 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6692
Meador Inge5d3fb222012-06-16 03:34:49 +00006693 QualType VaListTagTypedefType =
6694 Context->getTypedefType(VaListTagTypedefDecl);
6695
6696 // typedef __va_list_tag __builtin_va_list[1];
6697 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6698 QualType VaListTagArrayType
6699 = Context->getConstantArrayType(VaListTagTypedefType,
6700 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006701 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006702}
6703
6704static TypedefDecl *
6705CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006706 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006707 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006708 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006709 VaListTagDecl->startDefinition();
6710
6711 const size_t NumFields = 4;
6712 QualType FieldTypes[NumFields];
6713 const char *FieldNames[NumFields];
6714
6715 // unsigned gp_offset;
6716 FieldTypes[0] = Context->UnsignedIntTy;
6717 FieldNames[0] = "gp_offset";
6718
6719 // unsigned fp_offset;
6720 FieldTypes[1] = Context->UnsignedIntTy;
6721 FieldNames[1] = "fp_offset";
6722
6723 // void* overflow_arg_area;
6724 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6725 FieldNames[2] = "overflow_arg_area";
6726
6727 // void* reg_save_area;
6728 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6729 FieldNames[3] = "reg_save_area";
6730
6731 // Create fields
6732 for (unsigned i = 0; i < NumFields; ++i) {
6733 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6734 VaListTagDecl,
6735 SourceLocation(),
6736 SourceLocation(),
6737 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006738 FieldTypes[i], /*TInfo=*/nullptr,
6739 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006740 /*Mutable=*/false,
6741 ICIS_NoInit);
6742 Field->setAccess(AS_public);
6743 VaListTagDecl->addDecl(Field);
6744 }
6745 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006746 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006747 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6748
Richard Smith9b88a4c2015-07-27 05:40:23 +00006749 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006750
Richard Smith9b88a4c2015-07-27 05:40:23 +00006751 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006752 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006753 QualType VaListTagArrayType =
6754 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006755 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006756}
6757
6758static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6759 // typedef int __builtin_va_list[4];
6760 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006761 QualType IntArrayType =
6762 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006763 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006764}
6765
Logan Chien57086ce2012-10-10 06:56:20 +00006766static TypedefDecl *
6767CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006768 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006769 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006770 if (Context->getLangOpts().CPlusPlus) {
6771 // namespace std { struct __va_list {
6772 NamespaceDecl *NS;
6773 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6774 Context->getTranslationUnitDecl(),
6775 /*Inline*/false, SourceLocation(),
6776 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006777 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006778 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006779 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006780 }
6781
6782 VaListDecl->startDefinition();
6783
6784 // void * __ap;
6785 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6786 VaListDecl,
6787 SourceLocation(),
6788 SourceLocation(),
6789 &Context->Idents.get("__ap"),
6790 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006791 /*TInfo=*/nullptr,
6792 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006793 /*Mutable=*/false,
6794 ICIS_NoInit);
6795 Field->setAccess(AS_public);
6796 VaListDecl->addDecl(Field);
6797
6798 // };
6799 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006800 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006801
6802 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006803 QualType T = Context->getRecordType(VaListDecl);
6804 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006805}
6806
Ulrich Weigand47445072013-05-06 16:26:41 +00006807static TypedefDecl *
6808CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006809 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006810 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006811 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006812 VaListTagDecl->startDefinition();
6813
6814 const size_t NumFields = 4;
6815 QualType FieldTypes[NumFields];
6816 const char *FieldNames[NumFields];
6817
6818 // long __gpr;
6819 FieldTypes[0] = Context->LongTy;
6820 FieldNames[0] = "__gpr";
6821
6822 // long __fpr;
6823 FieldTypes[1] = Context->LongTy;
6824 FieldNames[1] = "__fpr";
6825
6826 // void *__overflow_arg_area;
6827 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6828 FieldNames[2] = "__overflow_arg_area";
6829
6830 // void *__reg_save_area;
6831 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6832 FieldNames[3] = "__reg_save_area";
6833
6834 // Create fields
6835 for (unsigned i = 0; i < NumFields; ++i) {
6836 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6837 VaListTagDecl,
6838 SourceLocation(),
6839 SourceLocation(),
6840 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006841 FieldTypes[i], /*TInfo=*/nullptr,
6842 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006843 /*Mutable=*/false,
6844 ICIS_NoInit);
6845 Field->setAccess(AS_public);
6846 VaListTagDecl->addDecl(Field);
6847 }
6848 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006849 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006850 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006851
Richard Smith9b88a4c2015-07-27 05:40:23 +00006852 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006853
6854 // typedef __va_list_tag __builtin_va_list[1];
6855 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006856 QualType VaListTagArrayType =
6857 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006858
Alp Toker56b5cc92013-12-15 10:36:26 +00006859 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006860}
6861
Meador Inge5d3fb222012-06-16 03:34:49 +00006862static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6863 TargetInfo::BuiltinVaListKind Kind) {
6864 switch (Kind) {
6865 case TargetInfo::CharPtrBuiltinVaList:
6866 return CreateCharPtrBuiltinVaListDecl(Context);
6867 case TargetInfo::VoidPtrBuiltinVaList:
6868 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006869 case TargetInfo::AArch64ABIBuiltinVaList:
6870 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006871 case TargetInfo::PowerABIBuiltinVaList:
6872 return CreatePowerABIBuiltinVaListDecl(Context);
6873 case TargetInfo::X86_64ABIBuiltinVaList:
6874 return CreateX86_64ABIBuiltinVaListDecl(Context);
6875 case TargetInfo::PNaClABIBuiltinVaList:
6876 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006877 case TargetInfo::AAPCSABIBuiltinVaList:
6878 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006879 case TargetInfo::SystemZBuiltinVaList:
6880 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006881 }
6882
6883 llvm_unreachable("Unhandled __builtin_va_list type kind");
6884}
6885
6886TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006887 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006888 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006889 assert(BuiltinVaListDecl->isImplicit());
6890 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006891
6892 return BuiltinVaListDecl;
6893}
6894
Richard Smith9b88a4c2015-07-27 05:40:23 +00006895Decl *ASTContext::getVaListTagDecl() const {
6896 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006897 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006898 if (!VaListTagDecl)
6899 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006900
Richard Smith9b88a4c2015-07-27 05:40:23 +00006901 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006902}
6903
Charles Davisc7d5c942015-09-17 20:55:33 +00006904TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6905 if (!BuiltinMSVaListDecl)
6906 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6907
6908 return BuiltinMSVaListDecl;
6909}
6910
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006911void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006912 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006913 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006914
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006915 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006916}
6917
John McCalld28ae272009-12-02 08:04:21 +00006918/// \brief Retrieve the template name that corresponds to a non-empty
6919/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006920TemplateName
6921ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6922 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006923 unsigned size = End - Begin;
6924 assert(size > 1 && "set is not overloaded!");
6925
6926 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6927 size * sizeof(FunctionTemplateDecl*));
6928 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6929
6930 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006931 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006932 NamedDecl *D = *I;
6933 assert(isa<FunctionTemplateDecl>(D) ||
6934 (isa<UsingShadowDecl>(D) &&
6935 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6936 *Storage++ = D;
6937 }
6938
6939 return TemplateName(OT);
6940}
6941
Douglas Gregordc572a32009-03-30 22:58:21 +00006942/// \brief Retrieve the template name that represents a qualified
6943/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006944TemplateName
6945ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6946 bool TemplateKeyword,
6947 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006948 assert(NNS && "Missing nested-name-specifier in qualified template name");
6949
Douglas Gregorc42075a2010-02-04 18:10:26 +00006950 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006951 llvm::FoldingSetNodeID ID;
6952 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6953
Craig Topper36250ad2014-05-12 05:36:57 +00006954 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006955 QualifiedTemplateName *QTN =
6956 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6957 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006958 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006959 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006960 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6961 }
6962
6963 return TemplateName(QTN);
6964}
6965
6966/// \brief Retrieve the template name that represents a dependent
6967/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006968TemplateName
6969ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6970 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006971 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006972 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006973
6974 llvm::FoldingSetNodeID ID;
6975 DependentTemplateName::Profile(ID, NNS, Name);
6976
Craig Topper36250ad2014-05-12 05:36:57 +00006977 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006978 DependentTemplateName *QTN =
6979 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6980
6981 if (QTN)
6982 return TemplateName(QTN);
6983
6984 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6985 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006986 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006987 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006988 } else {
6989 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006990 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006991 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006992 DependentTemplateName *CheckQTN =
6993 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6994 assert(!CheckQTN && "Dependent type name canonicalization broken");
6995 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006996 }
6997
6998 DependentTemplateNames.InsertNode(QTN, InsertPos);
6999 return TemplateName(QTN);
7000}
7001
Douglas Gregor71395fa2009-11-04 00:56:37 +00007002/// \brief Retrieve the template name that represents a dependent
7003/// template name such as \c MetaFun::template operator+.
7004TemplateName
7005ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007006 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007007 assert((!NNS || NNS->isDependent()) &&
7008 "Nested name specifier must be dependent");
7009
7010 llvm::FoldingSetNodeID ID;
7011 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007012
7013 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007014 DependentTemplateName *QTN
7015 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007016
7017 if (QTN)
7018 return TemplateName(QTN);
7019
7020 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7021 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007022 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007023 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007024 } else {
7025 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007026 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007027 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007028
Douglas Gregorc42075a2010-02-04 18:10:26 +00007029 DependentTemplateName *CheckQTN
7030 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7031 assert(!CheckQTN && "Dependent template name canonicalization broken");
7032 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007033 }
7034
7035 DependentTemplateNames.InsertNode(QTN, InsertPos);
7036 return TemplateName(QTN);
7037}
7038
Douglas Gregor5590be02011-01-15 06:45:20 +00007039TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007040ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7041 TemplateName replacement) const {
7042 llvm::FoldingSetNodeID ID;
7043 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007044
7045 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007046 SubstTemplateTemplateParmStorage *subst
7047 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7048
7049 if (!subst) {
7050 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7051 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7052 }
7053
7054 return TemplateName(subst);
7055}
7056
7057TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007058ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7059 const TemplateArgument &ArgPack) const {
7060 ASTContext &Self = const_cast<ASTContext &>(*this);
7061 llvm::FoldingSetNodeID ID;
7062 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007063
7064 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007065 SubstTemplateTemplateParmPackStorage *Subst
7066 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7067
7068 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007069 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007070 ArgPack.pack_size(),
7071 ArgPack.pack_begin());
7072 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7073 }
7074
7075 return TemplateName(Subst);
7076}
7077
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007078/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007079/// TargetInfo, produce the corresponding type. The unsigned @p Type
7080/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007081CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007082 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007083 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007084 case TargetInfo::SignedChar: return SignedCharTy;
7085 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007086 case TargetInfo::SignedShort: return ShortTy;
7087 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7088 case TargetInfo::SignedInt: return IntTy;
7089 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7090 case TargetInfo::SignedLong: return LongTy;
7091 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7092 case TargetInfo::SignedLongLong: return LongLongTy;
7093 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7094 }
7095
David Blaikie83d382b2011-09-23 05:06:16 +00007096 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007097}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007098
7099//===----------------------------------------------------------------------===//
7100// Type Predicates.
7101//===----------------------------------------------------------------------===//
7102
Fariborz Jahanian96207692009-02-18 21:49:28 +00007103/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7104/// garbage collection attribute.
7105///
John McCall553d45a2011-01-12 00:34:59 +00007106Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007107 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007108 return Qualifiers::GCNone;
7109
David Blaikiebbafb8a2012-03-11 07:00:24 +00007110 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007111 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7112
7113 // Default behaviour under objective-C's gc is for ObjC pointers
7114 // (or pointers to them) be treated as though they were declared
7115 // as __strong.
7116 if (GCAttrs == Qualifiers::GCNone) {
7117 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7118 return Qualifiers::Strong;
7119 else if (Ty->isPointerType())
7120 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7121 } else {
7122 // It's not valid to set GC attributes on anything that isn't a
7123 // pointer.
7124#ifndef NDEBUG
7125 QualType CT = Ty->getCanonicalTypeInternal();
7126 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7127 CT = AT->getElementType();
7128 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7129#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007130 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007131 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007132}
7133
Chris Lattner49af6a42008-04-07 06:51:04 +00007134//===----------------------------------------------------------------------===//
7135// Type Compatibility Testing
7136//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007137
Mike Stump11289f42009-09-09 15:08:12 +00007138/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007139/// compatible.
7140static bool areCompatVectorTypes(const VectorType *LHS,
7141 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007142 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007143 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007144 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007145}
7146
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007147bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7148 QualType SecondVec) {
7149 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7150 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7151
7152 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7153 return true;
7154
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007155 // Treat Neon vector types and most AltiVec vector types as if they are the
7156 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007157 const VectorType *First = FirstVec->getAs<VectorType>();
7158 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007159 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007160 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007161 First->getVectorKind() != VectorType::AltiVecPixel &&
7162 First->getVectorKind() != VectorType::AltiVecBool &&
7163 Second->getVectorKind() != VectorType::AltiVecPixel &&
7164 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007165 return true;
7166
7167 return false;
7168}
7169
Steve Naroff8e6aee52009-07-23 01:01:38 +00007170//===----------------------------------------------------------------------===//
7171// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7172//===----------------------------------------------------------------------===//
7173
7174/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7175/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007176bool
7177ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7178 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007179 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007180 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007181 for (auto *PI : rProto->protocols())
7182 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007183 return true;
7184 return false;
7185}
7186
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007187/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7188/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007189bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7190 QualType rhs) {
7191 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7192 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7193 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7194
Aaron Ballman83731462014-03-17 16:14:00 +00007195 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007196 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007197 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007198 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7199 match = true;
7200 break;
7201 }
7202 }
7203 if (!match)
7204 return false;
7205 }
7206 return true;
7207}
7208
Steve Naroff8e6aee52009-07-23 01:01:38 +00007209/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7210/// ObjCQualifiedIDType.
7211bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7212 bool compare) {
7213 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007214 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007215 lhs->isObjCIdType() || lhs->isObjCClassType())
7216 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007217 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007218 rhs->isObjCIdType() || rhs->isObjCClassType())
7219 return true;
7220
7221 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007222 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007223
Steve Naroff8e6aee52009-07-23 01:01:38 +00007224 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007225
Steve Naroff8e6aee52009-07-23 01:01:38 +00007226 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007227 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007228 // make sure we check the class hierarchy.
7229 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007230 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007231 // when comparing an id<P> on lhs with a static type on rhs,
7232 // see if static class implements all of id's protocols, directly or
7233 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007234 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007235 return false;
7236 }
7237 }
7238 // If there are no qualifiers and no interface, we have an 'id'.
7239 return true;
7240 }
Mike Stump11289f42009-09-09 15:08:12 +00007241 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007242 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007243 bool match = false;
7244
7245 // when comparing an id<P> on lhs with a static type on rhs,
7246 // see if static class implements all of id's protocols, directly or
7247 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007248 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007249 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7250 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7251 match = true;
7252 break;
7253 }
7254 }
Mike Stump11289f42009-09-09 15:08:12 +00007255 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007256 // make sure we check the class hierarchy.
7257 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007258 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007259 // when comparing an id<P> on lhs with a static type on rhs,
7260 // see if static class implements all of id's protocols, directly or
7261 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007262 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007263 match = true;
7264 break;
7265 }
7266 }
7267 }
7268 if (!match)
7269 return false;
7270 }
Mike Stump11289f42009-09-09 15:08:12 +00007271
Steve Naroff8e6aee52009-07-23 01:01:38 +00007272 return true;
7273 }
Mike Stump11289f42009-09-09 15:08:12 +00007274
Steve Naroff8e6aee52009-07-23 01:01:38 +00007275 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7276 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7277
Mike Stump11289f42009-09-09 15:08:12 +00007278 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007279 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007280 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007281 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007282 bool match = false;
7283
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007284 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007285 // see if static class implements all of id's protocols, directly or
7286 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007287 // First, lhs protocols in the qualifier list must be found, direct
7288 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007289 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007290 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7291 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7292 match = true;
7293 break;
7294 }
7295 }
7296 if (!match)
7297 return false;
7298 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007299
7300 // Static class's protocols, or its super class or category protocols
7301 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7302 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7303 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7304 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7305 // This is rather dubious but matches gcc's behavior. If lhs has
7306 // no type qualifier and its class has no static protocol(s)
7307 // assume that it is mismatch.
7308 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7309 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007310 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007311 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007312 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007313 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7314 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7315 match = true;
7316 break;
7317 }
7318 }
7319 if (!match)
7320 return false;
7321 }
7322 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007323 return true;
7324 }
7325 return false;
7326}
7327
Eli Friedman47f77112008-08-22 00:56:42 +00007328/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007329/// compatible for assignment from RHS to LHS. This handles validation of any
7330/// protocol qualifiers on the LHS or RHS.
7331///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007332bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7333 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007334 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7335 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7336
Steve Naroff1329fa02009-07-15 18:40:39 +00007337 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007338 if (LHS->isObjCUnqualifiedIdOrClass() ||
7339 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007340 return true;
7341
Douglas Gregorab209d82015-07-07 03:58:42 +00007342 // Function object that propagates a successful result or handles
7343 // __kindof types.
7344 auto finish = [&](bool succeeded) -> bool {
7345 if (succeeded)
7346 return true;
7347
7348 if (!RHS->isKindOfType())
7349 return false;
7350
7351 // Strip off __kindof and protocol qualifiers, then check whether
7352 // we can assign the other way.
7353 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7354 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7355 };
7356
7357 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7358 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7359 QualType(RHSOPT,0),
7360 false));
7361 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007362
Douglas Gregorab209d82015-07-07 03:58:42 +00007363 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7364 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7365 QualType(RHSOPT,0)));
7366 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007367
John McCall8b07ec22010-05-15 11:32:37 +00007368 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007369 if (LHS->getInterface() && RHS->getInterface()) {
7370 return finish(canAssignObjCInterfaces(LHS, RHS));
7371 }
Mike Stump11289f42009-09-09 15:08:12 +00007372
Steve Naroff8e6aee52009-07-23 01:01:38 +00007373 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007374}
7375
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007376/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007377/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007378/// arguments in block literals. When passed as arguments, passing 'A*' where
7379/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7380/// not OK. For the return type, the opposite is not OK.
7381bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7382 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007383 const ObjCObjectPointerType *RHSOPT,
7384 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007385
7386 // Function object that propagates a successful result or handles
7387 // __kindof types.
7388 auto finish = [&](bool succeeded) -> bool {
7389 if (succeeded)
7390 return true;
7391
7392 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7393 if (!Expected->isKindOfType())
7394 return false;
7395
7396 // Strip off __kindof and protocol qualifiers, then check whether
7397 // we can assign the other way.
7398 return canAssignObjCInterfacesInBlockPointer(
7399 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7400 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7401 BlockReturnType);
7402 };
7403
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007404 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007405 return true;
7406
7407 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007408 return finish(RHSOPT->isObjCBuiltinType() ||
7409 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007410 }
7411
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007412 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007413 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7414 QualType(RHSOPT,0),
7415 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007416
7417 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7418 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7419 if (LHS && RHS) { // We have 2 user-defined types.
7420 if (LHS != RHS) {
7421 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007422 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007423 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007424 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007425 }
7426 else
7427 return true;
7428 }
7429 return false;
7430}
7431
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007432/// Comparison routine for Objective-C protocols to be used with
7433/// llvm::array_pod_sort.
7434static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7435 ObjCProtocolDecl * const *rhs) {
7436 return (*lhs)->getName().compare((*rhs)->getName());
7437
7438}
7439
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007440/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007441/// of protocols inherited from two distinct objective-c pointer objects with
7442/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007443/// It is used to build composite qualifier list of the composite type of
7444/// the conditional expression involving two objective-c pointer objects.
7445static
7446void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007447 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007448 const ObjCObjectPointerType *LHSOPT,
7449 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007450 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007451
John McCall8b07ec22010-05-15 11:32:37 +00007452 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7453 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7454 assert(LHS->getInterface() && "LHS must have an interface base");
7455 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007456
7457 // Add all of the protocols for the LHS.
7458 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7459
7460 // Start with the protocol qualifiers.
7461 for (auto proto : LHS->quals()) {
7462 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007463 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007464
7465 // Also add the protocols associated with the LHS interface.
7466 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7467
7468 // Add all of the protocls for the RHS.
7469 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7470
7471 // Start with the protocol qualifiers.
7472 for (auto proto : RHS->quals()) {
7473 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007474 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007475
7476 // Also add the protocols associated with the RHS interface.
7477 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7478
7479 // Compute the intersection of the collected protocol sets.
7480 for (auto proto : LHSProtocolSet) {
7481 if (RHSProtocolSet.count(proto))
7482 IntersectionSet.push_back(proto);
7483 }
7484
7485 // Compute the set of protocols that is implied by either the common type or
7486 // the protocols within the intersection.
7487 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7488 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7489
7490 // Remove any implied protocols from the list of inherited protocols.
7491 if (!ImpliedProtocols.empty()) {
7492 IntersectionSet.erase(
7493 std::remove_if(IntersectionSet.begin(),
7494 IntersectionSet.end(),
7495 [&](ObjCProtocolDecl *proto) -> bool {
7496 return ImpliedProtocols.count(proto) > 0;
7497 }),
7498 IntersectionSet.end());
7499 }
7500
7501 // Sort the remaining protocols by name.
7502 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7503 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007504}
7505
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007506/// Determine whether the first type is a subtype of the second.
7507static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7508 QualType rhs) {
7509 // Common case: two object pointers.
7510 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7511 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7512 if (lhsOPT && rhsOPT)
7513 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7514
7515 // Two block pointers.
7516 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7517 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7518 if (lhsBlock && rhsBlock)
7519 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7520
7521 // If either is an unqualified 'id' and the other is a block, it's
7522 // acceptable.
7523 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7524 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7525 return true;
7526
7527 return false;
7528}
7529
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007530// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007531static bool sameObjCTypeArgs(ASTContext &ctx,
7532 const ObjCInterfaceDecl *iface,
7533 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007534 ArrayRef<QualType> rhsArgs,
7535 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007536 if (lhsArgs.size() != rhsArgs.size())
7537 return false;
7538
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007539 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007540 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007541 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7542 continue;
7543
7544 switch (typeParams->begin()[i]->getVariance()) {
7545 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007546 if (!stripKindOf ||
7547 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7548 rhsArgs[i].stripObjCKindOfType(ctx))) {
7549 return false;
7550 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007551 break;
7552
7553 case ObjCTypeParamVariance::Covariant:
7554 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7555 return false;
7556 break;
7557
7558 case ObjCTypeParamVariance::Contravariant:
7559 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7560 return false;
7561 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007562 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007563 }
7564
7565 return true;
7566}
7567
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007568QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007569 const ObjCObjectPointerType *Lptr,
7570 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007571 const ObjCObjectType *LHS = Lptr->getObjectType();
7572 const ObjCObjectType *RHS = Rptr->getObjectType();
7573 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7574 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007575
7576 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007577 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007578
Manman Renc46f7d12016-05-06 19:35:02 +00007579 // When either LHS or RHS is a kindof type, we should return a kindof type.
7580 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7581 // kindof(A).
7582 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7583
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007584 // Follow the left-hand side up the class hierarchy until we either hit a
7585 // root or find the RHS. Record the ancestors in case we don't find it.
7586 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7587 LHSAncestors;
7588 while (true) {
7589 // Record this ancestor. We'll need this if the common type isn't in the
7590 // path from the LHS to the root.
7591 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007592
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007593 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7594 // Get the type arguments.
7595 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7596 bool anyChanges = false;
7597 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7598 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007599 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7600 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007601 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007602 return QualType();
7603 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7604 // If only one has type arguments, the result will not have type
7605 // arguments.
7606 LHSTypeArgs = { };
7607 anyChanges = true;
7608 }
7609
7610 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007611 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007612 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7613 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007614 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007615 anyChanges = true;
7616
7617 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007618 // If we need to return a kindof type but LHS is not a kindof type, we
7619 // build a new result type.
7620 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007621 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007622 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007623 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007624 return getObjCObjectPointerType(Result);
7625 }
7626
7627 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007628 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007629
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007630 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007631 QualType LHSSuperType = LHS->getSuperClassType();
7632 if (LHSSuperType.isNull())
7633 break;
7634
7635 LHS = LHSSuperType->castAs<ObjCObjectType>();
7636 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007637
7638 // We didn't find anything by following the LHS to its root; now check
7639 // the RHS against the cached set of ancestors.
7640 while (true) {
7641 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7642 if (KnownLHS != LHSAncestors.end()) {
7643 LHS = KnownLHS->second;
7644
7645 // Get the type arguments.
7646 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7647 bool anyChanges = false;
7648 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7649 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007650 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7651 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007652 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007653 return QualType();
7654 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7655 // If only one has type arguments, the result will not have type
7656 // arguments.
7657 RHSTypeArgs = { };
7658 anyChanges = true;
7659 }
7660
7661 // Compute the intersection of protocols.
7662 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7663 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7664 Protocols);
7665 if (!Protocols.empty())
7666 anyChanges = true;
7667
Manman Renc46f7d12016-05-06 19:35:02 +00007668 // If we need to return a kindof type but RHS is not a kindof type, we
7669 // build a new result type.
7670 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007671 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007672 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007673 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007674 return getObjCObjectPointerType(Result);
7675 }
7676
7677 return getObjCObjectPointerType(QualType(RHS, 0));
7678 }
7679
7680 // Find the superclass of the RHS.
7681 QualType RHSSuperType = RHS->getSuperClassType();
7682 if (RHSSuperType.isNull())
7683 break;
7684
7685 RHS = RHSSuperType->castAs<ObjCObjectType>();
7686 }
7687
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007688 return QualType();
7689}
7690
John McCall8b07ec22010-05-15 11:32:37 +00007691bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7692 const ObjCObjectType *RHS) {
7693 assert(LHS->getInterface() && "LHS is not an interface type");
7694 assert(RHS->getInterface() && "RHS is not an interface type");
7695
Chris Lattner49af6a42008-04-07 06:51:04 +00007696 // Verify that the base decls are compatible: the RHS must be a subclass of
7697 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007698 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7699 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7700 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007701 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007702
Douglas Gregore83b9562015-07-07 03:57:53 +00007703 // If the LHS has protocol qualifiers, determine whether all of them are
7704 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7705 // LHS).
7706 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007707 // OK if conversion of LHS to SuperClass results in narrowing of types
7708 // ; i.e., SuperClass may implement at least one of the protocols
7709 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7710 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7711 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7712 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7713 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7714 // qualifiers.
7715 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007716 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007717 // If there is no protocols associated with RHS, it is not a match.
7718 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007719 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007720
7721 for (const auto *LHSProto : LHS->quals()) {
7722 bool SuperImplementsProtocol = false;
7723 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7724 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7725 SuperImplementsProtocol = true;
7726 break;
7727 }
7728 if (!SuperImplementsProtocol)
7729 return false;
7730 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007731 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007732
7733 // If the LHS is specialized, we may need to check type arguments.
7734 if (LHS->isSpecialized()) {
7735 // Follow the superclass chain until we've matched the LHS class in the
7736 // hierarchy. This substitutes type arguments through.
7737 const ObjCObjectType *RHSSuper = RHS;
7738 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7739 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7740
7741 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007742 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007743 !sameObjCTypeArgs(*this, LHS->getInterface(),
7744 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007745 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007746 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007747 }
7748 }
7749
7750 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007751}
7752
Steve Naroffb7605152009-02-12 17:52:19 +00007753bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7754 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007755 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7756 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007757
Steve Naroff7cae42b2009-07-10 23:34:53 +00007758 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007759 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007760
7761 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7762 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007763}
7764
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007765bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7766 return canAssignObjCInterfaces(
7767 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7768 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7769}
7770
Mike Stump11289f42009-09-09 15:08:12 +00007771/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007772/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007773/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007774/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007775bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7776 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007777 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007778 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007779
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007780 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007781}
7782
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007783bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007784 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007785}
7786
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007787bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7788 return !mergeTypes(LHS, RHS, true).isNull();
7789}
7790
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007791/// mergeTransparentUnionType - if T is a transparent union type and a member
7792/// of T is compatible with SubType, return the merged type, else return
7793/// QualType()
7794QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7795 bool OfBlockPointer,
7796 bool Unqualified) {
7797 if (const RecordType *UT = T->getAsUnionType()) {
7798 RecordDecl *UD = UT->getDecl();
7799 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007800 for (const auto *I : UD->fields()) {
7801 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007802 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7803 if (!MT.isNull())
7804 return MT;
7805 }
7806 }
7807 }
7808
7809 return QualType();
7810}
7811
Alp Toker9cacbab2014-01-20 20:26:09 +00007812/// mergeFunctionParameterTypes - merge two types which appear as function
7813/// parameter types
7814QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7815 bool OfBlockPointer,
7816 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007817 // GNU extension: two types are compatible if they appear as a function
7818 // argument, one of the types is a transparent union type and the other
7819 // type is compatible with a union member
7820 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7821 Unqualified);
7822 if (!lmerge.isNull())
7823 return lmerge;
7824
7825 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7826 Unqualified);
7827 if (!rmerge.isNull())
7828 return rmerge;
7829
7830 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7831}
7832
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007833QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007834 bool OfBlockPointer,
7835 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007836 const FunctionType *lbase = lhs->getAs<FunctionType>();
7837 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007838 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7839 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007840 bool allLTypes = true;
7841 bool allRTypes = true;
7842
7843 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007844 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007845 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007846 QualType RHS = rbase->getReturnType();
7847 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007848 bool UnqualifiedResult = Unqualified;
7849 if (!UnqualifiedResult)
7850 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007851 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007852 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007853 else
Alp Toker314cc812014-01-25 16:55:45 +00007854 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007855 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007856 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007857
7858 if (Unqualified)
7859 retType = retType.getUnqualifiedType();
7860
Alp Toker314cc812014-01-25 16:55:45 +00007861 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7862 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007863 if (Unqualified) {
7864 LRetType = LRetType.getUnqualifiedType();
7865 RRetType = RRetType.getUnqualifiedType();
7866 }
7867
7868 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007869 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007870 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007871 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007872
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007873 // FIXME: double check this
7874 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7875 // rbase->getRegParmAttr() != 0 &&
7876 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007877 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7878 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007879
Douglas Gregor8c940862010-01-18 17:14:39 +00007880 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007881 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007882 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007883
John McCall8c6b56f2010-12-15 01:06:38 +00007884 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007885 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7886 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007887 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7888 return QualType();
7889
John McCall31168b02011-06-15 23:02:42 +00007890 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7891 return QualType();
7892
John McCall8c6b56f2010-12-15 01:06:38 +00007893 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7894 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007895
Rafael Espindola8778c282012-11-29 16:09:03 +00007896 if (lbaseInfo.getNoReturn() != NoReturn)
7897 allLTypes = false;
7898 if (rbaseInfo.getNoReturn() != NoReturn)
7899 allRTypes = false;
7900
John McCall31168b02011-06-15 23:02:42 +00007901 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007902
Eli Friedman47f77112008-08-22 00:56:42 +00007903 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007904 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7905 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007906 // Compatible functions must have the same number of parameters
7907 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007908 return QualType();
7909
7910 // Variadic and non-variadic functions aren't compatible
7911 if (lproto->isVariadic() != rproto->isVariadic())
7912 return QualType();
7913
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007914 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7915 return QualType();
7916
John McCall18afab72016-03-01 00:49:02 +00007917 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007918 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007919
7920 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007921 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007922 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7923 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7924 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7925 QualType paramType = mergeFunctionParameterTypes(
7926 lParamType, rParamType, OfBlockPointer, Unqualified);
7927 if (paramType.isNull())
7928 return QualType();
7929
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007930 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007931 paramType = paramType.getUnqualifiedType();
7932
7933 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007934 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007935 lParamType = lParamType.getUnqualifiedType();
7936 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007937 }
Alp Toker601b22c2014-01-21 23:35:24 +00007938
7939 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007940 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007941 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007942 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007943 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007944
Eli Friedman47f77112008-08-22 00:56:42 +00007945 if (allLTypes) return lhs;
7946 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007947
7948 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7949 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007950 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007951 }
7952
7953 if (lproto) allRTypes = false;
7954 if (rproto) allLTypes = false;
7955
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007956 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007957 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007958 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007959 if (proto->isVariadic()) return QualType();
7960 // Check that the types are compatible with the types that
7961 // would result from default argument promotions (C99 6.7.5.3p15).
7962 // The only types actually affected are promotable integer
7963 // types and floats, which would be passed as a different
7964 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007965 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7966 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007967
Eli Friedman448ce402012-08-30 00:44:15 +00007968 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007969 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007970 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7971 paramTy = Enum->getDecl()->getIntegerType();
7972 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007973 return QualType();
7974 }
Alp Toker601b22c2014-01-21 23:35:24 +00007975
7976 if (paramTy->isPromotableIntegerType() ||
7977 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007978 return QualType();
7979 }
7980
7981 if (allLTypes) return lhs;
7982 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007983
7984 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7985 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007986 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007987 }
7988
7989 if (allLTypes) return lhs;
7990 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007991 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007992}
7993
John McCall433c2e62013-03-21 00:10:07 +00007994/// Given that we have an enum type and a non-enum type, try to merge them.
7995static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7996 QualType other, bool isBlockReturnType) {
7997 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7998 // a signed integer type, or an unsigned integer type.
7999 // Compatibility is based on the underlying type, not the promotion
8000 // type.
8001 QualType underlyingType = ET->getDecl()->getIntegerType();
8002 if (underlyingType.isNull()) return QualType();
8003 if (Context.hasSameType(underlyingType, other))
8004 return other;
8005
8006 // In block return types, we're more permissive and accept any
8007 // integral type of the same size.
8008 if (isBlockReturnType && other->isIntegerType() &&
8009 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8010 return other;
8011
8012 return QualType();
8013}
8014
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008015QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008016 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008017 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008018 // C++ [expr]: If an expression initially has the type "reference to T", the
8019 // type is adjusted to "T" prior to any further analysis, the expression
8020 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008021 // expression is an lvalue unless the reference is an rvalue reference and
8022 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008023 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8024 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008025
8026 if (Unqualified) {
8027 LHS = LHS.getUnqualifiedType();
8028 RHS = RHS.getUnqualifiedType();
8029 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008030
Eli Friedman47f77112008-08-22 00:56:42 +00008031 QualType LHSCan = getCanonicalType(LHS),
8032 RHSCan = getCanonicalType(RHS);
8033
8034 // If two types are identical, they are compatible.
8035 if (LHSCan == RHSCan)
8036 return LHS;
8037
John McCall8ccfcb52009-09-24 19:53:00 +00008038 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008039 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8040 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008041 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00008042 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00008043 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00008044 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
8045 return QualType();
8046 if (LQuals.isAddressSpaceSupersetOf(RQuals))
8047 return LHS;
8048 if (RQuals.isAddressSpaceSupersetOf(LQuals))
8049 return RHS;
8050 }
John McCall8ccfcb52009-09-24 19:53:00 +00008051 // If any of these qualifiers are different, we have a type
8052 // mismatch.
8053 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008054 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8055 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00008056 return QualType();
8057
8058 // Exactly one GC qualifier difference is allowed: __strong is
8059 // okay if the other type has no GC qualifier but is an Objective
8060 // C object pointer (i.e. implicitly strong by default). We fix
8061 // this by pretending that the unqualified type was actually
8062 // qualified __strong.
8063 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8064 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8065 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8066
8067 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8068 return QualType();
8069
8070 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8071 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8072 }
8073 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8074 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8075 }
Eli Friedman47f77112008-08-22 00:56:42 +00008076 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008077 }
8078
8079 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008080
Eli Friedmandcca6332009-06-01 01:22:52 +00008081 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8082 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008083
Chris Lattnerfd652912008-01-14 05:45:46 +00008084 // We want to consider the two function types to be the same for these
8085 // comparisons, just force one to the other.
8086 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8087 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008088
8089 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008090 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8091 LHSClass = Type::ConstantArray;
8092 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8093 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008094
John McCall8b07ec22010-05-15 11:32:37 +00008095 // ObjCInterfaces are just specialized ObjCObjects.
8096 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8097 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8098
Nate Begemance4d7fc2008-04-18 23:10:10 +00008099 // Canonicalize ExtVector -> Vector.
8100 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8101 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008102
Chris Lattner95554662008-04-07 05:43:21 +00008103 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008104 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008105 // Note that we only have special rules for turning block enum
8106 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008107 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008108 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008109 }
John McCall9dd450b2009-09-21 23:43:11 +00008110 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008111 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008112 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008113 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008114 if (OfBlockPointer && !BlockReturnType) {
8115 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8116 return LHS;
8117 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8118 return RHS;
8119 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008120
Eli Friedman47f77112008-08-22 00:56:42 +00008121 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008122 }
Eli Friedman47f77112008-08-22 00:56:42 +00008123
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008124 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008125 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008126#define TYPE(Class, Base)
8127#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008128#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008129#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8130#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8131#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008132 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008133
Richard Smith27d807c2013-04-30 13:56:41 +00008134 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008135 case Type::LValueReference:
8136 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008137 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008138 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008139
John McCall8b07ec22010-05-15 11:32:37 +00008140 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008141 case Type::IncompleteArray:
8142 case Type::VariableArray:
8143 case Type::FunctionProto:
8144 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008145 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008146
Chris Lattnerfd652912008-01-14 05:45:46 +00008147 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008148 {
8149 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008150 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8151 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008152 if (Unqualified) {
8153 LHSPointee = LHSPointee.getUnqualifiedType();
8154 RHSPointee = RHSPointee.getUnqualifiedType();
8155 }
8156 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8157 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008158 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008159 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008160 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008161 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008162 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008163 return getPointerType(ResultType);
8164 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008165 case Type::BlockPointer:
8166 {
8167 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008168 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8169 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008170 if (Unqualified) {
8171 LHSPointee = LHSPointee.getUnqualifiedType();
8172 RHSPointee = RHSPointee.getUnqualifiedType();
8173 }
8174 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8175 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008176 if (ResultType.isNull()) return QualType();
8177 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8178 return LHS;
8179 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8180 return RHS;
8181 return getBlockPointerType(ResultType);
8182 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008183 case Type::Atomic:
8184 {
8185 // Merge two pointer types, while trying to preserve typedef info
8186 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8187 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8188 if (Unqualified) {
8189 LHSValue = LHSValue.getUnqualifiedType();
8190 RHSValue = RHSValue.getUnqualifiedType();
8191 }
8192 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8193 Unqualified);
8194 if (ResultType.isNull()) return QualType();
8195 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8196 return LHS;
8197 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8198 return RHS;
8199 return getAtomicType(ResultType);
8200 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008201 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008202 {
8203 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8204 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8205 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8206 return QualType();
8207
8208 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8209 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008210 if (Unqualified) {
8211 LHSElem = LHSElem.getUnqualifiedType();
8212 RHSElem = RHSElem.getUnqualifiedType();
8213 }
8214
8215 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008216 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008217 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8218 return LHS;
8219 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8220 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008221 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8222 ArrayType::ArraySizeModifier(), 0);
8223 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8224 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008225 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8226 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008227 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8228 return LHS;
8229 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8230 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008231 if (LVAT) {
8232 // FIXME: This isn't correct! But tricky to implement because
8233 // the array's size has to be the size of LHS, but the type
8234 // has to be different.
8235 return LHS;
8236 }
8237 if (RVAT) {
8238 // FIXME: This isn't correct! But tricky to implement because
8239 // the array's size has to be the size of RHS, but the type
8240 // has to be different.
8241 return RHS;
8242 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008243 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8244 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008245 return getIncompleteArrayType(ResultType,
8246 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008247 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008248 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008249 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008250 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008251 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008252 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008253 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008254 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008255 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008256 case Type::Complex:
8257 // Distinct complex types are incompatible.
8258 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008259 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008260 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008261 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8262 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008263 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008264 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008265 case Type::ObjCObject: {
8266 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008267 // FIXME: This should be type compatibility, e.g. whether
8268 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008269 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8270 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8271 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008272 return LHS;
8273
Eli Friedman47f77112008-08-22 00:56:42 +00008274 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008275 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008276 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008277 if (OfBlockPointer) {
8278 if (canAssignObjCInterfacesInBlockPointer(
8279 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008280 RHS->getAs<ObjCObjectPointerType>(),
8281 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008282 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008283 return QualType();
8284 }
John McCall9dd450b2009-09-21 23:43:11 +00008285 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8286 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008287 return LHS;
8288
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008289 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008290 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008291 case Type::Pipe:
8292 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008293 assert(LHS != RHS &&
8294 "Equivalent pipe types should have already been handled!");
8295 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008296 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008297 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008298
David Blaikie8a40f702012-01-17 06:56:22 +00008299 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008300}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008301
John McCall18afab72016-03-01 00:49:02 +00008302bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8303 const FunctionProtoType *firstFnType,
8304 const FunctionProtoType *secondFnType) {
8305 // Fast path: if the first type doesn't have ext parameter infos,
8306 // we match if and only if they second type also doesn't have them.
8307 if (!firstFnType->hasExtParameterInfos())
8308 return !secondFnType->hasExtParameterInfos();
8309
8310 // Otherwise, we can only match if the second type has them.
8311 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008312 return false;
John McCall18afab72016-03-01 00:49:02 +00008313
8314 auto firstEPI = firstFnType->getExtParameterInfos();
8315 auto secondEPI = secondFnType->getExtParameterInfos();
8316 assert(firstEPI.size() == secondEPI.size());
8317
8318 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8319 if (firstEPI[i] != secondEPI[i])
8320 return false;
8321 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008322 return true;
8323}
8324
Chandler Carruth21c90602015-12-30 03:24:14 +00008325void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8326 ObjCLayouts[CD] = nullptr;
8327}
8328
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008329/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8330/// 'RHS' attributes and returns the merged version; including for function
8331/// return types.
8332QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8333 QualType LHSCan = getCanonicalType(LHS),
8334 RHSCan = getCanonicalType(RHS);
8335 // If two types are identical, they are compatible.
8336 if (LHSCan == RHSCan)
8337 return LHS;
8338 if (RHSCan->isFunctionType()) {
8339 if (!LHSCan->isFunctionType())
8340 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008341 QualType OldReturnType =
8342 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008343 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008344 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008345 QualType ResReturnType =
8346 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8347 if (ResReturnType.isNull())
8348 return QualType();
8349 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8350 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8351 // In either case, use OldReturnType to build the new function type.
8352 const FunctionType *F = LHS->getAs<FunctionType>();
8353 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008354 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8355 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008356 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008357 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008358 return ResultType;
8359 }
8360 }
8361 return QualType();
8362 }
8363
8364 // If the qualifiers are different, the types can still be merged.
8365 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8366 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8367 if (LQuals != RQuals) {
8368 // If any of these qualifiers are different, we have a type mismatch.
8369 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8370 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8371 return QualType();
8372
8373 // Exactly one GC qualifier difference is allowed: __strong is
8374 // okay if the other type has no GC qualifier but is an Objective
8375 // C object pointer (i.e. implicitly strong by default). We fix
8376 // this by pretending that the unqualified type was actually
8377 // qualified __strong.
8378 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8379 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8380 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8381
8382 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8383 return QualType();
8384
8385 if (GC_L == Qualifiers::Strong)
8386 return LHS;
8387 if (GC_R == Qualifiers::Strong)
8388 return RHS;
8389 return QualType();
8390 }
8391
8392 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8393 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8394 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8395 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8396 if (ResQT == LHSBaseQT)
8397 return LHS;
8398 if (ResQT == RHSBaseQT)
8399 return RHS;
8400 }
8401 return QualType();
8402}
8403
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008404//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008405// Integer Predicates
8406//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008407
Jay Foad39c79802011-01-12 09:06:06 +00008408unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008409 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008410 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008411 if (T->isBooleanType())
8412 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008413 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008414 return (unsigned)getTypeSize(T);
8415}
8416
Abramo Bagnara13640492012-09-09 10:21:24 +00008417QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008418 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008419
8420 // Turn <4 x signed int> -> <4 x unsigned int>
8421 if (const VectorType *VTy = T->getAs<VectorType>())
8422 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008423 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008424
8425 // For enums, we return the unsigned version of the base type.
8426 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008427 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008428
8429 const BuiltinType *BTy = T->getAs<BuiltinType>();
8430 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008431 switch (BTy->getKind()) {
8432 case BuiltinType::Char_S:
8433 case BuiltinType::SChar:
8434 return UnsignedCharTy;
8435 case BuiltinType::Short:
8436 return UnsignedShortTy;
8437 case BuiltinType::Int:
8438 return UnsignedIntTy;
8439 case BuiltinType::Long:
8440 return UnsignedLongTy;
8441 case BuiltinType::LongLong:
8442 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008443 case BuiltinType::Int128:
8444 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008445 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008446 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008447 }
8448}
8449
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008450ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008451
Richard Smith1fa5d642013-05-11 05:45:24 +00008452void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8453 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008454
8455//===----------------------------------------------------------------------===//
8456// Builtin Type Computation
8457//===----------------------------------------------------------------------===//
8458
8459/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008460/// pointer over the consumed characters. This returns the resultant type. If
8461/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8462/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8463/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008464///
8465/// RequiresICE is filled in on return to indicate whether the value is required
8466/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008467static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008468 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008469 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008470 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008471 // Modifiers.
8472 int HowLong = 0;
8473 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008474 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008475
Chris Lattnerdc226c22010-10-01 22:42:38 +00008476 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008477 bool Done = false;
8478 while (!Done) {
8479 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008480 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008481 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008482 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008483 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008484 case 'S':
8485 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8486 assert(!Signed && "Can't use 'S' modifier multiple times!");
8487 Signed = true;
8488 break;
8489 case 'U':
8490 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008491 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008492 Unsigned = true;
8493 break;
8494 case 'L':
8495 assert(HowLong <= 2 && "Can't have LLLL modifier");
8496 ++HowLong;
8497 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008498 case 'W':
8499 // This modifier represents int64 type.
8500 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8501 switch (Context.getTargetInfo().getInt64Type()) {
8502 default:
8503 llvm_unreachable("Unexpected integer type");
8504 case TargetInfo::SignedLong:
8505 HowLong = 1;
8506 break;
8507 case TargetInfo::SignedLongLong:
8508 HowLong = 2;
8509 break;
8510 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008511 }
8512 }
8513
8514 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008515
Chris Lattnerecd79c62009-06-14 00:45:47 +00008516 // Read the base type.
8517 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008518 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008519 case 'v':
8520 assert(HowLong == 0 && !Signed && !Unsigned &&
8521 "Bad modifiers used with 'v'!");
8522 Type = Context.VoidTy;
8523 break;
Jack Carter24bef982013-08-15 15:16:57 +00008524 case 'h':
8525 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008526 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008527 Type = Context.HalfTy;
8528 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008529 case 'f':
8530 assert(HowLong == 0 && !Signed && !Unsigned &&
8531 "Bad modifiers used with 'f'!");
8532 Type = Context.FloatTy;
8533 break;
8534 case 'd':
8535 assert(HowLong < 2 && !Signed && !Unsigned &&
8536 "Bad modifiers used with 'd'!");
8537 if (HowLong)
8538 Type = Context.LongDoubleTy;
8539 else
8540 Type = Context.DoubleTy;
8541 break;
8542 case 's':
8543 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8544 if (Unsigned)
8545 Type = Context.UnsignedShortTy;
8546 else
8547 Type = Context.ShortTy;
8548 break;
8549 case 'i':
8550 if (HowLong == 3)
8551 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8552 else if (HowLong == 2)
8553 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8554 else if (HowLong == 1)
8555 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8556 else
8557 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8558 break;
8559 case 'c':
8560 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8561 if (Signed)
8562 Type = Context.SignedCharTy;
8563 else if (Unsigned)
8564 Type = Context.UnsignedCharTy;
8565 else
8566 Type = Context.CharTy;
8567 break;
8568 case 'b': // boolean
8569 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8570 Type = Context.BoolTy;
8571 break;
8572 case 'z': // size_t.
8573 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8574 Type = Context.getSizeType();
8575 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008576 case 'w': // wchar_t.
8577 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8578 Type = Context.getWideCharType();
8579 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008580 case 'F':
8581 Type = Context.getCFConstantStringType();
8582 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008583 case 'G':
8584 Type = Context.getObjCIdType();
8585 break;
8586 case 'H':
8587 Type = Context.getObjCSelType();
8588 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008589 case 'M':
8590 Type = Context.getObjCSuperType();
8591 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008592 case 'a':
8593 Type = Context.getBuiltinVaListType();
8594 assert(!Type.isNull() && "builtin va list type not initialized!");
8595 break;
8596 case 'A':
8597 // This is a "reference" to a va_list; however, what exactly
8598 // this means depends on how va_list is defined. There are two
8599 // different kinds of va_list: ones passed by value, and ones
8600 // passed by reference. An example of a by-value va_list is
8601 // x86, where va_list is a char*. An example of by-ref va_list
8602 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8603 // we want this argument to be a char*&; for x86-64, we want
8604 // it to be a __va_list_tag*.
8605 Type = Context.getBuiltinVaListType();
8606 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008607 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008608 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008609 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008610 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008611 break;
8612 case 'V': {
8613 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008614 unsigned NumElements = strtoul(Str, &End, 10);
8615 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008616 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008617
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008618 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8619 RequiresICE, false);
8620 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008621
8622 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008623 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008624 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008625 break;
8626 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008627 case 'E': {
8628 char *End;
8629
8630 unsigned NumElements = strtoul(Str, &End, 10);
8631 assert(End != Str && "Missing vector size");
8632
8633 Str = End;
8634
8635 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8636 false);
8637 Type = Context.getExtVectorType(ElementType, NumElements);
8638 break;
8639 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008640 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008641 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8642 false);
8643 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008644 Type = Context.getComplexType(ElementType);
8645 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008646 }
8647 case 'Y' : {
8648 Type = Context.getPointerDiffType();
8649 break;
8650 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008651 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008652 Type = Context.getFILEType();
8653 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008654 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008655 return QualType();
8656 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008657 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008658 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008659 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008660 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008661 else
8662 Type = Context.getjmp_bufType();
8663
Mike Stump2adb4da2009-07-28 23:47:15 +00008664 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008665 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008666 return QualType();
8667 }
8668 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008669 case 'K':
8670 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8671 Type = Context.getucontext_tType();
8672
8673 if (Type.isNull()) {
8674 Error = ASTContext::GE_Missing_ucontext;
8675 return QualType();
8676 }
8677 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008678 case 'p':
8679 Type = Context.getProcessIDType();
8680 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008681 }
Mike Stump11289f42009-09-09 15:08:12 +00008682
Chris Lattnerdc226c22010-10-01 22:42:38 +00008683 // If there are modifiers and if we're allowed to parse them, go for it.
8684 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008685 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008686 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008687 default: Done = true; --Str; break;
8688 case '*':
8689 case '&': {
8690 // Both pointers and references can have their pointee types
8691 // qualified with an address space.
8692 char *End;
8693 unsigned AddrSpace = strtoul(Str, &End, 10);
8694 if (End != Str && AddrSpace != 0) {
8695 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8696 Str = End;
8697 }
8698 if (c == '*')
8699 Type = Context.getPointerType(Type);
8700 else
8701 Type = Context.getLValueReferenceType(Type);
8702 break;
8703 }
8704 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8705 case 'C':
8706 Type = Type.withConst();
8707 break;
8708 case 'D':
8709 Type = Context.getVolatileType(Type);
8710 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008711 case 'R':
8712 Type = Type.withRestrict();
8713 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008714 }
8715 }
Chris Lattner84733392010-10-01 07:13:18 +00008716
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008717 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008718 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008719
Chris Lattnerecd79c62009-06-14 00:45:47 +00008720 return Type;
8721}
8722
8723/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008724QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008725 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008726 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008727 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008728
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008729 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008730
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008731 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008732 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008733 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8734 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008735 if (Error != GE_None)
8736 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008737
8738 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8739
Chris Lattnerecd79c62009-06-14 00:45:47 +00008740 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008741 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008742 if (Error != GE_None)
8743 return QualType();
8744
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008745 // If this argument is required to be an IntegerConstantExpression and the
8746 // caller cares, fill in the bitmask we return.
8747 if (RequiresICE && IntegerConstantArgs)
8748 *IntegerConstantArgs |= 1 << ArgTypes.size();
8749
Chris Lattnerecd79c62009-06-14 00:45:47 +00008750 // Do array -> pointer decay. The builtin should use the decayed type.
8751 if (Ty->isArrayType())
8752 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008753
Chris Lattnerecd79c62009-06-14 00:45:47 +00008754 ArgTypes.push_back(Ty);
8755 }
8756
David Majnemerba3e5ec2015-03-13 18:26:17 +00008757 if (Id == Builtin::BI__GetExceptionInfo)
8758 return QualType();
8759
Chris Lattnerecd79c62009-06-14 00:45:47 +00008760 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8761 "'.' should only occur at end of builtin type list!");
8762
Reid Kleckner78af0702013-08-27 23:08:25 +00008763 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008764 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8765
8766 bool Variadic = (TypeStr[0] == '.');
8767
Richard Smith836de6b2016-12-19 23:59:34 +00008768 // We really shouldn't be making a no-proto type here.
8769 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008770 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008771
John McCalldb40c7f2010-12-14 08:05:40 +00008772 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008773 EPI.ExtInfo = EI;
8774 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008775 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8776 EPI.ExceptionSpec.Type =
8777 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008778
Jordan Rose5c382722013-03-08 21:51:21 +00008779 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008780}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008781
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008782static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8783 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008784 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008785 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008786
Rafael Espindola3ae00052013-05-13 00:12:11 +00008787 GVALinkage External = GVA_StrongExternal;
8788 switch (FD->getTemplateSpecializationKind()) {
8789 case TSK_Undeclared:
8790 case TSK_ExplicitSpecialization:
8791 External = GVA_StrongExternal;
8792 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008793
Rafael Espindola3ae00052013-05-13 00:12:11 +00008794 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008795 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008796
David Majnemerc3d07332014-05-15 06:25:57 +00008797 // C++11 [temp.explicit]p10:
8798 // [ Note: The intent is that an inline function that is the subject of
8799 // an explicit instantiation declaration will still be implicitly
8800 // instantiated when used so that the body can be considered for
8801 // inlining, but that no out-of-line copy of the inline function would be
8802 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008803 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008804 return GVA_AvailableExternally;
8805
Rafael Espindola3ae00052013-05-13 00:12:11 +00008806 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008807 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008808 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008809 }
8810
8811 if (!FD->isInlined())
8812 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008813
David Majnemer3f021502015-10-08 04:53:31 +00008814 if ((!Context.getLangOpts().CPlusPlus &&
8815 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008816 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008817 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008818 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8819
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008820 // GNU or C99 inline semantics. Determine whether this symbol should be
8821 // externally visible.
8822 if (FD->isInlineDefinitionExternallyVisible())
8823 return External;
8824
8825 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008826 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008827 }
8828
David Majnemer54e3ba52014-04-02 23:17:29 +00008829 // Functions specified with extern and inline in -fms-compatibility mode
8830 // forcibly get emitted. While the body of the function cannot be later
8831 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008832 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008833 return GVA_StrongODR;
8834
David Majnemer27d69db2014-04-28 22:17:59 +00008835 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008836}
8837
Artem Belevichca2b9512016-05-02 20:30:03 +00008838static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8839 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008840 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8841 // dllexport/dllimport on inline functions.
8842 if (D->hasAttr<DLLImportAttr>()) {
8843 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8844 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008845 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008846 if (L == GVA_DiscardableODR)
8847 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008848 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8849 D->hasAttr<CUDAGlobalAttr>()) {
8850 // Device-side functions with __global__ attribute must always be
8851 // visible externally so they can be launched from host.
8852 if (L == GVA_DiscardableODR || L == GVA_Internal)
8853 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008854 }
8855 return L;
8856}
8857
8858GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008859 return adjustGVALinkageForAttributes(
8860 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008861}
8862
8863static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8864 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008865 if (!VD->isExternallyVisible())
8866 return GVA_Internal;
8867
David Majnemer27d69db2014-04-28 22:17:59 +00008868 if (VD->isStaticLocal()) {
8869 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8870 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8871 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8872 LexicalContext = LexicalContext->getLexicalParent();
8873
Richard Smith9e2341d2015-03-23 03:25:59 +00008874 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008875 // enclosing function.
8876 if (LexicalContext)
8877 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008878 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008879
8880 // GVA_StrongODR function linkage is stronger than what we need,
8881 // downgrade to GVA_DiscardableODR.
8882 // This allows us to discard the variable if we never end up needing it.
8883 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8884 : StaticLocalLinkage;
8885 }
8886
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008887 // MSVC treats in-class initialized static data members as definitions.
8888 // By giving them non-strong linkage, out-of-line definitions won't
8889 // cause link errors.
8890 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8891 return GVA_DiscardableODR;
8892
Richard Smithd9b90092016-07-02 01:32:16 +00008893 // Most non-template variables have strong linkage; inline variables are
8894 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8895 GVALinkage StrongLinkage;
8896 switch (Context.getInlineVariableDefinitionKind(VD)) {
8897 case ASTContext::InlineVariableDefinitionKind::None:
8898 StrongLinkage = GVA_StrongExternal;
8899 break;
8900 case ASTContext::InlineVariableDefinitionKind::Weak:
8901 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008902 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008903 break;
8904 case ASTContext::InlineVariableDefinitionKind::Strong:
8905 StrongLinkage = GVA_StrongODR;
8906 break;
8907 }
Richard Smith62f19e72016-06-25 00:15:56 +00008908
Richard Smith8809a0c2013-09-27 20:14:12 +00008909 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008910 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008911 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008912
David Majnemer6d1780c2015-07-17 23:36:49 +00008913 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008914 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8915 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008916 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008917 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008918
Rafael Espindola3ae00052013-05-13 00:12:11 +00008919 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008920 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008921
David Majnemer27d69db2014-04-28 22:17:59 +00008922 case TSK_ExplicitInstantiationDeclaration:
8923 return GVA_AvailableExternally;
8924
Rafael Espindola3ae00052013-05-13 00:12:11 +00008925 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008926 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008927 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008928
8929 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008930}
8931
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008932GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008933 return adjustGVALinkageForAttributes(
8934 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008935}
8936
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008937bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008938 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8939 if (!VD->isFileVarDecl())
8940 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008941 // Global named register variables (GNU extension) are never emitted.
8942 if (VD->getStorageClass() == SC_Register)
8943 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008944 if (VD->getDescribedVarTemplate() ||
8945 isa<VarTemplatePartialSpecializationDecl>(VD))
8946 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008947 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8948 // We never need to emit an uninstantiated function template.
8949 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8950 return false;
Nico Weber66220292016-03-02 17:28:48 +00008951 } else if (isa<PragmaCommentDecl>(D))
8952 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008953 else if (isa<OMPThreadPrivateDecl>(D) ||
8954 D->hasAttr<OMPDeclareTargetDeclAttr>())
8955 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008956 else if (isa<PragmaDetectMismatchDecl>(D))
8957 return true;
Nico Weber66220292016-03-02 17:28:48 +00008958 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008959 return !D->getDeclContext()->isDependentContext();
8960 else if (isa<OMPDeclareReductionDecl>(D))
8961 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00008962 else if (isa<ImportDecl>(D))
8963 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00008964 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008965 return false;
8966
8967 // If this is a member of a class template, we do not need to emit it.
8968 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008969 return false;
8970
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008971 // Weak references don't produce any output by themselves.
8972 if (D->hasAttr<WeakRefAttr>())
8973 return false;
8974
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008975 // Aliases and used decls are required.
8976 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8977 return true;
8978
8979 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8980 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008981 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008982 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008983
8984 // Constructors and destructors are required.
8985 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8986 return true;
8987
John McCall6bd2a892013-01-25 22:31:03 +00008988 // The key function for a class is required. This rule only comes
8989 // into play when inline functions can be key functions, though.
8990 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8991 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8992 const CXXRecordDecl *RD = MD->getParent();
8993 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8994 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8995 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8996 return true;
8997 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008998 }
8999 }
9000
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009001 // static, static inline, always_inline, and extern inline functions can
9002 // always be deferred. Normal inline functions can be deferred in C99/C++.
9003 // Implicit template instantiations can also be deferred in C++.
Justin Lebar606f01f2016-10-13 20:52:17 +00009004 return !isDiscardableGVALinkage(GetGVALinkageForFunction(FD));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009005 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009006
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009007 const VarDecl *VD = cast<VarDecl>(D);
9008 assert(VD->isFileVarDecl() && "Expected file scoped var");
9009
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009010 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9011 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009012 return false;
9013
Richard Smitha0e5e542012-11-12 21:38:00 +00009014 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00009015 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00009016 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009017
Richard Smitha0e5e542012-11-12 21:38:00 +00009018 // Variables that have destruction with side-effects are required.
9019 if (VD->getType().isDestructedType())
9020 return true;
9021
9022 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009023 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9024 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00009025 return true;
9026
Richard Smithda383632016-08-15 01:33:41 +00009027 // Likewise, variables with tuple-like bindings are required if their
9028 // bindings have side-effects.
9029 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9030 for (auto *BD : DD->bindings())
9031 if (auto *BindingVD = BD->getHoldingVar())
9032 if (DeclMustBeEmitted(BindingVD))
9033 return true;
9034
Richard Smitha0e5e542012-11-12 21:38:00 +00009035 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009036}
Charles Davis53c59df2010-08-16 03:33:14 +00009037
Reid Kleckner78af0702013-08-27 23:08:25 +00009038CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9039 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009040 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009041 if (IsCXXMethod)
9042 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009043
Alexey Bataeva7547182016-05-18 09:06:38 +00009044 switch (LangOpts.getDefaultCallingConv()) {
9045 case LangOptions::DCC_None:
9046 break;
9047 case LangOptions::DCC_CDecl:
9048 return CC_C;
9049 case LangOptions::DCC_FastCall:
9050 if (getTargetInfo().hasFeature("sse2"))
9051 return CC_X86FastCall;
9052 break;
9053 case LangOptions::DCC_StdCall:
9054 if (!IsVariadic)
9055 return CC_X86StdCall;
9056 break;
9057 case LangOptions::DCC_VectorCall:
9058 // __vectorcall cannot be applied to variadic functions.
9059 if (!IsVariadic)
9060 return CC_X86VectorCall;
9061 break;
9062 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009063 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009064}
9065
Jay Foad39c79802011-01-12 09:06:06 +00009066bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009067 // Pass through to the C++ ABI object
9068 return ABI->isNearlyEmpty(RD);
9069}
9070
Reid Kleckner96f8f932014-02-05 17:27:08 +00009071VTableContextBase *ASTContext::getVTableContext() {
9072 if (!VTContext.get()) {
9073 if (Target->getCXXABI().isMicrosoft())
9074 VTContext.reset(new MicrosoftVTableContext(*this));
9075 else
9076 VTContext.reset(new ItaniumVTableContext(*this));
9077 }
9078 return VTContext.get();
9079}
9080
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009081MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009082 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009083 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009084 case TargetCXXABI::GenericItanium:
9085 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009086 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009087 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009088 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009089 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009090 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009091 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009092 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009093 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009094 }
David Blaikie83d382b2011-09-23 05:06:16 +00009095 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009096}
9097
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009098CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009099
9100size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009101 return ASTRecordLayouts.getMemorySize() +
9102 llvm::capacity_in_bytes(ObjCLayouts) +
9103 llvm::capacity_in_bytes(KeyFunctions) +
9104 llvm::capacity_in_bytes(ObjCImpls) +
9105 llvm::capacity_in_bytes(BlockVarCopyInits) +
9106 llvm::capacity_in_bytes(DeclAttrs) +
9107 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9108 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9109 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9110 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9111 llvm::capacity_in_bytes(OverriddenMethods) +
9112 llvm::capacity_in_bytes(Types) +
9113 llvm::capacity_in_bytes(VariableArrayTypes) +
9114 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009115}
Ted Kremenek540017e2011-10-06 05:00:56 +00009116
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009117/// getIntTypeForBitwidth -
9118/// sets integer QualTy according to specified details:
9119/// bitwidth, signed/unsigned.
9120/// Returns empty type if there is no appropriate target types.
9121QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9122 unsigned Signed) const {
9123 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9124 CanQualType QualTy = getFromTargetType(Ty);
9125 if (!QualTy && DestWidth == 128)
9126 return Signed ? Int128Ty : UnsignedInt128Ty;
9127 return QualTy;
9128}
9129
9130/// getRealTypeForBitwidth -
9131/// sets floating point QualTy according to specified bitwidth.
9132/// Returns empty type if there is no appropriate target types.
9133QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9134 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9135 switch (Ty) {
9136 case TargetInfo::Float:
9137 return FloatTy;
9138 case TargetInfo::Double:
9139 return DoubleTy;
9140 case TargetInfo::LongDouble:
9141 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009142 case TargetInfo::Float128:
9143 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009144 case TargetInfo::NoFloat:
9145 return QualType();
9146 }
9147
9148 llvm_unreachable("Unhandled TargetInfo::RealType value");
9149}
9150
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009151void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9152 if (Number > 1)
9153 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009154}
9155
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009156unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009157 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009158 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009159}
9160
David Majnemer2206bf52014-03-05 08:57:59 +00009161void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9162 if (Number > 1)
9163 StaticLocalNumbers[VD] = Number;
9164}
9165
9166unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009167 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009168 return I != StaticLocalNumbers.end() ? I->second : 1;
9169}
9170
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009171MangleNumberingContext &
9172ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009173 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009174 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009175 if (!MCtx)
9176 MCtx = createMangleNumberingContext();
9177 return *MCtx;
9178}
9179
Justin Lebar20ebffc2016-10-10 16:26:19 +00009180std::unique_ptr<MangleNumberingContext>
9181ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009182 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009183}
9184
David Majnemere7a818f2015-03-06 18:53:55 +00009185const CXXConstructorDecl *
9186ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9187 return ABI->getCopyConstructorForExceptionObject(
9188 cast<CXXRecordDecl>(RD->getFirstDecl()));
9189}
9190
9191void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9192 CXXConstructorDecl *CD) {
9193 return ABI->addCopyConstructorForExceptionObject(
9194 cast<CXXRecordDecl>(RD->getFirstDecl()),
9195 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9196}
9197
David Majnemer00350522015-08-31 18:48:39 +00009198void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9199 TypedefNameDecl *DD) {
9200 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9201}
9202
9203TypedefNameDecl *
9204ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9205 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9206}
9207
9208void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9209 DeclaratorDecl *DD) {
9210 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9211}
9212
9213DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9214 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9215}
9216
Ted Kremenek540017e2011-10-06 05:00:56 +00009217void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9218 ParamIndices[D] = index;
9219}
9220
9221unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9222 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9223 assert(I != ParamIndices.end() &&
9224 "ParmIndices lacks entry set by ParmVarDecl");
9225 return I->second;
9226}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009227
Richard Smithe6c01442013-06-05 00:46:14 +00009228APValue *
9229ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9230 bool MayCreate) {
9231 assert(E && E->getStorageDuration() == SD_Static &&
9232 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009233 if (MayCreate) {
9234 APValue *&MTVI = MaterializedTemporaryValues[E];
9235 if (!MTVI)
9236 MTVI = new (*this) APValue;
9237 return MTVI;
9238 }
Richard Smithe6c01442013-06-05 00:46:14 +00009239
David Majnemer2dcef9e2015-08-13 23:50:15 +00009240 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009241}
9242
Fariborz Jahanian615de762013-05-28 17:37:39 +00009243bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9244 const llvm::Triple &T = getTargetInfo().getTriple();
9245 if (!T.isOSDarwin())
9246 return false;
9247
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009248 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9249 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9250 return false;
9251
Fariborz Jahanian615de762013-05-28 17:37:39 +00009252 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9253 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9254 uint64_t Size = sizeChars.getQuantity();
9255 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9256 unsigned Align = alignChars.getQuantity();
9257 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9258 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9259}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009260
9261namespace {
9262
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009263ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9264 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009265 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009266 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009267 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009268 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009269 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009270}
9271
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009272/// Template specializations to abstract away from pointers and TypeLocs.
9273/// @{
9274template <typename T>
9275ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9276 return ast_type_traits::DynTypedNode::create(*Node);
9277}
9278template <>
9279ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9280 return ast_type_traits::DynTypedNode::create(Node);
9281}
9282template <>
9283ast_type_traits::DynTypedNode
9284createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9285 return ast_type_traits::DynTypedNode::create(Node);
9286}
9287/// @}
9288
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009289 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9290 /// parents as defined by the \c RecursiveASTVisitor.
9291 ///
9292 /// Note that the relationship described here is purely in terms of AST
9293 /// traversal - there are other relationships (for example declaration context)
9294 /// in the AST that are better modeled by special matchers.
9295 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009296 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009297 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009298 public:
9299 /// \brief Builds and returns the translation unit's parent map.
9300 ///
9301 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009302 static std::pair<ASTContext::ParentMapPointers *,
9303 ASTContext::ParentMapOtherNodes *>
9304 buildMap(TranslationUnitDecl &TU) {
9305 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9306 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009307 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009308 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009309 }
9310
9311 private:
9312 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9313
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009314 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9315 ASTContext::ParentMapOtherNodes *OtherParents)
9316 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009317
9318 bool shouldVisitTemplateInstantiations() const {
9319 return true;
9320 }
9321 bool shouldVisitImplicitCode() const {
9322 return true;
9323 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009324
Richard Smith85838722015-11-24 03:09:01 +00009325 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9326 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009327 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009328 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009329 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009330 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009331 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009332 // FIXME: Currently we add the same parent multiple times, but only
9333 // when no memoization data is available for the type.
9334 // For example when we visit all subexpressions of template
9335 // instantiations; this is suboptimal, but benign: the only way to
9336 // visit those is with hasAncestor / hasParent, and those do not create
9337 // new matches.
9338 // The plan is to enable DynTypedNode to be storable in a map or hash
9339 // map. The main problem there is to implement hash functions /
9340 // comparison operators for all types that DynTypedNode supports that
9341 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009342 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009343 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009344 if (const auto *D = ParentStack.back().get<Decl>())
9345 NodeOrVector = D;
9346 else if (const auto *S = ParentStack.back().get<Stmt>())
9347 NodeOrVector = S;
9348 else
9349 NodeOrVector =
9350 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009351 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009352 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9353 auto *Vector = new ASTContext::ParentVector(
9354 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009355 if (auto *Node =
9356 NodeOrVector
9357 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9358 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009359 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009360 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009361
9362 auto *Vector =
9363 NodeOrVector.template get<ASTContext::ParentVector *>();
9364 // Skip duplicates for types that have memoization data.
9365 // We must check that the type has memoization data before calling
9366 // std::find() because DynTypedNode::operator== can't compare all
9367 // types.
9368 bool Found = ParentStack.back().getMemoizationData() &&
9369 std::find(Vector->begin(), Vector->end(),
9370 ParentStack.back()) != Vector->end();
9371 if (!Found)
9372 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009373 }
9374 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009375 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009376 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009377 ParentStack.pop_back();
9378 return Result;
9379 }
9380
9381 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009382 return TraverseNode(DeclNode, DeclNode,
9383 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009384 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009385 }
9386
9387 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009388 return TraverseNode(StmtNode, StmtNode,
9389 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009390 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009391 }
9392
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009393 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009394 return TraverseNode(
9395 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9396 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9397 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009398 }
9399
9400 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9401 return TraverseNode(
9402 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009403 [&] {
9404 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9405 },
9406 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009407 }
9408
9409 ASTContext::ParentMapPointers *Parents;
9410 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009411 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9412
9413 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9414 };
9415
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009416} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009417
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009418template <typename NodeTy, typename MapTy>
9419static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9420 const MapTy &Map) {
9421 auto I = Map.find(Node);
9422 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009423 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009424 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009425 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009426 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009427 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009428 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009429}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009430
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009431ASTContext::DynTypedNodeList
9432ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9433 if (!PointerParents) {
9434 // We always need to run over the whole translation unit, as
9435 // hasAncestor can escape any subtree.
9436 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9437 PointerParents.reset(Maps.first);
9438 OtherParents.reset(Maps.second);
9439 }
9440 if (Node.getNodeKind().hasPointerIdentity())
9441 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9442 return getDynNodeFromMap(Node, *OtherParents);
9443}
9444
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009445bool
9446ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9447 const ObjCMethodDecl *MethodImpl) {
9448 // No point trying to match an unavailable/deprecated mothod.
9449 if (MethodDecl->hasAttr<UnavailableAttr>()
9450 || MethodDecl->hasAttr<DeprecatedAttr>())
9451 return false;
9452 if (MethodDecl->getObjCDeclQualifier() !=
9453 MethodImpl->getObjCDeclQualifier())
9454 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009455 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009456 return false;
9457
9458 if (MethodDecl->param_size() != MethodImpl->param_size())
9459 return false;
9460
9461 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9462 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9463 EF = MethodDecl->param_end();
9464 IM != EM && IF != EF; ++IM, ++IF) {
9465 const ParmVarDecl *DeclVar = (*IF);
9466 const ParmVarDecl *ImplVar = (*IM);
9467 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9468 return false;
9469 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9470 return false;
9471 }
9472 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9473
9474}
Richard Smith053f6c62014-05-16 23:01:30 +00009475
Yaxun Liu402804b2016-12-15 08:09:08 +00009476uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9477 unsigned AS;
9478 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9479 AS = 0;
9480 else
9481 AS = QT->getPointeeType().getAddressSpace();
9482
9483 return getTargetInfo().getNullPointerValue(AS);
9484}
9485
Richard Smith053f6c62014-05-16 23:01:30 +00009486// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9487// doesn't include ASTContext.h
9488template
9489clang::LazyGenerationalUpdatePtr<
9490 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9491clang::LazyGenerationalUpdatePtr<
9492 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9493 const clang::ASTContext &Ctx, Decl *Value);