blob: ffa8cbbf6c5ebc46a3829131b9470e5905fab476 [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"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.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 {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
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}
330} // unnamed namespace
331
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) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000687 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000688 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000690 return CreateMicrosoftCXXABI(*this);
691 }
David Blaikie8a40f702012-01-17 06:56:22 +0000692 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000693}
694
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 const LangOptions &LOpts) {
697 if (LOpts.FakeAddressSpaceMap) {
698 // The fake address space map must have a distinct entry for each
699 // language-specific address space.
700 static const unsigned FakeAddrSpaceMap[] = {
701 1, // opencl_global
702 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000703 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000704 4, // opencl_generic
705 5, // cuda_device
706 6, // cuda_constant
707 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 }
713}
714
David Tweed31d09b02013-09-13 12:04:22 +0000715static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
716 const LangOptions &LangOpts) {
717 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000718 case LangOptions::ASMM_Target:
719 return TI.useAddressSpaceMapMangling();
720 case LangOptions::ASMM_On:
721 return true;
722 case LangOptions::ASMM_Off:
723 return false;
724 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000725 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000726}
727
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000728ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000729 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000730 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
732 DependentTemplateSpecializationTypes(this_()),
733 SubstTemplateTemplateParmPacks(this_()),
734 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
735 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000736 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
737 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
738 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000739 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
740 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
741 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
742 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000743 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
744 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000745 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000746 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
747 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
748 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
749 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000750 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751 TUDecl = TranslationUnitDecl::Create(*this);
752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000755 ReleaseParentMapEntries();
756
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000757 // Release the DenseMaps associated with DeclContext objects.
758 // FIXME: Is this the ideal solution?
759 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000760
Manuel Klimeka7328992013-06-03 13:51:33 +0000761 // Call all of the deallocation functions on all of their targets.
762 for (DeallocationMap::const_iterator I = Deallocations.begin(),
763 E = Deallocations.end(); I != E; ++I)
764 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
765 (I->first)((I->second)[J]);
766
Ted Kremenek076baeb2010-06-08 23:00:58 +0000767 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000768 // because they can contain DenseMaps.
769 for (llvm::DenseMap<const ObjCContainerDecl*,
770 const ASTRecordLayout*>::iterator
771 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
772 // Increment in loop to prevent using deallocated memory.
773 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
774 R->Destroy(*this);
775
Ted Kremenek076baeb2010-06-08 23:00:58 +0000776 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
777 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000782
783 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
784 AEnd = DeclAttrs.end();
785 A != AEnd; ++A)
786 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000787
David Majnemere694f3e2015-08-14 14:43:50 +0000788 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
789 MaterializedTemporaryValues)
790 MTVPair.second->~APValue();
791
Reid Kleckner588c9372014-02-19 23:44:52 +0000792 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000793}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000794
Manuel Klimek95403e62014-05-21 13:28:59 +0000795void ASTContext::ReleaseParentMapEntries() {
796 if (!AllParents) return;
797 for (const auto &Entry : *AllParents) {
798 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
799 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
800 } else {
801 assert(Entry.second.is<ParentVector *>());
802 delete Entry.second.get<ParentVector *>();
803 }
804 }
805}
806
Douglas Gregor1a809332010-05-23 18:26:36 +0000807void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000808 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000809}
810
Mike Stump11289f42009-09-09 15:08:12 +0000811void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000812ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
813 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000814}
815
Chris Lattner4eb445d2007-01-26 01:27:23 +0000816void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000817 llvm::errs() << "\n*** AST Context Stats:\n";
818 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000819
Douglas Gregora30d0462009-05-26 14:40:08 +0000820 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000821#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000822#define ABSTRACT_TYPE(Name, Parent)
823#include "clang/AST/TypeNodes.def"
824 0 // Extra
825 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000826
Chris Lattner4eb445d2007-01-26 01:27:23 +0000827 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
828 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000829 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000830 }
831
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 unsigned Idx = 0;
833 unsigned TotalBytes = 0;
834#define TYPE(Name, Parent) \
835 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << " " << counts[Idx] << " " << #Name \
837 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000838 TotalBytes += counts[Idx] * sizeof(Name##Type); \
839 ++Idx;
840#define ABSTRACT_TYPE(Name, Parent)
841#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chandler Carruth3c147a72011-07-04 05:32:14 +0000843 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
844
Douglas Gregor7454c562010-07-02 20:37:36 +0000845 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
847 << NumImplicitDefaultConstructors
848 << " implicit default constructors created\n";
849 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
850 << NumImplicitCopyConstructors
851 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
854 << NumImplicitMoveConstructors
855 << " implicit move constructors created\n";
856 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
857 << NumImplicitCopyAssignmentOperators
858 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
861 << NumImplicitMoveAssignmentOperators
862 << " implicit move assignment operators created\n";
863 llvm::errs() << NumImplicitDestructorsDeclared << "/"
864 << NumImplicitDestructors
865 << " implicit destructors created\n";
866
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000867 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000869 ExternalSource->PrintStats();
870 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000871
Douglas Gregor5b11d492010-07-25 17:53:33 +0000872 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000873}
874
Richard Smith42413142015-05-15 20:05:43 +0000875void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
876 bool NotifyListeners) {
877 if (NotifyListeners)
878 if (auto *Listener = getASTMutationListener())
879 Listener->RedefinedHiddenDefinition(ND, M);
880
881 if (getLangOpts().ModulesLocalVisibility)
882 MergedDefModules[ND].push_back(M);
883 else
884 ND->setHidden(false);
885}
886
887void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
888 auto It = MergedDefModules.find(ND);
889 if (It == MergedDefModules.end())
890 return;
891
892 auto &Merged = It->second;
893 llvm::DenseSet<Module*> Found;
894 for (Module *&M : Merged)
895 if (!Found.insert(M).second)
896 M = nullptr;
897 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
898}
899
Richard Smithf19e1272015-03-07 00:04:49 +0000900ExternCContextDecl *ASTContext::getExternCContextDecl() const {
901 if (!ExternCContext)
902 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
903
904 return ExternCContext;
905}
906
Alp Toker2dea15b2013-12-17 01:22:38 +0000907RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
908 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000909 SourceLocation Loc;
910 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000911 if (getLangOpts().CPlusPlus)
912 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
913 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000914 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000915 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
916 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000917 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000918 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
919 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000920 return NewDecl;
921}
922
923TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
924 StringRef Name) const {
925 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
926 TypedefDecl *NewDecl = TypedefDecl::Create(
927 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
928 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
929 NewDecl->setImplicit();
930 return NewDecl;
931}
932
Douglas Gregor801c99d2011-08-12 06:49:56 +0000933TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 if (!Int128Decl)
935 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000936 return Int128Decl;
937}
938
939TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000940 if (!UInt128Decl)
941 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000942 return UInt128Decl;
943}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000944
Nico Webere1687c52013-06-20 21:44:55 +0000945TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000946 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000947 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000948 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000949
Nico Webere1687c52013-06-20 21:44:55 +0000950 return Float128StubDecl;
951}
952
John McCall48f2d582009-10-23 23:03:21 +0000953void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000954 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000955 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000956 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000957}
958
Artem Belevichb5bc9232015-09-22 17:23:22 +0000959void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
960 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000961 assert((!this->Target || this->Target == &Target) &&
962 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000963 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregore8bbc122011-09-02 00:18:52 +0000965 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000966 this->AuxTarget = AuxTarget;
967
Douglas Gregore8bbc122011-09-02 00:18:52 +0000968 ABI.reset(createCXXABI(Target));
969 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000970 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000971
Chris Lattner970e54e2006-11-12 00:37:36 +0000972 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000973 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattner970e54e2006-11-12 00:37:36 +0000975 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000976 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000977 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000978 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000979 InitBuiltinType(CharTy, BuiltinType::Char_S);
980 else
981 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000982 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000983 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
984 InitBuiltinType(ShortTy, BuiltinType::Short);
985 InitBuiltinType(IntTy, BuiltinType::Int);
986 InitBuiltinType(LongTy, BuiltinType::Long);
987 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattner970e54e2006-11-12 00:37:36 +0000989 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000990 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
991 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
992 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
993 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
994 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000995
Chris Lattner970e54e2006-11-12 00:37:36 +0000996 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000997 InitBuiltinType(FloatTy, BuiltinType::Float);
998 InitBuiltinType(DoubleTy, BuiltinType::Double);
999 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001000
Chris Lattnerf122cef2009-04-30 02:43:43 +00001001 // GNU extension, 128-bit integers.
1002 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1003 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1004
Hans Wennborg0d81e012013-05-10 10:08:40 +00001005 // C++ 3.9.1p5
1006 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1007 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1008 else // -fshort-wchar makes wchar_t be unsigned.
1009 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1010 if (LangOpts.CPlusPlus && LangOpts.WChar)
1011 WideCharTy = WCharTy;
1012 else {
1013 // C99 (or C++ using -fno-wchar).
1014 WideCharTy = getFromTargetType(Target.getWCharType());
1015 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001016
James Molloy36365542012-05-04 10:55:22 +00001017 WIntTy = getFromTargetType(Target.getWIntType());
1018
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001019 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1020 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1021 else // C99
1022 Char16Ty = getFromTargetType(Target.getChar16Type());
1023
1024 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1025 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1026 else // C99
1027 Char32Ty = getFromTargetType(Target.getChar32Type());
1028
Douglas Gregor4619e432008-12-05 23:32:09 +00001029 // Placeholder type for type-dependent expressions whose type is
1030 // completely unknown. No code should ever check a type against
1031 // DependentTy and users should never see it; however, it is here to
1032 // help diagnose failures to properly check for type-dependent
1033 // expressions.
1034 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001035
John McCall36e7fe32010-10-12 00:20:44 +00001036 // Placeholder type for functions.
1037 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1038
John McCall0009fcc2011-04-26 20:42:42 +00001039 // Placeholder type for bound members.
1040 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1041
John McCall526ab472011-10-25 17:37:35 +00001042 // Placeholder type for pseudo-objects.
1043 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1044
John McCall31996342011-04-07 08:22:57 +00001045 // "any" type; useful for debugger-like clients.
1046 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1047
John McCall8a6b59a2011-10-17 18:09:15 +00001048 // Placeholder type for unbridged ARC casts.
1049 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1050
Eli Friedman34866c72012-08-31 00:14:07 +00001051 // Placeholder type for builtin functions.
1052 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1053
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001054 // Placeholder type for OMP array sections.
1055 if (LangOpts.OpenMP)
1056 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1057
Chris Lattner970e54e2006-11-12 00:37:36 +00001058 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001059 FloatComplexTy = getComplexType(FloatTy);
1060 DoubleComplexTy = getComplexType(DoubleTy);
1061 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001063 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001064 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1065 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001066 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001067
1068 if (LangOpts.OpenCL) {
1069 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1070 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1071 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1072 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1073 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001074 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1075 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1076 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1077 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1078 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1079 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1080 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001081 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001082
Guy Benyei61054192013-02-07 10:55:47 +00001083 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001084 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001085 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1086 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1087 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1088 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001089 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001090
1091 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001092 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1093 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001094
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001095 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001096
1097 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001098
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001099 // void * type
1100 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001101
1102 // nullptr type (C++0x 2.14.7)
1103 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001104
1105 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1106 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001107
1108 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001109 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001110}
1111
David Blaikie9c902b52011-09-25 23:23:43 +00001112DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001113 return SourceMgr.getDiagnostics();
1114}
1115
Douglas Gregor561eceb2010-08-30 16:49:28 +00001116AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1117 AttrVec *&Result = DeclAttrs[D];
1118 if (!Result) {
1119 void *Mem = Allocate(sizeof(AttrVec));
1120 Result = new (Mem) AttrVec;
1121 }
1122
1123 return *Result;
1124}
1125
1126/// \brief Erase the attributes corresponding to the given declaration.
1127void ASTContext::eraseDeclAttrs(const Decl *D) {
1128 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1129 if (Pos != DeclAttrs.end()) {
1130 Pos->second->~AttrVec();
1131 DeclAttrs.erase(Pos);
1132 }
1133}
1134
Larisse Voufo39a1e502013-08-06 01:03:05 +00001135// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001136MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001137ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001138 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001139 return getTemplateOrSpecializationInfo(Var)
1140 .dyn_cast<MemberSpecializationInfo *>();
1141}
1142
1143ASTContext::TemplateOrSpecializationInfo
1144ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1145 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1146 TemplateOrInstantiation.find(Var);
1147 if (Pos == TemplateOrInstantiation.end())
1148 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001150 return Pos->second;
1151}
1152
Mike Stump11289f42009-09-09 15:08:12 +00001153void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001154ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001155 TemplateSpecializationKind TSK,
1156 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001157 assert(Inst->isStaticDataMember() && "Not a static data member");
1158 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001159 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1160 Tmpl, TSK, PointOfInstantiation));
1161}
1162
1163void
1164ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1165 TemplateOrSpecializationInfo TSI) {
1166 assert(!TemplateOrInstantiation[Inst] &&
1167 "Already noted what the variable was instantiated from");
1168 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001169}
1170
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001171FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1172 const FunctionDecl *FD){
1173 assert(FD && "Specialization is 0");
1174 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001175 = ClassScopeSpecializationPattern.find(FD);
1176 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001177 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001178
1179 return Pos->second;
1180}
1181
1182void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1183 FunctionDecl *Pattern) {
1184 assert(FD && "Specialization is 0");
1185 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001186 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001187}
1188
John McCalle61f2ba2009-11-18 02:36:19 +00001189NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001190ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001191 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001192 = InstantiatedFromUsingDecl.find(UUD);
1193 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001194 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001195
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001196 return Pos->second;
1197}
1198
1199void
John McCallb96ec562009-12-04 22:46:56 +00001200ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1201 assert((isa<UsingDecl>(Pattern) ||
1202 isa<UnresolvedUsingValueDecl>(Pattern) ||
1203 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1204 "pattern decl is not a using decl");
1205 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1206 InstantiatedFromUsingDecl[Inst] = Pattern;
1207}
1208
1209UsingShadowDecl *
1210ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1211 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1212 = InstantiatedFromUsingShadowDecl.find(Inst);
1213 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001214 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001215
1216 return Pos->second;
1217}
1218
1219void
1220ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1221 UsingShadowDecl *Pattern) {
1222 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1223 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001224}
1225
Anders Carlsson5da84842009-09-01 04:26:58 +00001226FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1227 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1228 = InstantiatedFromUnnamedFieldDecl.find(Field);
1229 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001230 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001231
Anders Carlsson5da84842009-09-01 04:26:58 +00001232 return Pos->second;
1233}
1234
1235void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1236 FieldDecl *Tmpl) {
1237 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1238 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1239 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1240 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001241
Anders Carlsson5da84842009-09-01 04:26:58 +00001242 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1243}
1244
Douglas Gregor832940b2010-03-02 23:58:15 +00001245ASTContext::overridden_cxx_method_iterator
1246ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1247 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001248 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001249 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001250 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001251
1252 return Pos->second.begin();
1253}
1254
1255ASTContext::overridden_cxx_method_iterator
1256ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1257 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001258 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001259 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001260 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001261
1262 return Pos->second.end();
1263}
1264
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001265unsigned
1266ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1267 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001268 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001269 if (Pos == OverriddenMethods.end())
1270 return 0;
1271
1272 return Pos->second.size();
1273}
1274
Douglas Gregor832940b2010-03-02 23:58:15 +00001275void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1276 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001277 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001278 OverriddenMethods[Method].push_back(Overridden);
1279}
1280
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001281void ASTContext::getOverriddenMethods(
1282 const NamedDecl *D,
1283 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001284 assert(D);
1285
1286 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001287 Overridden.append(overridden_methods_begin(CXXMethod),
1288 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001289 return;
1290 }
1291
1292 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1293 if (!Method)
1294 return;
1295
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001296 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1297 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001298 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001299}
1300
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001301void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1302 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1303 assert(!Import->isFromASTFile() && "Non-local import declaration");
1304 if (!FirstLocalImport) {
1305 FirstLocalImport = Import;
1306 LastLocalImport = Import;
1307 return;
1308 }
1309
1310 LastLocalImport->NextLocalImport = Import;
1311 LastLocalImport = Import;
1312}
1313
Chris Lattner53cfe802007-07-18 17:52:12 +00001314//===----------------------------------------------------------------------===//
1315// Type Sizing and Analysis
1316//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001317
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001318/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1319/// scalar floating point type.
1320const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001321 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001322 assert(BT && "Not a floating point type!");
1323 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001324 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001325 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001326 case BuiltinType::Float: return Target->getFloatFormat();
1327 case BuiltinType::Double: return Target->getDoubleFormat();
1328 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001329 }
1330}
1331
Rafael Espindola71eccb32013-08-08 19:53:46 +00001332CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001333 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001334
John McCall94268702010-10-08 18:24:19 +00001335 bool UseAlignAttrOnly = false;
1336 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1337 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001338
John McCall94268702010-10-08 18:24:19 +00001339 // __attribute__((aligned)) can increase or decrease alignment
1340 // *except* on a struct or struct member, where it only increases
1341 // alignment unless 'packed' is also specified.
1342 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001343 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001344 // ignore that possibility; Sema should diagnose it.
1345 if (isa<FieldDecl>(D)) {
1346 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1347 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1348 } else {
1349 UseAlignAttrOnly = true;
1350 }
1351 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001352 else if (isa<FieldDecl>(D))
1353 UseAlignAttrOnly =
1354 D->hasAttr<PackedAttr>() ||
1355 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001356
John McCall4e819612011-01-20 07:57:12 +00001357 // If we're using the align attribute only, just ignore everything
1358 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001359 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001360 // do nothing
1361
John McCall94268702010-10-08 18:24:19 +00001362 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001363 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001364 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001365 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001366 T = RT->getPointeeType();
1367 else
1368 T = getPointerType(RT->getPointeeType());
1369 }
Richard Smithf6d70302014-06-10 23:34:28 +00001370 QualType BaseT = getBaseElementType(T);
1371 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001372 // Adjust alignments of declarations with array type by the
1373 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001374 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001375 unsigned MinWidth = Target->getLargeArrayMinWidth();
1376 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001377 if (isa<VariableArrayType>(arrayType))
1378 Align = std::max(Align, Target->getLargeArrayAlign());
1379 else if (isa<ConstantArrayType>(arrayType) &&
1380 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1381 Align = std::max(Align, Target->getLargeArrayAlign());
1382 }
John McCall33ddac02011-01-19 10:06:00 +00001383 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001384 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001385 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001386 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001387 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1388 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001389 }
John McCall4e819612011-01-20 07:57:12 +00001390
1391 // Fields can be subject to extra alignment constraints, like if
1392 // the field is packed, the struct is packed, or the struct has a
1393 // a max-field-alignment constraint (#pragma pack). So calculate
1394 // the actual alignment of the field within the struct, and then
1395 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001396 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1397 const RecordDecl *Parent = Field->getParent();
1398 // We can only produce a sensible answer if the record is valid.
1399 if (!Parent->isInvalidDecl()) {
1400 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001401
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001402 // Start with the record's overall alignment.
1403 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001404
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001405 // Use the GCD of that and the offset within the record.
1406 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1407 if (Offset > 0) {
1408 // Alignment is always a power of 2, so the GCD will be a power of 2,
1409 // which means we get to do this crazy thing instead of Euclid's.
1410 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1411 if (LowBitOfOffset < FieldAlign)
1412 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1413 }
1414
1415 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001416 }
Charles Davis3fc51072010-02-23 04:52:00 +00001417 }
Chris Lattner68061312009-01-24 21:53:27 +00001418 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001419
Ken Dyckcc56c542011-01-15 18:38:59 +00001420 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001421}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001422
John McCallf1249922012-08-21 04:10:00 +00001423// getTypeInfoDataSizeInChars - Return the size of a type, in
1424// chars. If the type is a record, its data size is returned. This is
1425// the size of the memcpy that's performed when assigning this type
1426// using a trivial copy/move assignment operator.
1427std::pair<CharUnits, CharUnits>
1428ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1429 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1430
1431 // In C++, objects can sometimes be allocated into the tail padding
1432 // of a base-class subobject. We decide whether that's possible
1433 // during class layout, so here we can just trust the layout results.
1434 if (getLangOpts().CPlusPlus) {
1435 if (const RecordType *RT = T->getAs<RecordType>()) {
1436 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1437 sizeAndAlign.first = layout.getDataSize();
1438 }
1439 }
1440
1441 return sizeAndAlign;
1442}
1443
Richard Trieu04d2d942013-05-14 21:59:17 +00001444/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1445/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1446std::pair<CharUnits, CharUnits>
1447static getConstantArrayInfoInChars(const ASTContext &Context,
1448 const ConstantArrayType *CAT) {
1449 std::pair<CharUnits, CharUnits> EltInfo =
1450 Context.getTypeInfoInChars(CAT->getElementType());
1451 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001452 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1453 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001454 "Overflow in array type char size evaluation");
1455 uint64_t Width = EltInfo.first.getQuantity() * Size;
1456 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001457 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1458 Context.getTargetInfo().getPointerWidth(0) == 64)
1459 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001460 return std::make_pair(CharUnits::fromQuantity(Width),
1461 CharUnits::fromQuantity(Align));
1462}
1463
John McCall87fe5d52010-05-20 01:18:31 +00001464std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001465ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001466 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1467 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001468 TypeInfo Info = getTypeInfo(T);
1469 return std::make_pair(toCharUnitsFromBits(Info.Width),
1470 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001471}
1472
1473std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001474ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001475 return getTypeInfoInChars(T.getTypePtr());
1476}
1477
David Majnemer34b57492014-07-30 01:30:47 +00001478bool ASTContext::isAlignmentRequired(const Type *T) const {
1479 return getTypeInfo(T).AlignIsRequired;
1480}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001481
David Majnemer34b57492014-07-30 01:30:47 +00001482bool ASTContext::isAlignmentRequired(QualType T) const {
1483 return isAlignmentRequired(T.getTypePtr());
1484}
1485
1486TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001487 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1488 if (I != MemoizedTypeInfo.end())
1489 return I->second;
1490
1491 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1492 TypeInfo TI = getTypeInfoImpl(T);
1493 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001494 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001495}
1496
1497/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1498/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001499///
1500/// FIXME: Pointers into different addr spaces could have different sizes and
1501/// alignment requirements: getPointerInfo should take an AddrSpace, this
1502/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001503TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1504 uint64_t Width = 0;
1505 unsigned Align = 8;
1506 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001507 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001508#define TYPE(Class, Base)
1509#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001510#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001511#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001512#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1513 case Type::Class: \
1514 assert(!T->isDependentType() && "should not see dependent types here"); \
1515 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001516#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001517 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001518
Chris Lattner355332d2007-07-13 22:27:08 +00001519 case Type::FunctionNoProto:
1520 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001521 // GCC extension: alignof(function) = 32 bits
1522 Width = 0;
1523 Align = 32;
1524 break;
1525
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001526 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001527 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001528 Width = 0;
1529 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1530 break;
1531
Steve Naroff5c131802007-08-30 01:06:46 +00001532 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001533 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001534
David Majnemer34b57492014-07-30 01:30:47 +00001535 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001536 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001537 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001538 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001539 Width = EltInfo.Width * Size;
1540 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001541 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1542 getTargetInfo().getPointerWidth(0) == 64)
1543 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001544 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001545 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001546 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001547 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001548 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001549 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1550 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001551 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001552 // If the alignment is not a power of 2, round up to the next power of 2.
1553 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001554 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001555 Align = llvm::NextPowerOf2(Align);
1556 Width = llvm::RoundUpToAlignment(Width, Align);
1557 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001558 // Adjust the alignment based on the target max.
1559 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1560 if (TargetVectorAlign && TargetVectorAlign < Align)
1561 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001562 break;
1563 }
Chris Lattner647fb222007-07-18 18:26:58 +00001564
Chris Lattner7570e9c2008-03-08 08:52:55 +00001565 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001566 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001567 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001568 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001569 // GCC extension: alignof(void) = 8 bits.
1570 Width = 0;
1571 Align = 8;
1572 break;
1573
Chris Lattner6a4f7452007-12-19 19:23:28 +00001574 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001575 Width = Target->getBoolWidth();
1576 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001577 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001578 case BuiltinType::Char_S:
1579 case BuiltinType::Char_U:
1580 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001581 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001582 Width = Target->getCharWidth();
1583 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001584 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001585 case BuiltinType::WChar_S:
1586 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001587 Width = Target->getWCharWidth();
1588 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001589 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001590 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001591 Width = Target->getChar16Width();
1592 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001593 break;
1594 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001595 Width = Target->getChar32Width();
1596 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001597 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001598 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001599 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001600 Width = Target->getShortWidth();
1601 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001602 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001603 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001604 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getIntWidth();
1606 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001608 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001609 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getLongWidth();
1611 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001612 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001613 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001614 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getLongLongWidth();
1616 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001617 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001618 case BuiltinType::Int128:
1619 case BuiltinType::UInt128:
1620 Width = 128;
1621 Align = 128; // int128_t is 128-bit aligned on all targets.
1622 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001623 case BuiltinType::Half:
1624 Width = Target->getHalfWidth();
1625 Align = Target->getHalfAlign();
1626 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001627 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001628 Width = Target->getFloatWidth();
1629 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001630 break;
1631 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001632 Width = Target->getDoubleWidth();
1633 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001634 break;
1635 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001636 Width = Target->getLongDoubleWidth();
1637 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001638 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001639 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001640 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1641 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001642 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001643 case BuiltinType::ObjCId:
1644 case BuiltinType::ObjCClass:
1645 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001646 Width = Target->getPointerWidth(0);
1647 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001648 break;
Guy Benyei61054192013-02-07 10:55:47 +00001649 case BuiltinType::OCLSampler:
1650 // Samplers are modeled as integers.
1651 Width = Target->getIntWidth();
1652 Align = Target->getIntAlign();
1653 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001654 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001655 case BuiltinType::OCLClkEvent:
1656 case BuiltinType::OCLQueue:
1657 case BuiltinType::OCLNDRange:
1658 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001659 case BuiltinType::OCLImage1d:
1660 case BuiltinType::OCLImage1dArray:
1661 case BuiltinType::OCLImage1dBuffer:
1662 case BuiltinType::OCLImage2d:
1663 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001664 case BuiltinType::OCLImage2dDepth:
1665 case BuiltinType::OCLImage2dArrayDepth:
1666 case BuiltinType::OCLImage2dMSAA:
1667 case BuiltinType::OCLImage2dArrayMSAA:
1668 case BuiltinType::OCLImage2dMSAADepth:
1669 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001670 case BuiltinType::OCLImage3d:
1671 // Currently these types are pointers to opaque types.
1672 Width = Target->getPointerWidth(0);
1673 Align = Target->getPointerAlign(0);
1674 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001675 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001676 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001677 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001678 Width = Target->getPointerWidth(0);
1679 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001680 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001681 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001682 unsigned AS = getTargetAddressSpace(
1683 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001684 Width = Target->getPointerWidth(AS);
1685 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001686 break;
1687 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001688 case Type::LValueReference:
1689 case Type::RValueReference: {
1690 // alignof and sizeof should never enter this code path here, so we go
1691 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001692 unsigned AS = getTargetAddressSpace(
1693 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001694 Width = Target->getPointerWidth(AS);
1695 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001696 break;
1697 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001698 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001699 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001700 Width = Target->getPointerWidth(AS);
1701 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001702 break;
1703 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001704 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001705 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001706 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001707 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001708 }
Chris Lattner647fb222007-07-18 18:26:58 +00001709 case Type::Complex: {
1710 // Complex types have the same alignment as their elements, but twice the
1711 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001712 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1713 Width = EltInfo.Width * 2;
1714 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001715 break;
1716 }
John McCall8b07ec22010-05-15 11:32:37 +00001717 case Type::ObjCObject:
1718 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001719 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001720 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001721 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001722 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001723 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001724 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001725 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001726 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001727 break;
1728 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001729 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001730 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001731 const TagType *TT = cast<TagType>(T);
1732
1733 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001734 Width = 8;
1735 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001736 break;
1737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
David Majnemer475b25e2015-01-21 10:54:38 +00001739 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1740 const EnumDecl *ED = ET->getDecl();
1741 TypeInfo Info =
1742 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1743 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1744 Info.Align = AttrAlign;
1745 Info.AlignIsRequired = true;
1746 }
1747 return Info;
1748 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001749
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001750 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001751 const RecordDecl *RD = RT->getDecl();
1752 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001753 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001754 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001755 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001756 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001757 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001758
Chris Lattner63d2b362009-10-22 05:17:15 +00001759 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001760 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1761 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001762
Richard Smith30482bc2011-02-20 03:19:35 +00001763 case Type::Auto: {
1764 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001765 assert(!A->getDeducedType().isNull() &&
1766 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001767 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001768 }
1769
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001770 case Type::Paren:
1771 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1772
Douglas Gregoref462e62009-04-30 17:32:17 +00001773 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001774 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001775 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001776 // If the typedef has an aligned attribute on it, it overrides any computed
1777 // alignment we have. This violates the GCC documentation (which says that
1778 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001779 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001780 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001781 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001782 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001783 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001784 AlignIsRequired = Info.AlignIsRequired;
1785 }
David Majnemer34b57492014-07-30 01:30:47 +00001786 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001787 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001788 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001789
Abramo Bagnara6150c882010-05-11 21:36:43 +00001790 case Type::Elaborated:
1791 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001792
John McCall81904512011-01-06 01:58:22 +00001793 case Type::Attributed:
1794 return getTypeInfo(
1795 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1796
Eli Friedman0dfb8892011-10-06 23:00:33 +00001797 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001798 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001799 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1800 Width = Info.Width;
1801 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001802
1803 // If the size of the type doesn't exceed the platform's max
1804 // atomic promotion width, make the size and alignment more
1805 // favorable to atomic operations:
1806 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1807 // Round the size up to a power of 2.
1808 if (!llvm::isPowerOf2_64(Width))
1809 Width = llvm::NextPowerOf2(Width);
1810
1811 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001812 Align = static_cast<unsigned>(Width);
1813 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001814 }
1815
Douglas Gregoref462e62009-04-30 17:32:17 +00001816 }
Mike Stump11289f42009-09-09 15:08:12 +00001817
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001818 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001819 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001820}
1821
Alexey Bataev00396512015-07-02 03:40:19 +00001822unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1823 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1824 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1825 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1826 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1827 getTargetInfo().getABI() == "elfv1-qpx" &&
1828 T->isSpecificBuiltinType(BuiltinType::Double))
1829 SimdAlign = 256;
1830 return SimdAlign;
1831}
1832
Ken Dyckcc56c542011-01-15 18:38:59 +00001833/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1834CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1835 return CharUnits::fromQuantity(BitSize / getCharWidth());
1836}
1837
Ken Dyckb0fcc592011-02-11 01:54:29 +00001838/// toBits - Convert a size in characters to a size in characters.
1839int64_t ASTContext::toBits(CharUnits CharSize) const {
1840 return CharSize.getQuantity() * getCharWidth();
1841}
1842
Ken Dyck8c89d592009-12-22 14:23:30 +00001843/// getTypeSizeInChars - Return the size of the specified type, in characters.
1844/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001845CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001846 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001847}
Jay Foad39c79802011-01-12 09:06:06 +00001848CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001849 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001850}
1851
Ken Dycka6046ab2010-01-26 17:25:18 +00001852/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001853/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001854CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001855 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001856}
Jay Foad39c79802011-01-12 09:06:06 +00001857CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001858 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001859}
1860
Chris Lattnera3402cd2009-01-27 18:08:34 +00001861/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1862/// type for the current target in bits. This can be different than the ABI
1863/// alignment in cases where it is beneficial for performance to overalign
1864/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001865unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001866 TypeInfo TI = getTypeInfo(T);
1867 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001868
David Majnemere1544562015-04-24 01:25:05 +00001869 T = T->getBaseElementTypeUnsafe();
1870
1871 // The preferred alignment of member pointers is that of a pointer.
1872 if (T->isMemberPointerType())
1873 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1874
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001875 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1876 return ABIAlign; // Never overalign on XCore.
1877
Eli Friedman7ab09572009-05-25 21:27:19 +00001878 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001879 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001880 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001881 if (const EnumType *ET = T->getAs<EnumType>())
1882 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001883 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001884 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1885 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001886 // Don't increase the alignment if an alignment attribute was specified on a
1887 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001888 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001889 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001890
Chris Lattnera3402cd2009-01-27 18:08:34 +00001891 return ABIAlign;
1892}
1893
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001894/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1895/// for __attribute__((aligned)) on this target, to be used if no alignment
1896/// value is specified.
1897unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1898 return getTargetInfo().getDefaultAlignForAttributeAligned();
1899}
1900
Ulrich Weigandfa806422013-05-06 16:23:57 +00001901/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1902/// to a global variable of the specified type.
1903unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1904 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1905}
1906
1907/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1908/// should be given to a global variable of the specified type.
1909CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1910 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1911}
1912
David Majnemer08ef2ba2015-06-23 20:34:18 +00001913CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1914 CharUnits Offset = CharUnits::Zero();
1915 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1916 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1917 Offset += Layout->getBaseClassOffset(Base);
1918 Layout = &getASTRecordLayout(Base);
1919 }
1920 return Offset;
1921}
1922
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001923/// DeepCollectObjCIvars -
1924/// This routine first collects all declared, but not synthesized, ivars in
1925/// super class and then collects all ivars, including those synthesized for
1926/// current class. This routine is used for implementation of current class
1927/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001928///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001929void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1930 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001931 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001932 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1933 DeepCollectObjCIvars(SuperClass, false, Ivars);
1934 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001935 for (const auto *I : OI->ivars())
1936 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001937 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001938 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001939 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001940 Iv= Iv->getNextIvar())
1941 Ivars.push_back(Iv);
1942 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001943}
1944
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001945/// CollectInheritedProtocols - Collect all protocols in current class and
1946/// those inherited by it.
1947void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001948 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001949 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001950 // We can use protocol_iterator here instead of
1951 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001952 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001953 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001954 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001955
1956 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001957 for (const auto *Cat : OI->visible_categories())
1958 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001959
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001960 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1961 while (SD) {
1962 CollectInheritedProtocols(SD, Protocols);
1963 SD = SD->getSuperClass();
1964 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001965 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001966 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001967 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001968 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001969 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001970 // Insert the protocol.
1971 if (!Protocols.insert(
1972 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1973 return;
1974
1975 for (auto *Proto : OP->protocols())
1976 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001977 }
1978}
1979
Jay Foad39c79802011-01-12 09:06:06 +00001980unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001981 unsigned count = 0;
1982 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001983 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001984 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001985
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001986 // Count ivar defined in this class's implementation. This
1987 // includes synthesized ivars.
1988 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001989 count += ImplDecl->ivar_size();
1990
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001991 return count;
1992}
1993
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001994bool ASTContext::isSentinelNullExpr(const Expr *E) {
1995 if (!E)
1996 return false;
1997
1998 // nullptr_t is always treated as null.
1999 if (E->getType()->isNullPtrType()) return true;
2000
2001 if (E->getType()->isAnyPointerType() &&
2002 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2003 Expr::NPC_ValueDependentIsNull))
2004 return true;
2005
2006 // Unfortunately, __null has type 'int'.
2007 if (isa<GNUNullExpr>(E)) return true;
2008
2009 return false;
2010}
2011
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002012/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2013ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2014 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2015 I = ObjCImpls.find(D);
2016 if (I != ObjCImpls.end())
2017 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002018 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002019}
2020/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2021ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2022 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2023 I = ObjCImpls.find(D);
2024 if (I != ObjCImpls.end())
2025 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002026 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002027}
2028
2029/// \brief Set the implementation of ObjCInterfaceDecl.
2030void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2031 ObjCImplementationDecl *ImplD) {
2032 assert(IFaceD && ImplD && "Passed null params");
2033 ObjCImpls[IFaceD] = ImplD;
2034}
2035/// \brief Set the implementation of ObjCCategoryDecl.
2036void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2037 ObjCCategoryImplDecl *ImplD) {
2038 assert(CatD && ImplD && "Passed null params");
2039 ObjCImpls[CatD] = ImplD;
2040}
2041
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002042const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2043 const NamedDecl *ND) const {
2044 if (const ObjCInterfaceDecl *ID =
2045 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002046 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002047 if (const ObjCCategoryDecl *CD =
2048 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002049 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002050 if (const ObjCImplDecl *IMD =
2051 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002052 return IMD->getClassInterface();
2053
Craig Topper36250ad2014-05-12 05:36:57 +00002054 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002055}
2056
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002057/// \brief Get the copy initialization expression of VarDecl,or NULL if
2058/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002059Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002060 assert(VD && "Passed null params");
2061 assert(VD->hasAttr<BlocksAttr>() &&
2062 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002063 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002064 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002065 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002066}
2067
2068/// \brief Set the copy inialization expression of a block var decl.
2069void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2070 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002071 assert(VD->hasAttr<BlocksAttr>() &&
2072 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002073 BlockVarCopyInits[VD] = Init;
2074}
2075
John McCallbcd03502009-12-07 02:54:59 +00002076TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002077 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002078 if (!DataSize)
2079 DataSize = TypeLoc::getFullDataSizeForType(T);
2080 else
2081 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002082 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002083
John McCallbcd03502009-12-07 02:54:59 +00002084 TypeSourceInfo *TInfo =
2085 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2086 new (TInfo) TypeSourceInfo(T);
2087 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002088}
2089
John McCallbcd03502009-12-07 02:54:59 +00002090TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002091 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002092 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002093 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002094 return DI;
2095}
2096
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002097const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002098ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002099 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002100}
2101
2102const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002103ASTContext::getASTObjCImplementationLayout(
2104 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002105 return getObjCLayout(D->getClassInterface(), D);
2106}
2107
Chris Lattner983a8bb2007-07-13 22:13:22 +00002108//===----------------------------------------------------------------------===//
2109// Type creation/memoization methods
2110//===----------------------------------------------------------------------===//
2111
Jay Foad39c79802011-01-12 09:06:06 +00002112QualType
John McCall33ddac02011-01-19 10:06:00 +00002113ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2114 unsigned fastQuals = quals.getFastQualifiers();
2115 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002116
2117 // Check if we've already instantiated this type.
2118 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002119 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002120 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002121 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2122 assert(eq->getQualifiers() == quals);
2123 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002124 }
2125
John McCall33ddac02011-01-19 10:06:00 +00002126 // If the base type is not canonical, make the appropriate canonical type.
2127 QualType canon;
2128 if (!baseType->isCanonicalUnqualified()) {
2129 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002130 canonSplit.Quals.addConsistentQualifiers(quals);
2131 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002132
2133 // Re-find the insert position.
2134 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2135 }
2136
2137 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2138 ExtQualNodes.InsertNode(eq, insertPos);
2139 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002140}
2141
Jay Foad39c79802011-01-12 09:06:06 +00002142QualType
2143ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002144 QualType CanT = getCanonicalType(T);
2145 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002146 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002147
John McCall8ccfcb52009-09-24 19:53:00 +00002148 // If we are composing extended qualifiers together, merge together
2149 // into one ExtQuals node.
2150 QualifierCollector Quals;
2151 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002152
John McCall8ccfcb52009-09-24 19:53:00 +00002153 // If this type already has an address space specified, it cannot get
2154 // another one.
2155 assert(!Quals.hasAddressSpace() &&
2156 "Type cannot be in multiple addr spaces!");
2157 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002158
John McCall8ccfcb52009-09-24 19:53:00 +00002159 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002160}
2161
Chris Lattnerd60183d2009-02-18 22:53:11 +00002162QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002163 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002164 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002165 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002166 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002167
John McCall53fa7142010-12-24 02:08:15 +00002168 if (const PointerType *ptr = T->getAs<PointerType>()) {
2169 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002170 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002171 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2172 return getPointerType(ResultType);
2173 }
2174 }
Mike Stump11289f42009-09-09 15:08:12 +00002175
John McCall8ccfcb52009-09-24 19:53:00 +00002176 // If we are composing extended qualifiers together, merge together
2177 // into one ExtQuals node.
2178 QualifierCollector Quals;
2179 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCall8ccfcb52009-09-24 19:53:00 +00002181 // If this type already has an ObjCGC specified, it cannot get
2182 // another one.
2183 assert(!Quals.hasObjCGCAttr() &&
2184 "Type cannot have multiple ObjCGCs!");
2185 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCall8ccfcb52009-09-24 19:53:00 +00002187 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002188}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002189
John McCall4f5019e2010-12-19 02:44:49 +00002190const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2191 FunctionType::ExtInfo Info) {
2192 if (T->getExtInfo() == Info)
2193 return T;
2194
2195 QualType Result;
2196 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002197 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002198 } else {
2199 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2200 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2201 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002202 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002203 }
2204
2205 return cast<FunctionType>(Result.getTypePtr());
2206}
2207
Richard Smith2a7d4812013-05-04 07:00:32 +00002208void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2209 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002210 FD = FD->getMostRecentDecl();
2211 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002212 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2213 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002214 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002215 if (FunctionDecl *Next = FD->getPreviousDecl())
2216 FD = Next;
2217 else
2218 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002219 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002220 if (ASTMutationListener *L = getASTMutationListener())
2221 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002222}
2223
Richard Smith0b3a4622014-11-13 20:01:57 +00002224/// Get a function type and produce the equivalent function type with the
2225/// specified exception specification. Type sugar that can be present on a
2226/// declaration of a function with an exception specification is permitted
2227/// and preserved. Other type sugar (for instance, typedefs) is not.
2228static QualType getFunctionTypeWithExceptionSpec(
2229 ASTContext &Context, QualType Orig,
2230 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2231 // Might have some parens.
2232 if (auto *PT = dyn_cast<ParenType>(Orig))
2233 return Context.getParenType(
2234 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2235
2236 // Might have a calling-convention attribute.
2237 if (auto *AT = dyn_cast<AttributedType>(Orig))
2238 return Context.getAttributedType(
2239 AT->getAttrKind(),
2240 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2241 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2242 ESI));
2243
2244 // Anything else must be a function type. Rebuild it with the new exception
2245 // specification.
2246 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2247 return Context.getFunctionType(
2248 Proto->getReturnType(), Proto->getParamTypes(),
2249 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2250}
2251
2252void ASTContext::adjustExceptionSpec(
2253 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2254 bool AsWritten) {
2255 // Update the type.
2256 QualType Updated =
2257 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2258 FD->setType(Updated);
2259
2260 if (!AsWritten)
2261 return;
2262
2263 // Update the type in the type source information too.
2264 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2265 // If the type and the type-as-written differ, we may need to update
2266 // the type-as-written too.
2267 if (TSInfo->getType() != FD->getType())
2268 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2269
2270 // FIXME: When we get proper type location information for exceptions,
2271 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2272 // up the TypeSourceInfo;
2273 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2274 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2275 "TypeLoc size mismatch from updating exception specification");
2276 TSInfo->overrideType(Updated);
2277 }
2278}
2279
Chris Lattnerc6395932007-06-22 20:56:16 +00002280/// getComplexType - Return the uniqued reference to the type for a complex
2281/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002282QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002283 // Unique pointers, to guarantee there is only one pointer of a particular
2284 // structure.
2285 llvm::FoldingSetNodeID ID;
2286 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002287
Craig Topper36250ad2014-05-12 05:36:57 +00002288 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002289 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2290 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002291
Chris Lattnerc6395932007-06-22 20:56:16 +00002292 // If the pointee type isn't canonical, this won't be a canonical type either,
2293 // so fill in the canonical type field.
2294 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002295 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002296 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattnerc6395932007-06-22 20:56:16 +00002298 // Get the new insert position for the node we care about.
2299 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002300 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002301 }
John McCall90d1c2d2009-09-24 23:30:46 +00002302 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002303 Types.push_back(New);
2304 ComplexTypes.InsertNode(New, InsertPos);
2305 return QualType(New, 0);
2306}
2307
Chris Lattner970e54e2006-11-12 00:37:36 +00002308/// getPointerType - Return the uniqued reference to the type for a pointer to
2309/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002310QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002311 // Unique pointers, to guarantee there is only one pointer of a particular
2312 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002313 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002314 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002315
Craig Topper36250ad2014-05-12 05:36:57 +00002316 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002317 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002318 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002319
Chris Lattner7ccecb92006-11-12 08:50:50 +00002320 // If the pointee type isn't canonical, this won't be a canonical type either,
2321 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002322 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002323 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002324 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002325
Bob Wilsonc8541f22013-03-15 17:12:43 +00002326 // Get the new insert position for the node we care about.
2327 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002328 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002329 }
John McCall90d1c2d2009-09-24 23:30:46 +00002330 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002331 Types.push_back(New);
2332 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002333 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002334}
2335
Reid Kleckner0503a872013-12-05 01:23:43 +00002336QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2337 llvm::FoldingSetNodeID ID;
2338 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002339 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002340 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2341 if (AT)
2342 return QualType(AT, 0);
2343
2344 QualType Canonical = getCanonicalType(New);
2345
2346 // Get the new insert position for the node we care about.
2347 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002348 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002349
2350 AT = new (*this, TypeAlignment)
2351 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2352 Types.push_back(AT);
2353 AdjustedTypes.InsertNode(AT, InsertPos);
2354 return QualType(AT, 0);
2355}
2356
Reid Kleckner8a365022013-06-24 17:51:48 +00002357QualType ASTContext::getDecayedType(QualType T) const {
2358 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2359
Reid Kleckner8a365022013-06-24 17:51:48 +00002360 QualType Decayed;
2361
2362 // C99 6.7.5.3p7:
2363 // A declaration of a parameter as "array of type" shall be
2364 // adjusted to "qualified pointer to type", where the type
2365 // qualifiers (if any) are those specified within the [ and ] of
2366 // the array type derivation.
2367 if (T->isArrayType())
2368 Decayed = getArrayDecayedType(T);
2369
2370 // C99 6.7.5.3p8:
2371 // A declaration of a parameter as "function returning type"
2372 // shall be adjusted to "pointer to function returning type", as
2373 // in 6.3.2.1.
2374 if (T->isFunctionType())
2375 Decayed = getPointerType(T);
2376
Reid Kleckner0503a872013-12-05 01:23:43 +00002377 llvm::FoldingSetNodeID ID;
2378 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002379 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002380 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2381 if (AT)
2382 return QualType(AT, 0);
2383
Reid Kleckner8a365022013-06-24 17:51:48 +00002384 QualType Canonical = getCanonicalType(Decayed);
2385
2386 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002387 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002388 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002389
Reid Kleckner0503a872013-12-05 01:23:43 +00002390 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2391 Types.push_back(AT);
2392 AdjustedTypes.InsertNode(AT, InsertPos);
2393 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002394}
2395
Mike Stump11289f42009-09-09 15:08:12 +00002396/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002397/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002398QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002399 assert(T->isFunctionType() && "block of function types only");
2400 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002401 // structure.
2402 llvm::FoldingSetNodeID ID;
2403 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002404
Craig Topper36250ad2014-05-12 05:36:57 +00002405 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002406 if (BlockPointerType *PT =
2407 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2408 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002409
2410 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002411 // type either so fill in the canonical type field.
2412 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002413 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002414 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002415
Steve Naroffec33ed92008-08-27 16:04:49 +00002416 // Get the new insert position for the node we care about.
2417 BlockPointerType *NewIP =
2418 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002419 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002420 }
John McCall90d1c2d2009-09-24 23:30:46 +00002421 BlockPointerType *New
2422 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002423 Types.push_back(New);
2424 BlockPointerTypes.InsertNode(New, InsertPos);
2425 return QualType(New, 0);
2426}
2427
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002428/// getLValueReferenceType - Return the uniqued reference to the type for an
2429/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002430QualType
2431ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002432 assert(getCanonicalType(T) != OverloadTy &&
2433 "Unresolved overloaded function type");
2434
Bill Wendling3708c182007-05-27 10:15:43 +00002435 // Unique pointers, to guarantee there is only one pointer of a particular
2436 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002437 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002438 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002439
Craig Topper36250ad2014-05-12 05:36:57 +00002440 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002441 if (LValueReferenceType *RT =
2442 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002443 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002444
John McCallfc93cf92009-10-22 22:37:11 +00002445 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2446
Bill Wendling3708c182007-05-27 10:15:43 +00002447 // If the referencee type isn't canonical, this won't be a canonical type
2448 // either, so fill in the canonical type field.
2449 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002450 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2451 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2452 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002453
Bill Wendling3708c182007-05-27 10:15:43 +00002454 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002455 LValueReferenceType *NewIP =
2456 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002457 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002458 }
2459
John McCall90d1c2d2009-09-24 23:30:46 +00002460 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002461 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2462 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002463 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002464 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002465
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002466 return QualType(New, 0);
2467}
2468
2469/// getRValueReferenceType - Return the uniqued reference to the type for an
2470/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002471QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002472 // Unique pointers, to guarantee there is only one pointer of a particular
2473 // structure.
2474 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002475 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002476
Craig Topper36250ad2014-05-12 05:36:57 +00002477 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002478 if (RValueReferenceType *RT =
2479 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2480 return QualType(RT, 0);
2481
John McCallfc93cf92009-10-22 22:37:11 +00002482 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2483
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002484 // If the referencee type isn't canonical, this won't be a canonical type
2485 // either, so fill in the canonical type field.
2486 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002487 if (InnerRef || !T.isCanonical()) {
2488 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2489 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002490
2491 // Get the new insert position for the node we care about.
2492 RValueReferenceType *NewIP =
2493 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002494 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002495 }
2496
John McCall90d1c2d2009-09-24 23:30:46 +00002497 RValueReferenceType *New
2498 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002499 Types.push_back(New);
2500 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002501 return QualType(New, 0);
2502}
2503
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002504/// getMemberPointerType - Return the uniqued reference to the type for a
2505/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002506QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002507 // Unique pointers, to guarantee there is only one pointer of a particular
2508 // structure.
2509 llvm::FoldingSetNodeID ID;
2510 MemberPointerType::Profile(ID, T, Cls);
2511
Craig Topper36250ad2014-05-12 05:36:57 +00002512 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002513 if (MemberPointerType *PT =
2514 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2515 return QualType(PT, 0);
2516
2517 // If the pointee or class type isn't canonical, this won't be a canonical
2518 // type either, so fill in the canonical type field.
2519 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002520 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002521 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2522
2523 // Get the new insert position for the node we care about.
2524 MemberPointerType *NewIP =
2525 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002526 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002527 }
John McCall90d1c2d2009-09-24 23:30:46 +00002528 MemberPointerType *New
2529 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002530 Types.push_back(New);
2531 MemberPointerTypes.InsertNode(New, InsertPos);
2532 return QualType(New, 0);
2533}
2534
Mike Stump11289f42009-09-09 15:08:12 +00002535/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002536/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002537QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002538 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002539 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002540 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002541 assert((EltTy->isDependentType() ||
2542 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002543 "Constant array of VLAs is illegal!");
2544
Chris Lattnere2df3f92009-05-13 04:12:56 +00002545 // Convert the array size into a canonical width matching the pointer size for
2546 // the target.
2547 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002548 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002549 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner23b7eb62007-06-15 23:05:46 +00002551 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002552 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Craig Topper36250ad2014-05-12 05:36:57 +00002554 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002555 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002556 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002557 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002558
John McCall33ddac02011-01-19 10:06:00 +00002559 // If the element type isn't canonical or has qualifiers, this won't
2560 // be a canonical type either, so fill in the canonical type field.
2561 QualType Canon;
2562 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2563 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002564 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002565 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002566 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002567
Chris Lattner36f8e652007-01-27 08:31:04 +00002568 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002569 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002570 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002571 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
John McCall90d1c2d2009-09-24 23:30:46 +00002574 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002575 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002576 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002577 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002578 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002579}
2580
John McCall06549462011-01-18 08:40:38 +00002581/// getVariableArrayDecayedType - Turns the given type, which may be
2582/// variably-modified, into the corresponding type with all the known
2583/// sizes replaced with [*].
2584QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2585 // Vastly most common case.
2586 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002587
John McCall06549462011-01-18 08:40:38 +00002588 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002589
John McCall06549462011-01-18 08:40:38 +00002590 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002591 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002592 switch (ty->getTypeClass()) {
2593#define TYPE(Class, Base)
2594#define ABSTRACT_TYPE(Class, Base)
2595#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2596#include "clang/AST/TypeNodes.def"
2597 llvm_unreachable("didn't desugar past all non-canonical types?");
2598
2599 // These types should never be variably-modified.
2600 case Type::Builtin:
2601 case Type::Complex:
2602 case Type::Vector:
2603 case Type::ExtVector:
2604 case Type::DependentSizedExtVector:
2605 case Type::ObjCObject:
2606 case Type::ObjCInterface:
2607 case Type::ObjCObjectPointer:
2608 case Type::Record:
2609 case Type::Enum:
2610 case Type::UnresolvedUsing:
2611 case Type::TypeOfExpr:
2612 case Type::TypeOf:
2613 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002614 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002615 case Type::DependentName:
2616 case Type::InjectedClassName:
2617 case Type::TemplateSpecialization:
2618 case Type::DependentTemplateSpecialization:
2619 case Type::TemplateTypeParm:
2620 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002621 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002622 case Type::PackExpansion:
2623 llvm_unreachable("type should never be variably-modified");
2624
2625 // These types can be variably-modified but should never need to
2626 // further decay.
2627 case Type::FunctionNoProto:
2628 case Type::FunctionProto:
2629 case Type::BlockPointer:
2630 case Type::MemberPointer:
2631 return type;
2632
2633 // These types can be variably-modified. All these modifications
2634 // preserve structure except as noted by comments.
2635 // TODO: if we ever care about optimizing VLAs, there are no-op
2636 // optimizations available here.
2637 case Type::Pointer:
2638 result = getPointerType(getVariableArrayDecayedType(
2639 cast<PointerType>(ty)->getPointeeType()));
2640 break;
2641
2642 case Type::LValueReference: {
2643 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2644 result = getLValueReferenceType(
2645 getVariableArrayDecayedType(lv->getPointeeType()),
2646 lv->isSpelledAsLValue());
2647 break;
2648 }
2649
2650 case Type::RValueReference: {
2651 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2652 result = getRValueReferenceType(
2653 getVariableArrayDecayedType(lv->getPointeeType()));
2654 break;
2655 }
2656
Eli Friedman0dfb8892011-10-06 23:00:33 +00002657 case Type::Atomic: {
2658 const AtomicType *at = cast<AtomicType>(ty);
2659 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2660 break;
2661 }
2662
John McCall06549462011-01-18 08:40:38 +00002663 case Type::ConstantArray: {
2664 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2665 result = getConstantArrayType(
2666 getVariableArrayDecayedType(cat->getElementType()),
2667 cat->getSize(),
2668 cat->getSizeModifier(),
2669 cat->getIndexTypeCVRQualifiers());
2670 break;
2671 }
2672
2673 case Type::DependentSizedArray: {
2674 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2675 result = getDependentSizedArrayType(
2676 getVariableArrayDecayedType(dat->getElementType()),
2677 dat->getSizeExpr(),
2678 dat->getSizeModifier(),
2679 dat->getIndexTypeCVRQualifiers(),
2680 dat->getBracketsRange());
2681 break;
2682 }
2683
2684 // Turn incomplete types into [*] types.
2685 case Type::IncompleteArray: {
2686 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2687 result = getVariableArrayType(
2688 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002689 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002690 ArrayType::Normal,
2691 iat->getIndexTypeCVRQualifiers(),
2692 SourceRange());
2693 break;
2694 }
2695
2696 // Turn VLA types into [*] types.
2697 case Type::VariableArray: {
2698 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2699 result = getVariableArrayType(
2700 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002701 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002702 ArrayType::Star,
2703 vat->getIndexTypeCVRQualifiers(),
2704 vat->getBracketsRange());
2705 break;
2706 }
2707 }
2708
2709 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002710 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002711}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002712
Steve Naroffcadebd02007-08-30 18:14:25 +00002713/// getVariableArrayType - Returns a non-unique reference to the type for a
2714/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002715QualType ASTContext::getVariableArrayType(QualType EltTy,
2716 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002717 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002718 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002719 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002720 // Since we don't unique expressions, it isn't possible to unique VLA's
2721 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002722 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002723
John McCall33ddac02011-01-19 10:06:00 +00002724 // Be sure to pull qualifiers off the element type.
2725 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2726 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002727 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002728 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002729 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002730 }
2731
John McCall90d1c2d2009-09-24 23:30:46 +00002732 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002733 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002734
2735 VariableArrayTypes.push_back(New);
2736 Types.push_back(New);
2737 return QualType(New, 0);
2738}
2739
Douglas Gregor4619e432008-12-05 23:32:09 +00002740/// getDependentSizedArrayType - Returns a non-unique reference to
2741/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002742/// type.
John McCall33ddac02011-01-19 10:06:00 +00002743QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2744 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002745 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002746 unsigned elementTypeQuals,
2747 SourceRange brackets) const {
2748 assert((!numElements || numElements->isTypeDependent() ||
2749 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002750 "Size must be type- or value-dependent!");
2751
John McCall33ddac02011-01-19 10:06:00 +00002752 // Dependently-sized array types that do not have a specified number
2753 // of elements will have their sizes deduced from a dependent
2754 // initializer. We do no canonicalization here at all, which is okay
2755 // because they can't be used in most locations.
2756 if (!numElements) {
2757 DependentSizedArrayType *newType
2758 = new (*this, TypeAlignment)
2759 DependentSizedArrayType(*this, elementType, QualType(),
2760 numElements, ASM, elementTypeQuals,
2761 brackets);
2762 Types.push_back(newType);
2763 return QualType(newType, 0);
2764 }
2765
2766 // Otherwise, we actually build a new type every time, but we
2767 // also build a canonical type.
2768
2769 SplitQualType canonElementType = getCanonicalType(elementType).split();
2770
Craig Topper36250ad2014-05-12 05:36:57 +00002771 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002772 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002773 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002774 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002775 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002776
John McCall33ddac02011-01-19 10:06:00 +00002777 // Look for an existing type with these properties.
2778 DependentSizedArrayType *canonTy =
2779 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002780
John McCall33ddac02011-01-19 10:06:00 +00002781 // If we don't have one, build one.
2782 if (!canonTy) {
2783 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002784 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002785 QualType(), numElements, ASM, elementTypeQuals,
2786 brackets);
2787 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2788 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002789 }
2790
John McCall33ddac02011-01-19 10:06:00 +00002791 // Apply qualifiers from the element type to the array.
2792 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002793 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002794
David Majnemer16a74702015-07-24 05:54:19 +00002795 // If we didn't need extra canonicalization for the element type or the size
2796 // expression, then just use that as our result.
2797 if (QualType(canonElementType.Ty, 0) == elementType &&
2798 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002799 return canon;
2800
2801 // Otherwise, we need to build a type which follows the spelling
2802 // of the element type.
2803 DependentSizedArrayType *sugaredType
2804 = new (*this, TypeAlignment)
2805 DependentSizedArrayType(*this, elementType, canon, numElements,
2806 ASM, elementTypeQuals, brackets);
2807 Types.push_back(sugaredType);
2808 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002809}
2810
John McCall33ddac02011-01-19 10:06:00 +00002811QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002812 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002813 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002814 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002815 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002816
Craig Topper36250ad2014-05-12 05:36:57 +00002817 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002818 if (IncompleteArrayType *iat =
2819 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2820 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002821
2822 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002823 // either, so fill in the canonical type field. We also have to pull
2824 // qualifiers off the element type.
2825 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002826
John McCall33ddac02011-01-19 10:06:00 +00002827 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2828 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002829 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002830 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002831 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002832
2833 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002834 IncompleteArrayType *existing =
2835 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2836 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002837 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002838
John McCall33ddac02011-01-19 10:06:00 +00002839 IncompleteArrayType *newType = new (*this, TypeAlignment)
2840 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002841
John McCall33ddac02011-01-19 10:06:00 +00002842 IncompleteArrayTypes.InsertNode(newType, insertPos);
2843 Types.push_back(newType);
2844 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002845}
2846
Steve Naroff91fcddb2007-07-18 18:00:27 +00002847/// getVectorType - Return the unique reference to a vector type of
2848/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002849QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002850 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002851 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002852
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002853 // Check if we've already instantiated a vector of this type.
2854 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002855 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002856
Craig Topper36250ad2014-05-12 05:36:57 +00002857 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002858 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2859 return QualType(VTP, 0);
2860
2861 // If the element type isn't canonical, this won't be a canonical type either,
2862 // so fill in the canonical type field.
2863 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002864 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002865 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002867 // Get the new insert position for the node we care about.
2868 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002869 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002870 }
John McCall90d1c2d2009-09-24 23:30:46 +00002871 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002872 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002873 VectorTypes.InsertNode(New, InsertPos);
2874 Types.push_back(New);
2875 return QualType(New, 0);
2876}
2877
Nate Begemance4d7fc2008-04-18 23:10:10 +00002878/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002879/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002880QualType
2881ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002882 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002883
Steve Naroff91fcddb2007-07-18 18:00:27 +00002884 // Check if we've already instantiated a vector of this type.
2885 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002886 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002887 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002888 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002889 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2890 return QualType(VTP, 0);
2891
2892 // If the element type isn't canonical, this won't be a canonical type either,
2893 // so fill in the canonical type field.
2894 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002895 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002896 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002897
Steve Naroff91fcddb2007-07-18 18:00:27 +00002898 // Get the new insert position for the node we care about.
2899 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002900 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002901 }
John McCall90d1c2d2009-09-24 23:30:46 +00002902 ExtVectorType *New = new (*this, TypeAlignment)
2903 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002904 VectorTypes.InsertNode(New, InsertPos);
2905 Types.push_back(New);
2906 return QualType(New, 0);
2907}
2908
Jay Foad39c79802011-01-12 09:06:06 +00002909QualType
2910ASTContext::getDependentSizedExtVectorType(QualType vecType,
2911 Expr *SizeExpr,
2912 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002913 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002914 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002915 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002916
Craig Topper36250ad2014-05-12 05:36:57 +00002917 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002918 DependentSizedExtVectorType *Canon
2919 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2920 DependentSizedExtVectorType *New;
2921 if (Canon) {
2922 // We already have a canonical version of this array type; use it as
2923 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002924 New = new (*this, TypeAlignment)
2925 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2926 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002927 } else {
2928 QualType CanonVecTy = getCanonicalType(vecType);
2929 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002930 New = new (*this, TypeAlignment)
2931 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2932 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002933
2934 DependentSizedExtVectorType *CanonCheck
2935 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2936 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2937 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002938 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2939 } else {
2940 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2941 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002942 New = new (*this, TypeAlignment)
2943 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002944 }
2945 }
Mike Stump11289f42009-09-09 15:08:12 +00002946
Douglas Gregor758a8692009-06-17 21:51:59 +00002947 Types.push_back(New);
2948 return QualType(New, 0);
2949}
2950
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002951/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002952///
Jay Foad39c79802011-01-12 09:06:06 +00002953QualType
2954ASTContext::getFunctionNoProtoType(QualType ResultTy,
2955 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002956 const CallingConv CallConv = Info.getCC();
2957
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002958 // Unique functions, to guarantee there is only one function of a particular
2959 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002960 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002961 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Craig Topper36250ad2014-05-12 05:36:57 +00002963 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002964 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002965 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002966 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002967
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002968 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002969 if (!ResultTy.isCanonical()) {
2970 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002971
Chris Lattner47955de2007-01-27 08:37:20 +00002972 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002973 FunctionNoProtoType *NewIP =
2974 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002975 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002976 }
Mike Stump11289f42009-09-09 15:08:12 +00002977
Roman Divacky65b88cd2011-03-01 17:40:53 +00002978 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002979 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002980 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002981 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002982 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002983 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002984}
2985
Douglas Gregorcd780372013-01-17 23:36:45 +00002986/// \brief Determine whether \p T is canonical as the result type of a function.
2987static bool isCanonicalResultType(QualType T) {
2988 return T.isCanonical() &&
2989 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2990 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2991}
2992
Douglas Gregora602a152015-10-01 20:20:47 +00002993CanQualType
2994ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
2995 CanQualType CanResultType = getCanonicalType(ResultType);
2996
2997 // Canonical result types do not have ARC lifetime qualifiers.
2998 if (CanResultType.getQualifiers().hasObjCLifetime()) {
2999 Qualifiers Qs = CanResultType.getQualifiers();
3000 Qs.removeObjCLifetime();
3001 return CanQualType::CreateUnsafe(
3002 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3003 }
3004
3005 return CanResultType;
3006}
3007
Jay Foad39c79802011-01-12 09:06:06 +00003008QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003009ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003010 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003011 size_t NumArgs = ArgArray.size();
3012
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003013 // Unique functions, to guarantee there is only one function of a particular
3014 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003015 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003016 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3017 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003018
Craig Topper36250ad2014-05-12 05:36:57 +00003019 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003020 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003021 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003022 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003023
3024 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003025 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003026 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003027 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003028 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003029 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003030 isCanonical = false;
3031
3032 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003033 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003034 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003035 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003036 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003037 CanonicalArgs.reserve(NumArgs);
3038 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003039 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003040
John McCalldb40c7f2010-12-14 08:05:40 +00003041 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003042 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003043 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003044
Douglas Gregora602a152015-10-01 20:20:47 +00003045 // Adjust the canonical function result type.
3046 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003047 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003048
Chris Lattnerfd4de792007-01-27 01:15:32 +00003049 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003050 FunctionProtoType *NewIP =
3051 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003052 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003053 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003054
John McCall31168b02011-06-15 23:02:42 +00003055 // FunctionProtoType objects are allocated with extra bytes after
3056 // them for three variable size arrays at the end:
3057 // - parameter types
3058 // - exception types
3059 // - consumed-arguments flags
3060 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003061 // expression, or information used to resolve the exception
3062 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003063 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003064 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003065 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3066 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3067 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003068 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003069 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003070 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003071 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003072 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003073 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003074 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003075 Size += NumArgs * sizeof(bool);
3076
John McCalldb40c7f2010-12-14 08:05:40 +00003077 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003078 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003079 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003080 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003081 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003082 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003083}
Chris Lattneref51c202006-11-10 07:17:23 +00003084
John McCalle78aac42010-03-10 03:28:59 +00003085#ifndef NDEBUG
3086static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3087 if (!isa<CXXRecordDecl>(D)) return false;
3088 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3089 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3090 return true;
3091 if (RD->getDescribedClassTemplate() &&
3092 !isa<ClassTemplateSpecializationDecl>(RD))
3093 return true;
3094 return false;
3095}
3096#endif
3097
3098/// getInjectedClassNameType - Return the unique reference to the
3099/// injected class name type for the specified templated declaration.
3100QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003101 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003102 assert(NeedsInjectedClassNameType(Decl));
3103 if (Decl->TypeForDecl) {
3104 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003105 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003106 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3107 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3108 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3109 } else {
John McCall424cec92011-01-19 06:33:43 +00003110 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003111 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003112 Decl->TypeForDecl = newType;
3113 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003114 }
3115 return QualType(Decl->TypeForDecl, 0);
3116}
3117
Douglas Gregor83a586e2008-04-13 21:07:44 +00003118/// getTypeDeclType - Return the unique reference to the type for the
3119/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003120QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003121 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003122 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003123
Richard Smithdda56e42011-04-15 14:24:37 +00003124 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003125 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003126
John McCall96f0b5f2010-03-10 06:48:02 +00003127 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3128 "Template type parameter types are always available.");
3129
John McCall81e38502010-02-16 03:57:14 +00003130 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003131 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003132 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003133 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003134 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003135 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003136 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003137 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003138 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003139 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3140 Decl->TypeForDecl = newType;
3141 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003142 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003143 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003144
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003145 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003146}
3147
Chris Lattner32d920b2007-01-26 02:01:53 +00003148/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003149/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003150QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003151ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3152 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003153 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003154
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003155 if (Canonical.isNull())
3156 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003157 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003158 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003159 Decl->TypeForDecl = newType;
3160 Types.push_back(newType);
3161 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003162}
3163
Jay Foad39c79802011-01-12 09:06:06 +00003164QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003165 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3166
Douglas Gregorec9fd132012-01-14 16:38:05 +00003167 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003168 if (PrevDecl->TypeForDecl)
3169 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3170
John McCall424cec92011-01-19 06:33:43 +00003171 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3172 Decl->TypeForDecl = newType;
3173 Types.push_back(newType);
3174 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003175}
3176
Jay Foad39c79802011-01-12 09:06:06 +00003177QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003178 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3179
Douglas Gregorec9fd132012-01-14 16:38:05 +00003180 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003181 if (PrevDecl->TypeForDecl)
3182 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3183
John McCall424cec92011-01-19 06:33:43 +00003184 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3185 Decl->TypeForDecl = newType;
3186 Types.push_back(newType);
3187 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003188}
3189
John McCall81904512011-01-06 01:58:22 +00003190QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3191 QualType modifiedType,
3192 QualType equivalentType) {
3193 llvm::FoldingSetNodeID id;
3194 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3195
Craig Topper36250ad2014-05-12 05:36:57 +00003196 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003197 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3198 if (type) return QualType(type, 0);
3199
3200 QualType canon = getCanonicalType(equivalentType);
3201 type = new (*this, TypeAlignment)
3202 AttributedType(canon, attrKind, modifiedType, equivalentType);
3203
3204 Types.push_back(type);
3205 AttributedTypes.InsertNode(type, insertPos);
3206
3207 return QualType(type, 0);
3208}
3209
3210
John McCallcebee162009-10-18 09:09:24 +00003211/// \brief Retrieve a substitution-result type.
3212QualType
3213ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003214 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003215 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003216 && "replacement types must always be canonical");
3217
3218 llvm::FoldingSetNodeID ID;
3219 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003220 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003221 SubstTemplateTypeParmType *SubstParm
3222 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3223
3224 if (!SubstParm) {
3225 SubstParm = new (*this, TypeAlignment)
3226 SubstTemplateTypeParmType(Parm, Replacement);
3227 Types.push_back(SubstParm);
3228 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3229 }
3230
3231 return QualType(SubstParm, 0);
3232}
3233
Douglas Gregorada4b792011-01-14 02:55:32 +00003234/// \brief Retrieve a
3235QualType ASTContext::getSubstTemplateTypeParmPackType(
3236 const TemplateTypeParmType *Parm,
3237 const TemplateArgument &ArgPack) {
3238#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003239 for (const auto &P : ArgPack.pack_elements()) {
3240 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3241 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003242 }
3243#endif
3244
3245 llvm::FoldingSetNodeID ID;
3246 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003247 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003248 if (SubstTemplateTypeParmPackType *SubstParm
3249 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3250 return QualType(SubstParm, 0);
3251
3252 QualType Canon;
3253 if (!Parm->isCanonicalUnqualified()) {
3254 Canon = getCanonicalType(QualType(Parm, 0));
3255 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3256 ArgPack);
3257 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3258 }
3259
3260 SubstTemplateTypeParmPackType *SubstParm
3261 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3262 ArgPack);
3263 Types.push_back(SubstParm);
3264 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3265 return QualType(SubstParm, 0);
3266}
3267
Douglas Gregoreff93e02009-02-05 23:33:38 +00003268/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003269/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003270/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003271QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003272 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003273 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003274 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003275 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003276 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003277 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003278 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3279
3280 if (TypeParm)
3281 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003282
Chandler Carruth08836322011-05-01 00:51:33 +00003283 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003284 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003285 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003286
3287 TemplateTypeParmType *TypeCheck
3288 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3289 assert(!TypeCheck && "Template type parameter canonical type broken");
3290 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003291 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003292 TypeParm = new (*this, TypeAlignment)
3293 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003294
3295 Types.push_back(TypeParm);
3296 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3297
3298 return QualType(TypeParm, 0);
3299}
3300
John McCalle78aac42010-03-10 03:28:59 +00003301TypeSourceInfo *
3302ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3303 SourceLocation NameLoc,
3304 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003305 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003306 assert(!Name.getAsDependentTemplateName() &&
3307 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003308 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003309
3310 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003311 TemplateSpecializationTypeLoc TL =
3312 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003313 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003314 TL.setTemplateNameLoc(NameLoc);
3315 TL.setLAngleLoc(Args.getLAngleLoc());
3316 TL.setRAngleLoc(Args.getRAngleLoc());
3317 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3318 TL.setArgLocInfo(i, Args[i].getLocInfo());
3319 return DI;
3320}
3321
Mike Stump11289f42009-09-09 15:08:12 +00003322QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003323ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003324 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003325 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003326 assert(!Template.getAsDependentTemplateName() &&
3327 "No dependent template names here!");
3328
John McCall6b51f282009-11-23 01:53:49 +00003329 unsigned NumArgs = Args.size();
3330
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003331 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003332 ArgVec.reserve(NumArgs);
3333 for (unsigned i = 0; i != NumArgs; ++i)
3334 ArgVec.push_back(Args[i].getArgument());
3335
John McCall2408e322010-04-27 00:57:59 +00003336 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003337 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003338}
3339
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003340#ifndef NDEBUG
3341static bool hasAnyPackExpansions(const TemplateArgument *Args,
3342 unsigned NumArgs) {
3343 for (unsigned I = 0; I != NumArgs; ++I)
3344 if (Args[I].isPackExpansion())
3345 return true;
3346
3347 return true;
3348}
3349#endif
3350
John McCall0ad16662009-10-29 08:12:44 +00003351QualType
3352ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003353 const TemplateArgument *Args,
3354 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003355 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003356 assert(!Template.getAsDependentTemplateName() &&
3357 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003358 // Look through qualified template names.
3359 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3360 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003361
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003362 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003363 Template.getAsTemplateDecl() &&
3364 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003365 QualType CanonType;
3366 if (!Underlying.isNull())
3367 CanonType = getCanonicalType(Underlying);
3368 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003369 // We can get here with an alias template when the specialization contains
3370 // a pack expansion that does not match up with a parameter pack.
3371 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3372 "Caller must compute aliased type");
3373 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003374 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3375 NumArgs);
3376 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003377
Douglas Gregora8e02e72009-07-28 23:00:59 +00003378 // Allocate the (non-canonical) template specialization type, but don't
3379 // try to unique it: these types typically have location information that
3380 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003381 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3382 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003383 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003384 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003385 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003386 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3387 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregor8bf42052009-02-09 18:46:07 +00003389 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003390 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003391}
3392
Mike Stump11289f42009-09-09 15:08:12 +00003393QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003394ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3395 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003396 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003397 assert(!Template.getAsDependentTemplateName() &&
3398 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003399
Douglas Gregore29139c2011-03-03 17:04:51 +00003400 // Look through qualified template names.
3401 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3402 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003403
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003404 // Build the canonical template specialization type.
3405 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003406 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003407 CanonArgs.reserve(NumArgs);
3408 for (unsigned I = 0; I != NumArgs; ++I)
3409 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3410
3411 // Determine whether this canonical template specialization type already
3412 // exists.
3413 llvm::FoldingSetNodeID ID;
3414 TemplateSpecializationType::Profile(ID, CanonTemplate,
3415 CanonArgs.data(), NumArgs, *this);
3416
Craig Topper36250ad2014-05-12 05:36:57 +00003417 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003418 TemplateSpecializationType *Spec
3419 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3420
3421 if (!Spec) {
3422 // Allocate a new canonical template specialization type.
3423 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3424 sizeof(TemplateArgument) * NumArgs),
3425 TypeAlignment);
3426 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3427 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003428 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003429 Types.push_back(Spec);
3430 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3431 }
3432
3433 assert(Spec->isDependentType() &&
3434 "Non-dependent template-id type must have a canonical type");
3435 return QualType(Spec, 0);
3436}
3437
3438QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003439ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3440 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003441 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003442 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003443 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003444
Craig Topper36250ad2014-05-12 05:36:57 +00003445 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003446 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003447 if (T)
3448 return QualType(T, 0);
3449
Douglas Gregorc42075a2010-02-04 18:10:26 +00003450 QualType Canon = NamedType;
3451 if (!Canon.isCanonical()) {
3452 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003453 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3454 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003455 (void)CheckT;
3456 }
3457
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003458 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003459 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003460 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003461 return QualType(T, 0);
3462}
3463
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003464QualType
Jay Foad39c79802011-01-12 09:06:06 +00003465ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003466 llvm::FoldingSetNodeID ID;
3467 ParenType::Profile(ID, InnerType);
3468
Craig Topper36250ad2014-05-12 05:36:57 +00003469 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003470 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3471 if (T)
3472 return QualType(T, 0);
3473
3474 QualType Canon = InnerType;
3475 if (!Canon.isCanonical()) {
3476 Canon = getCanonicalType(InnerType);
3477 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3478 assert(!CheckT && "Paren canonical type broken");
3479 (void)CheckT;
3480 }
3481
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003482 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003483 Types.push_back(T);
3484 ParenTypes.InsertNode(T, InsertPos);
3485 return QualType(T, 0);
3486}
3487
Douglas Gregor02085352010-03-31 20:19:30 +00003488QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3489 NestedNameSpecifier *NNS,
3490 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003491 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003492 if (Canon.isNull()) {
3493 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003494 ElaboratedTypeKeyword CanonKeyword = Keyword;
3495 if (Keyword == ETK_None)
3496 CanonKeyword = ETK_Typename;
3497
3498 if (CanonNNS != NNS || CanonKeyword != Keyword)
3499 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003500 }
3501
3502 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003503 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003504
Craig Topper36250ad2014-05-12 05:36:57 +00003505 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003506 DependentNameType *T
3507 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003508 if (T)
3509 return QualType(T, 0);
3510
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003511 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003512 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003513 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003514 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003515}
3516
Mike Stump11289f42009-09-09 15:08:12 +00003517QualType
John McCallc392f372010-06-11 00:33:02 +00003518ASTContext::getDependentTemplateSpecializationType(
3519 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003520 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003521 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003522 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003523 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003524 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003525 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3526 ArgCopy.push_back(Args[I].getArgument());
3527 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3528 ArgCopy.size(),
3529 ArgCopy.data());
3530}
3531
3532QualType
3533ASTContext::getDependentTemplateSpecializationType(
3534 ElaboratedTypeKeyword Keyword,
3535 NestedNameSpecifier *NNS,
3536 const IdentifierInfo *Name,
3537 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003538 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003539 assert((!NNS || NNS->isDependent()) &&
3540 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003541
Douglas Gregorc42075a2010-02-04 18:10:26 +00003542 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003543 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3544 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003545
Craig Topper36250ad2014-05-12 05:36:57 +00003546 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003547 DependentTemplateSpecializationType *T
3548 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003549 if (T)
3550 return QualType(T, 0);
3551
John McCallc392f372010-06-11 00:33:02 +00003552 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003553
John McCallc392f372010-06-11 00:33:02 +00003554 ElaboratedTypeKeyword CanonKeyword = Keyword;
3555 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3556
3557 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003558 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003559 for (unsigned I = 0; I != NumArgs; ++I) {
3560 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3561 if (!CanonArgs[I].structurallyEquals(Args[I]))
3562 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003563 }
3564
John McCallc392f372010-06-11 00:33:02 +00003565 QualType Canon;
3566 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3567 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3568 Name, NumArgs,
3569 CanonArgs.data());
3570
3571 // Find the insert position again.
3572 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3573 }
3574
3575 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3576 sizeof(TemplateArgument) * NumArgs),
3577 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003578 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003579 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003580 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003581 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003582 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003583}
3584
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003585QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003586 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003587 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003588 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003589
3590 assert(Pattern->containsUnexpandedParameterPack() &&
3591 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003592 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003593 PackExpansionType *T
3594 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 if (T)
3596 return QualType(T, 0);
3597
3598 QualType Canon;
3599 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003600 Canon = getCanonicalType(Pattern);
3601 // The canonical type might not contain an unexpanded parameter pack, if it
3602 // contains an alias template specialization which ignores one of its
3603 // parameters.
3604 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003605 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003606
Richard Smith68eea502012-07-16 00:20:35 +00003607 // Find the insert position again, in case we inserted an element into
3608 // PackExpansionTypes and invalidated our insert position.
3609 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3610 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003611 }
3612
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003613 T = new (*this, TypeAlignment)
3614 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003615 Types.push_back(T);
3616 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003617 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003618}
3619
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003620/// CmpProtocolNames - Comparison predicate for sorting protocols
3621/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003622static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3623 ObjCProtocolDecl *const *RHS) {
3624 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003625}
3626
John McCall8b07ec22010-05-15 11:32:37 +00003627static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003628 unsigned NumProtocols) {
3629 if (NumProtocols == 0) return true;
3630
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003631 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3632 return false;
3633
John McCallfc93cf92009-10-22 22:37:11 +00003634 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003635 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003636 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003637 return false;
3638 return true;
3639}
3640
3641static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003642 unsigned &NumProtocols) {
3643 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003644
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003645 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003646 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003647
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003648 // Canonicalize.
3649 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3650 Protocols[I] = Protocols[I]->getCanonicalDecl();
3651
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003652 // Remove duplicates.
3653 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3654 NumProtocols = ProtocolsEnd-Protocols;
3655}
3656
John McCall8b07ec22010-05-15 11:32:37 +00003657QualType ASTContext::getObjCObjectType(QualType BaseType,
3658 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003659 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003660 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003661 llvm::makeArrayRef(Protocols, NumProtocols),
3662 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003663}
3664
3665QualType ASTContext::getObjCObjectType(
3666 QualType baseType,
3667 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003668 ArrayRef<ObjCProtocolDecl *> protocols,
3669 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003670 // If the base type is an interface and there aren't any protocols or
3671 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003672 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3673 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003674 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003675
3676 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003677 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003678 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003679 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003680 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3681 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003682
Douglas Gregore9d95f12015-07-07 03:57:35 +00003683 // Determine the type arguments to be used for canonicalization,
3684 // which may be explicitly specified here or written on the base
3685 // type.
3686 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3687 if (effectiveTypeArgs.empty()) {
3688 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3689 effectiveTypeArgs = baseObject->getTypeArgs();
3690 }
John McCallfc93cf92009-10-22 22:37:11 +00003691
Douglas Gregore9d95f12015-07-07 03:57:35 +00003692 // Build the canonical type, which has the canonical base type and a
3693 // sorted-and-uniqued list of protocols and the type arguments
3694 // canonicalized.
3695 QualType canonical;
3696 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3697 effectiveTypeArgs.end(),
3698 [&](QualType type) {
3699 return type.isCanonical();
3700 });
3701 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3702 protocols.size());
3703 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3704 // Determine the canonical type arguments.
3705 ArrayRef<QualType> canonTypeArgs;
3706 SmallVector<QualType, 4> canonTypeArgsVec;
3707 if (!typeArgsAreCanonical) {
3708 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3709 for (auto typeArg : effectiveTypeArgs)
3710 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3711 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003712 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003713 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003714 }
3715
Douglas Gregore9d95f12015-07-07 03:57:35 +00003716 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3717 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3718 if (!protocolsSorted) {
3719 canonProtocolsVec.insert(canonProtocolsVec.begin(),
3720 protocols.begin(),
3721 protocols.end());
3722 unsigned uniqueCount = protocols.size();
3723 SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3724 canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3725 } else {
3726 canonProtocols = protocols;
3727 }
3728
3729 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003730 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003731
John McCallfc93cf92009-10-22 22:37:11 +00003732 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003733 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3734 }
3735
Douglas Gregore9d95f12015-07-07 03:57:35 +00003736 unsigned size = sizeof(ObjCObjectTypeImpl);
3737 size += typeArgs.size() * sizeof(QualType);
3738 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3739 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003740 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003741 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3742 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003743
3744 Types.push_back(T);
3745 ObjCObjectTypes.InsertNode(T, InsertPos);
3746 return QualType(T, 0);
3747}
3748
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003749/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3750/// protocol list adopt all protocols in QT's qualified-id protocol
3751/// list.
3752bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3753 ObjCInterfaceDecl *IC) {
3754 if (!QT->isObjCQualifiedIdType())
3755 return false;
3756
3757 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3758 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003759 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003760 if (!IC->ClassImplementsProtocol(Proto, false))
3761 return false;
3762 }
3763 return true;
3764 }
3765 return false;
3766}
3767
3768/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3769/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3770/// of protocols.
3771bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3772 ObjCInterfaceDecl *IDecl) {
3773 if (!QT->isObjCQualifiedIdType())
3774 return false;
3775 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3776 if (!OPT)
3777 return false;
3778 if (!IDecl->hasDefinition())
3779 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003780 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3781 CollectInheritedProtocols(IDecl, InheritedProtocols);
3782 if (InheritedProtocols.empty())
3783 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003784 // Check that if every protocol in list of id<plist> conforms to a protcol
3785 // of IDecl's, then bridge casting is ok.
3786 bool Conforms = false;
3787 for (auto *Proto : OPT->quals()) {
3788 Conforms = false;
3789 for (auto *PI : InheritedProtocols) {
3790 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3791 Conforms = true;
3792 break;
3793 }
3794 }
3795 if (!Conforms)
3796 break;
3797 }
3798 if (Conforms)
3799 return true;
3800
Aaron Ballman83731462014-03-17 16:14:00 +00003801 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003802 // If both the right and left sides have qualifiers.
3803 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003804 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003805 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003806 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003807 break;
3808 }
3809 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003810 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003811 }
3812 return true;
3813}
3814
John McCall8b07ec22010-05-15 11:32:37 +00003815/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3816/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003817QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003818 llvm::FoldingSetNodeID ID;
3819 ObjCObjectPointerType::Profile(ID, ObjectT);
3820
Craig Topper36250ad2014-05-12 05:36:57 +00003821 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003822 if (ObjCObjectPointerType *QT =
3823 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3824 return QualType(QT, 0);
3825
3826 // Find the canonical object type.
3827 QualType Canonical;
3828 if (!ObjectT.isCanonical()) {
3829 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3830
3831 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003832 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3833 }
3834
Douglas Gregorf85bee62010-02-08 22:59:26 +00003835 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003836 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3837 ObjCObjectPointerType *QType =
3838 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003839
Steve Narofffb4330f2009-06-17 22:40:22 +00003840 Types.push_back(QType);
3841 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003842 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003843}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003844
Douglas Gregor1c283312010-08-11 12:19:30 +00003845/// getObjCInterfaceType - Return the unique reference to the type for the
3846/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003847QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3848 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003849 if (Decl->TypeForDecl)
3850 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003851
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003852 if (PrevDecl) {
3853 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3854 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3855 return QualType(PrevDecl->TypeForDecl, 0);
3856 }
3857
Douglas Gregor7671e532011-12-16 16:34:57 +00003858 // Prefer the definition, if there is one.
3859 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3860 Decl = Def;
3861
Douglas Gregor1c283312010-08-11 12:19:30 +00003862 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3863 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3864 Decl->TypeForDecl = T;
3865 Types.push_back(T);
3866 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003867}
3868
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003869/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3870/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003871/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003872/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003873/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003874QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003875 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003876 if (tofExpr->isTypeDependent()) {
3877 llvm::FoldingSetNodeID ID;
3878 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003879
Craig Topper36250ad2014-05-12 05:36:57 +00003880 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003881 DependentTypeOfExprType *Canon
3882 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3883 if (Canon) {
3884 // We already have a "canonical" version of an identical, dependent
3885 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003886 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003887 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003888 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003889 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003890 Canon
3891 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003892 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3893 toe = Canon;
3894 }
3895 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003896 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003897 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003898 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003899 Types.push_back(toe);
3900 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003901}
3902
Steve Naroffa773cd52007-08-01 18:02:17 +00003903/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003904/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003905/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003906/// an issue. This doesn't affect the type checker, since it operates
3907/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003908QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003909 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003910 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003911 Types.push_back(tot);
3912 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003913}
3914
Anders Carlssonad6bd352009-06-24 21:24:56 +00003915
Richard Smith8eb1d322014-06-05 20:13:13 +00003916/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3917/// nodes. This would never be helpful, since each such type has its own
3918/// expression, and would not give a significant memory saving, since there
3919/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003920QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003921 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003922
3923 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003924 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003925 // unique dependent type. Two such decltype-specifiers refer to the same
3926 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003927 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003928 llvm::FoldingSetNodeID ID;
3929 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003930
Craig Topper36250ad2014-05-12 05:36:57 +00003931 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003932 DependentDecltypeType *Canon
3933 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003934 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003935 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003936 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003937 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003938 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003939 dt = new (*this, TypeAlignment)
3940 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003941 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003942 dt = new (*this, TypeAlignment)
3943 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003944 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003945 Types.push_back(dt);
3946 return QualType(dt, 0);
3947}
3948
Alexis Hunte852b102011-05-24 22:41:36 +00003949/// getUnaryTransformationType - We don't unique these, since the memory
3950/// savings are minimal and these are rare.
3951QualType ASTContext::getUnaryTransformType(QualType BaseType,
3952 QualType UnderlyingType,
3953 UnaryTransformType::UTTKind Kind)
3954 const {
3955 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003956 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3957 Kind,
3958 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003959 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003960 Types.push_back(Ty);
3961 return QualType(Ty, 0);
3962}
3963
Richard Smith2a7d4812013-05-04 07:00:32 +00003964/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3965/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3966/// canonical deduced-but-dependent 'auto' type.
3967QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003968 bool IsDependent) const {
3969 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003970 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003971
Richard Smith2a7d4812013-05-04 07:00:32 +00003972 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003973 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003974 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003975 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003976 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3977 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003978
Richard Smith74aeef52013-04-26 16:15:35 +00003979 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003980 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003981 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003982 Types.push_back(AT);
3983 if (InsertPos)
3984 AutoTypes.InsertNode(AT, InsertPos);
3985 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003986}
3987
Eli Friedman0dfb8892011-10-06 23:00:33 +00003988/// getAtomicType - Return the uniqued reference to the atomic type for
3989/// the given value type.
3990QualType ASTContext::getAtomicType(QualType T) const {
3991 // Unique pointers, to guarantee there is only one pointer of a particular
3992 // structure.
3993 llvm::FoldingSetNodeID ID;
3994 AtomicType::Profile(ID, T);
3995
Craig Topper36250ad2014-05-12 05:36:57 +00003996 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003997 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3998 return QualType(AT, 0);
3999
4000 // If the atomic value type isn't canonical, this won't be a canonical type
4001 // either, so fill in the canonical type field.
4002 QualType Canonical;
4003 if (!T.isCanonical()) {
4004 Canonical = getAtomicType(getCanonicalType(T));
4005
4006 // Get the new insert position for the node we care about.
4007 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004008 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004009 }
4010 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4011 Types.push_back(New);
4012 AtomicTypes.InsertNode(New, InsertPos);
4013 return QualType(New, 0);
4014}
4015
Richard Smith02e85f32011-04-14 22:09:26 +00004016/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4017QualType ASTContext::getAutoDeductType() const {
4018 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004019 AutoDeductTy = QualType(
4020 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004021 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004022 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004023 return AutoDeductTy;
4024}
4025
4026/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4027QualType ASTContext::getAutoRRefDeductType() const {
4028 if (AutoRRefDeductTy.isNull())
4029 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4030 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4031 return AutoRRefDeductTy;
4032}
4033
Chris Lattnerfb072462007-01-23 05:45:31 +00004034/// getTagDeclType - Return the unique reference to the type for the
4035/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004036QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004037 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004038 // FIXME: What is the design on getTagDeclType when it requires casting
4039 // away const? mutable?
4040 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004041}
4042
Mike Stump11289f42009-09-09 15:08:12 +00004043/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4044/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4045/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004046CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004047 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004048}
Chris Lattnerfb072462007-01-23 05:45:31 +00004049
Hans Wennborg27541db2011-10-27 08:29:09 +00004050/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4051CanQualType ASTContext::getIntMaxType() const {
4052 return getFromTargetType(Target->getIntMaxType());
4053}
4054
4055/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4056CanQualType ASTContext::getUIntMaxType() const {
4057 return getFromTargetType(Target->getUIntMaxType());
4058}
4059
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004060/// getSignedWCharType - Return the type of "signed wchar_t".
4061/// Used when in C++, as a GCC extension.
4062QualType ASTContext::getSignedWCharType() const {
4063 // FIXME: derive from "Target" ?
4064 return WCharTy;
4065}
4066
4067/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4068/// Used when in C++, as a GCC extension.
4069QualType ASTContext::getUnsignedWCharType() const {
4070 // FIXME: derive from "Target" ?
4071 return UnsignedIntTy;
4072}
4073
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004074QualType ASTContext::getIntPtrType() const {
4075 return getFromTargetType(Target->getIntPtrType());
4076}
4077
4078QualType ASTContext::getUIntPtrType() const {
4079 return getCorrespondingUnsignedType(getIntPtrType());
4080}
4081
Hans Wennborg27541db2011-10-27 08:29:09 +00004082/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004083/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4084QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004085 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004086}
4087
Eli Friedman4e91899e2012-11-27 02:58:24 +00004088/// \brief Return the unique type for "pid_t" defined in
4089/// <sys/types.h>. We need this to compute the correct type for vfork().
4090QualType ASTContext::getProcessIDType() const {
4091 return getFromTargetType(Target->getProcessIDType());
4092}
4093
Chris Lattnera21ad802008-04-02 05:18:44 +00004094//===----------------------------------------------------------------------===//
4095// Type Operators
4096//===----------------------------------------------------------------------===//
4097
Jay Foad39c79802011-01-12 09:06:06 +00004098CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004099 // Push qualifiers into arrays, and then discard any remaining
4100 // qualifiers.
4101 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004102 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004103 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004104 QualType Result;
4105 if (isa<ArrayType>(Ty)) {
4106 Result = getArrayDecayedType(QualType(Ty,0));
4107 } else if (isa<FunctionType>(Ty)) {
4108 Result = getPointerType(QualType(Ty, 0));
4109 } else {
4110 Result = QualType(Ty, 0);
4111 }
4112
4113 return CanQualType::CreateUnsafe(Result);
4114}
4115
John McCall6c9dd522011-01-18 07:41:22 +00004116QualType ASTContext::getUnqualifiedArrayType(QualType type,
4117 Qualifiers &quals) {
4118 SplitQualType splitType = type.getSplitUnqualifiedType();
4119
4120 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4121 // the unqualified desugared type and then drops it on the floor.
4122 // We then have to strip that sugar back off with
4123 // getUnqualifiedDesugaredType(), which is silly.
4124 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004125 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004126
4127 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004128 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004129 quals = splitType.Quals;
4130 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004131 }
4132
John McCall6c9dd522011-01-18 07:41:22 +00004133 // Otherwise, recurse on the array's element type.
4134 QualType elementType = AT->getElementType();
4135 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4136
4137 // If that didn't change the element type, AT has no qualifiers, so we
4138 // can just use the results in splitType.
4139 if (elementType == unqualElementType) {
4140 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004141 quals = splitType.Quals;
4142 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004143 }
4144
4145 // Otherwise, add in the qualifiers from the outermost type, then
4146 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004147 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004148
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004149 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004150 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004151 CAT->getSizeModifier(), 0);
4152 }
4153
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004154 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004155 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004156 }
4157
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004158 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004159 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004160 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004161 VAT->getSizeModifier(),
4162 VAT->getIndexTypeCVRQualifiers(),
4163 VAT->getBracketsRange());
4164 }
4165
4166 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004167 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004168 DSAT->getSizeModifier(), 0,
4169 SourceRange());
4170}
4171
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004172/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4173/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4174/// they point to and return true. If T1 and T2 aren't pointer types
4175/// or pointer-to-member types, or if they are not similar at this
4176/// level, returns false and leaves T1 and T2 unchanged. Top-level
4177/// qualifiers on T1 and T2 are ignored. This function will typically
4178/// be called in a loop that successively "unwraps" pointer and
4179/// pointer-to-member types to compare them at each level.
4180bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4181 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4182 *T2PtrType = T2->getAs<PointerType>();
4183 if (T1PtrType && T2PtrType) {
4184 T1 = T1PtrType->getPointeeType();
4185 T2 = T2PtrType->getPointeeType();
4186 return true;
4187 }
4188
4189 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4190 *T2MPType = T2->getAs<MemberPointerType>();
4191 if (T1MPType && T2MPType &&
4192 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4193 QualType(T2MPType->getClass(), 0))) {
4194 T1 = T1MPType->getPointeeType();
4195 T2 = T2MPType->getPointeeType();
4196 return true;
4197 }
4198
David Blaikiebbafb8a2012-03-11 07:00:24 +00004199 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004200 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4201 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4202 if (T1OPType && T2OPType) {
4203 T1 = T1OPType->getPointeeType();
4204 T2 = T2OPType->getPointeeType();
4205 return true;
4206 }
4207 }
4208
4209 // FIXME: Block pointers, too?
4210
4211 return false;
4212}
4213
Jay Foad39c79802011-01-12 09:06:06 +00004214DeclarationNameInfo
4215ASTContext::getNameForTemplate(TemplateName Name,
4216 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004217 switch (Name.getKind()) {
4218 case TemplateName::QualifiedTemplate:
4219 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004220 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004221 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4222 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004223
John McCalld9dfe3a2011-06-30 08:33:18 +00004224 case TemplateName::OverloadedTemplate: {
4225 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4226 // DNInfo work in progress: CHECKME: what about DNLoc?
4227 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4228 }
4229
4230 case TemplateName::DependentTemplate: {
4231 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004232 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004233 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004234 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4235 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004236 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004237 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4238 // DNInfo work in progress: FIXME: source locations?
4239 DeclarationNameLoc DNLoc;
4240 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4241 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4242 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004243 }
4244 }
4245
John McCalld9dfe3a2011-06-30 08:33:18 +00004246 case TemplateName::SubstTemplateTemplateParm: {
4247 SubstTemplateTemplateParmStorage *subst
4248 = Name.getAsSubstTemplateTemplateParm();
4249 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4250 NameLoc);
4251 }
4252
4253 case TemplateName::SubstTemplateTemplateParmPack: {
4254 SubstTemplateTemplateParmPackStorage *subst
4255 = Name.getAsSubstTemplateTemplateParmPack();
4256 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4257 NameLoc);
4258 }
4259 }
4260
4261 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004262}
4263
Jay Foad39c79802011-01-12 09:06:06 +00004264TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004265 switch (Name.getKind()) {
4266 case TemplateName::QualifiedTemplate:
4267 case TemplateName::Template: {
4268 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004269 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004270 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004271 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4272
4273 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004274 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004275 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004276
John McCalld9dfe3a2011-06-30 08:33:18 +00004277 case TemplateName::OverloadedTemplate:
4278 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004279
John McCalld9dfe3a2011-06-30 08:33:18 +00004280 case TemplateName::DependentTemplate: {
4281 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4282 assert(DTN && "Non-dependent template names must refer to template decls.");
4283 return DTN->CanonicalTemplateName;
4284 }
4285
4286 case TemplateName::SubstTemplateTemplateParm: {
4287 SubstTemplateTemplateParmStorage *subst
4288 = Name.getAsSubstTemplateTemplateParm();
4289 return getCanonicalTemplateName(subst->getReplacement());
4290 }
4291
4292 case TemplateName::SubstTemplateTemplateParmPack: {
4293 SubstTemplateTemplateParmPackStorage *subst
4294 = Name.getAsSubstTemplateTemplateParmPack();
4295 TemplateTemplateParmDecl *canonParameter
4296 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4297 TemplateArgument canonArgPack
4298 = getCanonicalTemplateArgument(subst->getArgumentPack());
4299 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4300 }
4301 }
4302
4303 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004304}
4305
Douglas Gregoradee3e32009-11-11 23:06:43 +00004306bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4307 X = getCanonicalTemplateName(X);
4308 Y = getCanonicalTemplateName(Y);
4309 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4310}
4311
Mike Stump11289f42009-09-09 15:08:12 +00004312TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004313ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004314 switch (Arg.getKind()) {
4315 case TemplateArgument::Null:
4316 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004317
Douglas Gregora8e02e72009-07-28 23:00:59 +00004318 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004319 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004320
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004321 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004322 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004323 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004324 }
Mike Stump11289f42009-09-09 15:08:12 +00004325
Eli Friedmanb826a002012-09-26 02:36:12 +00004326 case TemplateArgument::NullPtr:
4327 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4328 /*isNullPtr*/true);
4329
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004330 case TemplateArgument::Template:
4331 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004332
4333 case TemplateArgument::TemplateExpansion:
4334 return TemplateArgument(getCanonicalTemplateName(
4335 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004336 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004337
Douglas Gregora8e02e72009-07-28 23:00:59 +00004338 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004339 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004340
Douglas Gregora8e02e72009-07-28 23:00:59 +00004341 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004342 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004343
Douglas Gregora8e02e72009-07-28 23:00:59 +00004344 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004345 if (Arg.pack_size() == 0)
4346 return Arg;
4347
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004348 TemplateArgument *CanonArgs
4349 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004350 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004351 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004352 AEnd = Arg.pack_end();
4353 A != AEnd; (void)++A, ++Idx)
4354 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004355
Benjamin Kramercce63472015-08-05 09:40:22 +00004356 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004357 }
4358 }
4359
4360 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004361 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004362}
4363
Douglas Gregor333489b2009-03-27 23:10:48 +00004364NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004365ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004366 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004367 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004368
4369 switch (NNS->getKind()) {
4370 case NestedNameSpecifier::Identifier:
4371 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004372 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004373 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4374 NNS->getAsIdentifier());
4375
4376 case NestedNameSpecifier::Namespace:
4377 // A namespace is canonical; build a nested-name-specifier with
4378 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004379 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004380 NNS->getAsNamespace()->getOriginalNamespace());
4381
4382 case NestedNameSpecifier::NamespaceAlias:
4383 // A namespace is canonical; build a nested-name-specifier with
4384 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004385 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004386 NNS->getAsNamespaceAlias()->getNamespace()
4387 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004388
4389 case NestedNameSpecifier::TypeSpec:
4390 case NestedNameSpecifier::TypeSpecWithTemplate: {
4391 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004392
4393 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4394 // break it apart into its prefix and identifier, then reconsititute those
4395 // as the canonical nested-name-specifier. This is required to canonicalize
4396 // a dependent nested-name-specifier involving typedefs of dependent-name
4397 // types, e.g.,
4398 // typedef typename T::type T1;
4399 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004400 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4401 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004402 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004403
Eli Friedman5358a0a2012-03-03 04:09:56 +00004404 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4405 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4406 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004407 return NestedNameSpecifier::Create(*this, nullptr, false,
4408 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004409 }
4410
4411 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004412 case NestedNameSpecifier::Super:
4413 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004414 return NNS;
4415 }
4416
David Blaikie8a40f702012-01-17 06:56:22 +00004417 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004418}
4419
Chris Lattner7adf0762008-08-04 07:31:14 +00004420
Jay Foad39c79802011-01-12 09:06:06 +00004421const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004422 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004423 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004424 // Handle the common positive case fast.
4425 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4426 return AT;
4427 }
Mike Stump11289f42009-09-09 15:08:12 +00004428
John McCall8ccfcb52009-09-24 19:53:00 +00004429 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004430 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004431 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004432
John McCall8ccfcb52009-09-24 19:53:00 +00004433 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004434 // implements C99 6.7.3p8: "If the specification of an array type includes
4435 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004436
Chris Lattner7adf0762008-08-04 07:31:14 +00004437 // If we get here, we either have type qualifiers on the type, or we have
4438 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004439 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004440
John McCall33ddac02011-01-19 10:06:00 +00004441 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004442 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004443
Chris Lattner7adf0762008-08-04 07:31:14 +00004444 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004445 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004446 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004447 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004448
Chris Lattner7adf0762008-08-04 07:31:14 +00004449 // Otherwise, we have an array and we have qualifiers on it. Push the
4450 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004451 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004452
Chris Lattner7adf0762008-08-04 07:31:14 +00004453 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4454 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4455 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004456 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004457 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4458 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4459 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004460 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004461
Mike Stump11289f42009-09-09 15:08:12 +00004462 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004463 = dyn_cast<DependentSizedArrayType>(ATy))
4464 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004465 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004466 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004467 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004468 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004469 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004470
Chris Lattner7adf0762008-08-04 07:31:14 +00004471 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004472 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004473 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004474 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004475 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004476 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004477}
4478
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004479QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004480 if (T->isArrayType() || T->isFunctionType())
4481 return getDecayedType(T);
4482 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004483}
4484
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004485QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004486 T = getVariableArrayDecayedType(T);
4487 T = getAdjustedParameterType(T);
4488 return T.getUnqualifiedType();
4489}
4490
David Majnemerd09a51c2015-03-03 01:50:05 +00004491QualType ASTContext::getExceptionObjectType(QualType T) const {
4492 // C++ [except.throw]p3:
4493 // A throw-expression initializes a temporary object, called the exception
4494 // object, the type of which is determined by removing any top-level
4495 // cv-qualifiers from the static type of the operand of throw and adjusting
4496 // the type from "array of T" or "function returning T" to "pointer to T"
4497 // or "pointer to function returning T", [...]
4498 T = getVariableArrayDecayedType(T);
4499 if (T->isArrayType() || T->isFunctionType())
4500 T = getDecayedType(T);
4501 return T.getUnqualifiedType();
4502}
4503
Chris Lattnera21ad802008-04-02 05:18:44 +00004504/// getArrayDecayedType - Return the properly qualified result of decaying the
4505/// specified array type to a pointer. This operation is non-trivial when
4506/// handling typedefs etc. The canonical type of "T" must be an array type,
4507/// this returns a pointer to a properly qualified element of the array.
4508///
4509/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004510QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004511 // Get the element type with 'getAsArrayType' so that we don't lose any
4512 // typedefs in the element type of the array. This also handles propagation
4513 // of type qualifiers from the array type into the element type if present
4514 // (C99 6.7.3p8).
4515 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4516 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004517
Chris Lattner7adf0762008-08-04 07:31:14 +00004518 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004519
4520 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004521 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004522}
4523
John McCall33ddac02011-01-19 10:06:00 +00004524QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4525 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004526}
4527
John McCall33ddac02011-01-19 10:06:00 +00004528QualType ASTContext::getBaseElementType(QualType type) const {
4529 Qualifiers qs;
4530 while (true) {
4531 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004532 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004533 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004534
John McCall33ddac02011-01-19 10:06:00 +00004535 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004536 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538
John McCall33ddac02011-01-19 10:06:00 +00004539 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004540}
4541
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004542/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004543uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004544ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4545 uint64_t ElementCount = 1;
4546 do {
4547 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004548 CA = dyn_cast_or_null<ConstantArrayType>(
4549 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004550 } while (CA);
4551 return ElementCount;
4552}
4553
Steve Naroff0af91202007-04-27 21:51:21 +00004554/// getFloatingRank - Return a relative rank for floating point types.
4555/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004556static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004557 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004558 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004559
John McCall9dd450b2009-09-21 23:43:11 +00004560 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4561 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004562 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004563 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004564 case BuiltinType::Float: return FloatRank;
4565 case BuiltinType::Double: return DoubleRank;
4566 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004567 }
4568}
4569
Mike Stump11289f42009-09-09 15:08:12 +00004570/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4571/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004572/// 'typeDomain' is a real floating point or complex type.
4573/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004574QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4575 QualType Domain) const {
4576 FloatingRank EltRank = getFloatingRank(Size);
4577 if (Domain->isComplexType()) {
4578 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004579 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004580 case FloatRank: return FloatComplexTy;
4581 case DoubleRank: return DoubleComplexTy;
4582 case LongDoubleRank: return LongDoubleComplexTy;
4583 }
Steve Naroff0af91202007-04-27 21:51:21 +00004584 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004585
4586 assert(Domain->isRealFloatingType() && "Unknown domain!");
4587 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004588 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004589 case FloatRank: return FloatTy;
4590 case DoubleRank: return DoubleTy;
4591 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004592 }
David Blaikief47fa302012-01-17 02:30:50 +00004593 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004594}
4595
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004596/// getFloatingTypeOrder - Compare the rank of the two specified floating
4597/// point types, ignoring the domain of the type (i.e. 'double' ==
4598/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004599/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004600int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004601 FloatingRank LHSR = getFloatingRank(LHS);
4602 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004603
Chris Lattnerb90739d2008-04-06 23:38:49 +00004604 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004605 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004606 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004607 return 1;
4608 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004609}
4610
Chris Lattner76a00cf2008-04-06 22:59:24 +00004611/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4612/// routine will assert if passed a built-in type that isn't an integer or enum,
4613/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004614unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004615 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004616
Chris Lattner76a00cf2008-04-06 22:59:24 +00004617 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004618 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004619 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004620 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004621 case BuiltinType::Char_S:
4622 case BuiltinType::Char_U:
4623 case BuiltinType::SChar:
4624 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004625 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004626 case BuiltinType::Short:
4627 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004628 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004629 case BuiltinType::Int:
4630 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004631 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004632 case BuiltinType::Long:
4633 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004634 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004635 case BuiltinType::LongLong:
4636 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004637 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004638 case BuiltinType::Int128:
4639 case BuiltinType::UInt128:
4640 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004641 }
4642}
4643
Eli Friedman629ffb92009-08-20 04:21:42 +00004644/// \brief Whether this is a promotable bitfield reference according
4645/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4646///
4647/// \returns the type this bit-field will promote to, or NULL if no
4648/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004649QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004650 if (E->isTypeDependent() || E->isValueDependent())
4651 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004652
4653 // FIXME: We should not do this unless E->refersToBitField() is true. This
4654 // matters in C where getSourceBitField() will find bit-fields for various
4655 // cases where the source expression is not a bit-field designator.
4656
John McCalld25db7e2013-05-06 21:39:12 +00004657 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004658 if (!Field)
4659 return QualType();
4660
4661 QualType FT = Field->getType();
4662
Richard Smithcaf33902011-10-10 18:28:20 +00004663 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004664 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004665 // C++ [conv.prom]p5:
4666 // A prvalue for an integral bit-field can be converted to a prvalue of type
4667 // int if int can represent all the values of the bit-field; otherwise, it
4668 // can be converted to unsigned int if unsigned int can represent all the
4669 // values of the bit-field. If the bit-field is larger yet, no integral
4670 // promotion applies to it.
4671 // C11 6.3.1.1/2:
4672 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4673 // If an int can represent all values of the original type (as restricted by
4674 // the width, for a bit-field), the value is converted to an int; otherwise,
4675 // it is converted to an unsigned int.
4676 //
4677 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4678 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004679 if (BitWidth < IntSize)
4680 return IntTy;
4681
4682 if (BitWidth == IntSize)
4683 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4684
4685 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004686 // like the base type. GCC has some weird bugs in this area that we
4687 // deliberately do not follow (GCC follows a pre-standard resolution to
4688 // C's DR315 which treats bit-width as being part of the type, and this leaks
4689 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004690 return QualType();
4691}
4692
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004693/// getPromotedIntegerType - Returns the type that Promotable will
4694/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4695/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004696QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004697 assert(!Promotable.isNull());
4698 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004699 if (const EnumType *ET = Promotable->getAs<EnumType>())
4700 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004701
4702 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4703 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4704 // (3.9.1) can be converted to a prvalue of the first of the following
4705 // types that can represent all the values of its underlying type:
4706 // int, unsigned int, long int, unsigned long int, long long int, or
4707 // unsigned long long int [...]
4708 // FIXME: Is there some better way to compute this?
4709 if (BT->getKind() == BuiltinType::WChar_S ||
4710 BT->getKind() == BuiltinType::WChar_U ||
4711 BT->getKind() == BuiltinType::Char16 ||
4712 BT->getKind() == BuiltinType::Char32) {
4713 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4714 uint64_t FromSize = getTypeSize(BT);
4715 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4716 LongLongTy, UnsignedLongLongTy };
4717 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4718 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4719 if (FromSize < ToSize ||
4720 (FromSize == ToSize &&
4721 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4722 return PromoteTypes[Idx];
4723 }
4724 llvm_unreachable("char type should fit into long long");
4725 }
4726 }
4727
4728 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004729 if (Promotable->isSignedIntegerType())
4730 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004731 uint64_t PromotableSize = getIntWidth(Promotable);
4732 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004733 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4734 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4735}
4736
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004737/// \brief Recurses in pointer/array types until it finds an objc retainable
4738/// type and returns its ownership.
4739Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4740 while (!T.isNull()) {
4741 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4742 return T.getObjCLifetime();
4743 if (T->isArrayType())
4744 T = getBaseElementType(T);
4745 else if (const PointerType *PT = T->getAs<PointerType>())
4746 T = PT->getPointeeType();
4747 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004748 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004749 else
4750 break;
4751 }
4752
4753 return Qualifiers::OCL_None;
4754}
4755
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004756static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4757 // Incomplete enum types are not treated as integer types.
4758 // FIXME: In C++, enum types are never integer types.
4759 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4760 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004761 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004762}
4763
Mike Stump11289f42009-09-09 15:08:12 +00004764/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004765/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004766/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004767int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004768 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4769 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004770
4771 // Unwrap enums to their underlying type.
4772 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4773 LHSC = getIntegerTypeForEnum(ET);
4774 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4775 RHSC = getIntegerTypeForEnum(ET);
4776
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004777 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004778
Chris Lattner76a00cf2008-04-06 22:59:24 +00004779 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4780 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004781
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004782 unsigned LHSRank = getIntegerRank(LHSC);
4783 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004784
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004785 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4786 if (LHSRank == RHSRank) return 0;
4787 return LHSRank > RHSRank ? 1 : -1;
4788 }
Mike Stump11289f42009-09-09 15:08:12 +00004789
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004790 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4791 if (LHSUnsigned) {
4792 // If the unsigned [LHS] type is larger, return it.
4793 if (LHSRank >= RHSRank)
4794 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004795
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004796 // If the signed type can represent all values of the unsigned type, it
4797 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004798 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004799 return -1;
4800 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004801
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004802 // If the unsigned [RHS] type is larger, return it.
4803 if (RHSRank >= LHSRank)
4804 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004805
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004806 // If the signed type can represent all values of the unsigned type, it
4807 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004808 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004809 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004810}
Anders Carlsson98f07902007-08-17 05:31:46 +00004811
Mike Stump11289f42009-09-09 15:08:12 +00004812// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004813QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004814 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004815 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004816 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004817
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004818 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004819
Anders Carlsson98f07902007-08-17 05:31:46 +00004820 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004821 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004822 // int flags;
4823 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004824 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004825 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004826 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004827 FieldTypes[3] = LongTy;
4828
Anders Carlsson98f07902007-08-17 05:31:46 +00004829 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004830 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004831 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004832 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004833 SourceLocation(), nullptr,
4834 FieldTypes[i], /*TInfo=*/nullptr,
4835 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004836 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004837 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004838 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004839 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004840 }
4841
Douglas Gregord5058122010-02-11 01:19:42 +00004842 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004843 }
Mike Stump11289f42009-09-09 15:08:12 +00004844
Anders Carlsson98f07902007-08-17 05:31:46 +00004845 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004846}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004847
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004848QualType ASTContext::getObjCSuperType() const {
4849 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004850 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004851 TUDecl->addDecl(ObjCSuperTypeDecl);
4852 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4853 }
4854 return ObjCSuperType;
4855}
4856
Douglas Gregor512b0772009-04-23 22:29:11 +00004857void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004858 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004859 assert(Rec && "Invalid CFConstantStringType");
4860 CFConstantStringTypeDecl = Rec->getDecl();
4861}
4862
Jay Foad39c79802011-01-12 09:06:06 +00004863QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004864 if (BlockDescriptorType)
4865 return getTagDeclType(BlockDescriptorType);
4866
Alp Toker2dea15b2013-12-17 01:22:38 +00004867 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004868 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004869 RD = buildImplicitRecord("__block_descriptor");
4870 RD->startDefinition();
4871
Mike Stumpd0153282009-10-20 02:12:22 +00004872 QualType FieldTypes[] = {
4873 UnsignedLongTy,
4874 UnsignedLongTy,
4875 };
4876
Craig Topperd6d31ac2013-07-15 08:24:27 +00004877 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004878 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004879 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004880 };
4881
4882 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004883 FieldDecl *Field = FieldDecl::Create(
4884 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004885 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4886 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004887 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004888 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004889 }
4890
Alp Toker2dea15b2013-12-17 01:22:38 +00004891 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004892
Alp Toker2dea15b2013-12-17 01:22:38 +00004893 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004894
4895 return getTagDeclType(BlockDescriptorType);
4896}
4897
Jay Foad39c79802011-01-12 09:06:06 +00004898QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004899 if (BlockDescriptorExtendedType)
4900 return getTagDeclType(BlockDescriptorExtendedType);
4901
Alp Toker2dea15b2013-12-17 01:22:38 +00004902 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004903 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004904 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4905 RD->startDefinition();
4906
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004907 QualType FieldTypes[] = {
4908 UnsignedLongTy,
4909 UnsignedLongTy,
4910 getPointerType(VoidPtrTy),
4911 getPointerType(VoidPtrTy)
4912 };
4913
Craig Topperd6d31ac2013-07-15 08:24:27 +00004914 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004915 "reserved",
4916 "Size",
4917 "CopyFuncPtr",
4918 "DestroyFuncPtr"
4919 };
4920
4921 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004922 FieldDecl *Field = FieldDecl::Create(
4923 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004924 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4925 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004926 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004927 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004928 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004929 }
4930
Alp Toker2dea15b2013-12-17 01:22:38 +00004931 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004932
Alp Toker2dea15b2013-12-17 01:22:38 +00004933 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004934 return getTagDeclType(BlockDescriptorExtendedType);
4935}
4936
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004937/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4938/// requires copy/dispose. Note that this must match the logic
4939/// in buildByrefHelpers.
4940bool ASTContext::BlockRequiresCopying(QualType Ty,
4941 const VarDecl *D) {
4942 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4943 const Expr *copyExpr = getBlockVarCopyInits(D);
4944 if (!copyExpr && record->hasTrivialDestructor()) return false;
4945
Mike Stump94967902009-10-21 18:16:27 +00004946 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004947 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004948
4949 if (!Ty->isObjCRetainableType()) return false;
4950
4951 Qualifiers qs = Ty.getQualifiers();
4952
4953 // If we have lifetime, that dominates.
4954 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4955 assert(getLangOpts().ObjCAutoRefCount);
4956
4957 switch (lifetime) {
4958 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4959
4960 // These are just bits as far as the runtime is concerned.
4961 case Qualifiers::OCL_ExplicitNone:
4962 case Qualifiers::OCL_Autoreleasing:
4963 return false;
4964
4965 // Tell the runtime that this is ARC __weak, called by the
4966 // byref routines.
4967 case Qualifiers::OCL_Weak:
4968 // ARC __strong __block variables need to be retained.
4969 case Qualifiers::OCL_Strong:
4970 return true;
4971 }
4972 llvm_unreachable("fell out of lifetime switch!");
4973 }
4974 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4975 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004976}
4977
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004978bool ASTContext::getByrefLifetime(QualType Ty,
4979 Qualifiers::ObjCLifetime &LifeTime,
4980 bool &HasByrefExtendedLayout) const {
4981
4982 if (!getLangOpts().ObjC1 ||
4983 getLangOpts().getGC() != LangOptions::NonGC)
4984 return false;
4985
4986 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004987 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004988 HasByrefExtendedLayout = true;
4989 LifeTime = Qualifiers::OCL_None;
4990 }
4991 else if (getLangOpts().ObjCAutoRefCount)
4992 LifeTime = Ty.getObjCLifetime();
4993 // MRR.
4994 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4995 LifeTime = Qualifiers::OCL_ExplicitNone;
4996 else
4997 LifeTime = Qualifiers::OCL_None;
4998 return true;
4999}
5000
Douglas Gregorbab8a962011-09-08 01:46:34 +00005001TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5002 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005003 ObjCInstanceTypeDecl =
5004 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005005 return ObjCInstanceTypeDecl;
5006}
5007
Anders Carlsson18acd442007-10-29 06:33:42 +00005008// This returns true if a type has been typedefed to BOOL:
5009// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005010static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005011 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005012 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5013 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005014
Anders Carlssond8499822007-10-29 05:01:08 +00005015 return false;
5016}
5017
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005018/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005019/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005020CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005021 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5022 return CharUnits::Zero();
5023
Ken Dyck40775002010-01-11 17:06:35 +00005024 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005025
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005026 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005027 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005028 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005029 // Treat arrays as pointers, since that's how they're passed in.
5030 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005031 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005032 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005033}
5034
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005035bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005036 return getTargetInfo().getCXXABI().isMicrosoft() &&
5037 VD->isStaticDataMember() &&
5038 VD->getType()->isIntegralOrEnumerationType() && VD->isFirstDecl() &&
5039 !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005040}
5041
Ken Dyck40775002010-01-11 17:06:35 +00005042static inline
5043std::string charUnitsToString(const CharUnits &CU) {
5044 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005045}
5046
John McCall351762c2011-02-07 10:33:21 +00005047/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005048/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005049std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5050 std::string S;
5051
David Chisnall950a9512009-11-17 19:33:30 +00005052 const BlockDecl *Decl = Expr->getBlockDecl();
5053 QualType BlockTy =
5054 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5055 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005056 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005057 getObjCEncodingForMethodParameter(
5058 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5059 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005060 else
Alp Toker314cc812014-01-25 16:55:45 +00005061 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005062 // Compute size of all parameters.
5063 // Start with computing size of a pointer in number of bytes.
5064 // FIXME: There might(should) be a better way of doing this computation!
5065 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005066 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5067 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005068 for (auto PI : Decl->params()) {
5069 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005070 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005071 if (sz.isZero())
5072 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005073 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005074 ParmOffset += sz;
5075 }
5076 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005077 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005078 // Block pointer and offset.
5079 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005080
5081 // Argument types.
5082 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005083 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005084 QualType PType = PVDecl->getOriginalType();
5085 if (const ArrayType *AT =
5086 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5087 // Use array's original type only if it has known number of
5088 // elements.
5089 if (!isa<ConstantArrayType>(AT))
5090 PType = PVDecl->getType();
5091 } else if (PType->isFunctionType())
5092 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005093 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005094 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5095 S, true /*Extended*/);
5096 else
5097 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005098 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005099 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005100 }
John McCall351762c2011-02-07 10:33:21 +00005101
5102 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005103}
5104
Douglas Gregora9d84932011-05-27 01:19:52 +00005105bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005106 std::string& S) {
5107 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005108 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005109 CharUnits ParmOffset;
5110 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005111 for (auto PI : Decl->params()) {
5112 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005113 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005114 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005115 continue;
5116
David Chisnall50e4eba2010-12-30 14:05:53 +00005117 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005118 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005119 ParmOffset += sz;
5120 }
5121 S += charUnitsToString(ParmOffset);
5122 ParmOffset = CharUnits::Zero();
5123
5124 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005125 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005126 QualType PType = PVDecl->getOriginalType();
5127 if (const ArrayType *AT =
5128 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5129 // Use array's original type only if it has known number of
5130 // elements.
5131 if (!isa<ConstantArrayType>(AT))
5132 PType = PVDecl->getType();
5133 } else if (PType->isFunctionType())
5134 PType = PVDecl->getType();
5135 getObjCEncodingForType(PType, S);
5136 S += charUnitsToString(ParmOffset);
5137 ParmOffset += getObjCEncodingTypeSize(PType);
5138 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005139
5140 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005141}
5142
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005143/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5144/// method parameter or return type. If Extended, include class names and
5145/// block object types.
5146void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5147 QualType T, std::string& S,
5148 bool Extended) const {
5149 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5150 getObjCEncodingForTypeQualifier(QT, S);
5151 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005152 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005153 true /*OutermostType*/,
5154 false /*EncodingProperty*/,
5155 false /*StructField*/,
5156 Extended /*EncodeBlockParameters*/,
5157 Extended /*EncodeClassNames*/);
5158}
5159
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005160/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005161/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005162bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005163 std::string& S,
5164 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005165 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005166 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005167 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5168 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005169 // Compute size of all parameters.
5170 // Start with computing size of a pointer in number of bytes.
5171 // FIXME: There might(should) be a better way of doing this computation!
5172 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005173 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005174 // The first two arguments (self and _cmd) are pointers; account for
5175 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005176 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005177 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005178 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005179 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005180 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005181 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005182 continue;
5183
Ken Dyck40775002010-01-11 17:06:35 +00005184 assert (sz.isPositive() &&
5185 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005186 ParmOffset += sz;
5187 }
Ken Dyck40775002010-01-11 17:06:35 +00005188 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005189 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005190 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005191
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005192 // Argument types.
5193 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005194 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005195 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005196 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005197 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005198 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005199 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5200 // Use array's original type only if it has known number of
5201 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005202 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005203 PType = PVDecl->getType();
5204 } else if (PType->isFunctionType())
5205 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005206 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5207 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005208 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005209 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005210 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005211
5212 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005213}
5214
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005215ObjCPropertyImplDecl *
5216ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5217 const ObjCPropertyDecl *PD,
5218 const Decl *Container) const {
5219 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005220 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005221 if (const ObjCCategoryImplDecl *CID =
5222 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005223 for (auto *PID : CID->property_impls())
5224 if (PID->getPropertyDecl() == PD)
5225 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005226 } else {
5227 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5228 for (auto *PID : OID->property_impls())
5229 if (PID->getPropertyDecl() == PD)
5230 return PID;
5231 }
5232 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005233}
5234
Daniel Dunbar4932b362008-08-28 04:38:10 +00005235/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005236/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005237/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5238/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005239/// Property attributes are stored as a comma-delimited C string. The simple
5240/// attributes readonly and bycopy are encoded as single characters. The
5241/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5242/// encoded as single characters, followed by an identifier. Property types
5243/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005244/// these attributes are defined by the following enumeration:
5245/// @code
5246/// enum PropertyAttributes {
5247/// kPropertyReadOnly = 'R', // property is read-only.
5248/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5249/// kPropertyByref = '&', // property is a reference to the value last assigned
5250/// kPropertyDynamic = 'D', // property is dynamic
5251/// kPropertyGetter = 'G', // followed by getter selector name
5252/// kPropertySetter = 'S', // followed by setter selector name
5253/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005254/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005255/// kPropertyWeak = 'W' // 'weak' property
5256/// kPropertyStrong = 'P' // property GC'able
5257/// kPropertyNonAtomic = 'N' // property non-atomic
5258/// };
5259/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005260void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005261 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005262 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005263 // Collect information from the property implementation decl(s).
5264 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005265 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005266
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005267 if (ObjCPropertyImplDecl *PropertyImpDecl =
5268 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5269 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5270 Dynamic = true;
5271 else
5272 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005273 }
5274
5275 // FIXME: This is not very efficient.
5276 S = "T";
5277
5278 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005279 // GCC has some special rules regarding encoding of properties which
5280 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005281 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005282
5283 if (PD->isReadOnly()) {
5284 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005285 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5286 S += ",C";
5287 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5288 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005289 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5290 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005291 } else {
5292 switch (PD->getSetterKind()) {
5293 case ObjCPropertyDecl::Assign: break;
5294 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005295 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005296 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005297 }
5298 }
5299
5300 // It really isn't clear at all what this means, since properties
5301 // are "dynamic by default".
5302 if (Dynamic)
5303 S += ",D";
5304
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005305 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5306 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005307
Daniel Dunbar4932b362008-08-28 04:38:10 +00005308 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5309 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005310 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005311 }
5312
5313 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5314 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005315 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005316 }
5317
5318 if (SynthesizePID) {
5319 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5320 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005321 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005322 }
5323
5324 // FIXME: OBJCGC: weak & strong
5325}
5326
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005327/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005328/// Another legacy compatibility encoding: 32-bit longs are encoded as
5329/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005330/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5331///
5332void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005333 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005334 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005335 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005336 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005337 else
Jay Foad39c79802011-01-12 09:06:06 +00005338 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005339 PointeeTy = IntTy;
5340 }
5341 }
5342}
5343
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005344void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005345 const FieldDecl *Field,
5346 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005347 // We follow the behavior of gcc, expanding structures which are
5348 // directly pointed to, and expanding embedded structures. Note that
5349 // these rules are sufficient to prevent recursive encoding of the
5350 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005351 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005352 true /* outermost type */, false, false,
5353 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005354}
5355
Joe Groff98ac7d22014-07-07 22:25:15 +00005356void ASTContext::getObjCEncodingForPropertyType(QualType T,
5357 std::string& S) const {
5358 // Encode result type.
5359 // GCC has some special rules regarding encoding of properties which
5360 // closely resembles encoding of ivars.
5361 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5362 true /* outermost type */,
5363 true /* encoding property */);
5364}
5365
John McCall393a78d2012-12-20 02:45:14 +00005366static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5367 BuiltinType::Kind kind) {
5368 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005369 case BuiltinType::Void: return 'v';
5370 case BuiltinType::Bool: return 'B';
5371 case BuiltinType::Char_U:
5372 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005373 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005374 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005375 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005376 case BuiltinType::UInt: return 'I';
5377 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005378 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005379 case BuiltinType::UInt128: return 'T';
5380 case BuiltinType::ULongLong: return 'Q';
5381 case BuiltinType::Char_S:
5382 case BuiltinType::SChar: return 'c';
5383 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005384 case BuiltinType::WChar_S:
5385 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005386 case BuiltinType::Int: return 'i';
5387 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005388 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005389 case BuiltinType::LongLong: return 'q';
5390 case BuiltinType::Int128: return 't';
5391 case BuiltinType::Float: return 'f';
5392 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005393 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005394 case BuiltinType::NullPtr: return '*'; // like char*
5395
5396 case BuiltinType::Half:
5397 // FIXME: potentially need @encodes for these!
5398 return ' ';
5399
5400 case BuiltinType::ObjCId:
5401 case BuiltinType::ObjCClass:
5402 case BuiltinType::ObjCSel:
5403 llvm_unreachable("@encoding ObjC primitive type");
5404
5405 // OpenCL and placeholder types don't need @encodings.
5406 case BuiltinType::OCLImage1d:
5407 case BuiltinType::OCLImage1dArray:
5408 case BuiltinType::OCLImage1dBuffer:
5409 case BuiltinType::OCLImage2d:
5410 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005411 case BuiltinType::OCLImage2dDepth:
5412 case BuiltinType::OCLImage2dArrayDepth:
5413 case BuiltinType::OCLImage2dMSAA:
5414 case BuiltinType::OCLImage2dArrayMSAA:
5415 case BuiltinType::OCLImage2dMSAADepth:
5416 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005417 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005418 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005419 case BuiltinType::OCLClkEvent:
5420 case BuiltinType::OCLQueue:
5421 case BuiltinType::OCLNDRange:
5422 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005423 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005424 case BuiltinType::Dependent:
5425#define BUILTIN_TYPE(KIND, ID)
5426#define PLACEHOLDER_TYPE(KIND, ID) \
5427 case BuiltinType::KIND:
5428#include "clang/AST/BuiltinTypes.def"
5429 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005430 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005431 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005432}
5433
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005434static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5435 EnumDecl *Enum = ET->getDecl();
5436
5437 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5438 if (!Enum->isFixed())
5439 return 'i';
5440
5441 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005442 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5443 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005444}
5445
Jay Foad39c79802011-01-12 09:06:06 +00005446static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005447 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005448 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005449 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005450 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5451 // The GNU runtime requires more information; bitfields are encoded as b,
5452 // then the offset (in bits) of the first element, then the type of the
5453 // bitfield, then the size in bits. For example, in this structure:
5454 //
5455 // struct
5456 // {
5457 // int integer;
5458 // int flags:2;
5459 // };
5460 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5461 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5462 // information is not especially sensible, but we're stuck with it for
5463 // compatibility with GCC, although providing it breaks anything that
5464 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005465 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005466 const RecordDecl *RD = FD->getParent();
5467 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005468 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005469 if (const EnumType *ET = T->getAs<EnumType>())
5470 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005471 else {
5472 const BuiltinType *BT = T->castAs<BuiltinType>();
5473 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5474 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005475 }
Richard Smithcaf33902011-10-10 18:28:20 +00005476 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005477}
5478
Daniel Dunbar07d07852009-10-18 21:17:35 +00005479// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005480void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5481 bool ExpandPointedToStructures,
5482 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005483 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005484 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005485 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005486 bool StructField,
5487 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005488 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005489 bool EncodePointerToObjCTypedef,
5490 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005491 CanQualType CT = getCanonicalType(T);
5492 switch (CT->getTypeClass()) {
5493 case Type::Builtin:
5494 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005495 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005496 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005497 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5498 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5499 else
5500 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005501 return;
Mike Stump11289f42009-09-09 15:08:12 +00005502
John McCall393a78d2012-12-20 02:45:14 +00005503 case Type::Complex: {
5504 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005505 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005506 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005507 return;
5508 }
John McCall393a78d2012-12-20 02:45:14 +00005509
5510 case Type::Atomic: {
5511 const AtomicType *AT = T->castAs<AtomicType>();
5512 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005513 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005514 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005515 }
John McCall393a78d2012-12-20 02:45:14 +00005516
5517 // encoding for pointer or reference types.
5518 case Type::Pointer:
5519 case Type::LValueReference:
5520 case Type::RValueReference: {
5521 QualType PointeeTy;
5522 if (isa<PointerType>(CT)) {
5523 const PointerType *PT = T->castAs<PointerType>();
5524 if (PT->isObjCSelType()) {
5525 S += ':';
5526 return;
5527 }
5528 PointeeTy = PT->getPointeeType();
5529 } else {
5530 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5531 }
5532
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005533 bool isReadOnly = false;
5534 // For historical/compatibility reasons, the read-only qualifier of the
5535 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5536 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005537 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005538 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005539 if (OutermostType && T.isConstQualified()) {
5540 isReadOnly = true;
5541 S += 'r';
5542 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005543 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005544 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005545 while (P->getAs<PointerType>())
5546 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005547 if (P.isConstQualified()) {
5548 isReadOnly = true;
5549 S += 'r';
5550 }
5551 }
5552 if (isReadOnly) {
5553 // Another legacy compatibility encoding. Some ObjC qualifier and type
5554 // combinations need to be rearranged.
5555 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005556 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005557 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005558 }
Mike Stump11289f42009-09-09 15:08:12 +00005559
Anders Carlssond8499822007-10-29 05:01:08 +00005560 if (PointeeTy->isCharType()) {
5561 // char pointer types should be encoded as '*' unless it is a
5562 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005563 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005564 S += '*';
5565 return;
5566 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005567 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005568 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5569 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5570 S += '#';
5571 return;
5572 }
5573 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5574 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5575 S += '@';
5576 return;
5577 }
5578 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005579 }
Anders Carlssond8499822007-10-29 05:01:08 +00005580 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005581 getLegacyIntegralTypeEncoding(PointeeTy);
5582
Mike Stump11289f42009-09-09 15:08:12 +00005583 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005584 nullptr, false, false, false, false, false, false,
5585 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005586 return;
5587 }
John McCall393a78d2012-12-20 02:45:14 +00005588
5589 case Type::ConstantArray:
5590 case Type::IncompleteArray:
5591 case Type::VariableArray: {
5592 const ArrayType *AT = cast<ArrayType>(CT);
5593
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005594 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005595 // Incomplete arrays are encoded as a pointer to the array element.
5596 S += '^';
5597
Mike Stump11289f42009-09-09 15:08:12 +00005598 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005599 false, ExpandStructures, FD);
5600 } else {
5601 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005602
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005603 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5604 S += llvm::utostr(CAT->getSize().getZExtValue());
5605 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005606 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005607 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5608 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005609 S += '0';
5610 }
Mike Stump11289f42009-09-09 15:08:12 +00005611
5612 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005613 false, ExpandStructures, FD,
5614 false, false, false, false, false, false,
5615 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005616 S += ']';
5617 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005618 return;
5619 }
Mike Stump11289f42009-09-09 15:08:12 +00005620
John McCall393a78d2012-12-20 02:45:14 +00005621 case Type::FunctionNoProto:
5622 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005623 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005624 return;
Mike Stump11289f42009-09-09 15:08:12 +00005625
John McCall393a78d2012-12-20 02:45:14 +00005626 case Type::Record: {
5627 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005628 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005629 // Anonymous structures print as '?'
5630 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5631 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005632 if (ClassTemplateSpecializationDecl *Spec
5633 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5634 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005635 llvm::raw_string_ostream OS(S);
5636 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005637 TemplateArgs.data(),
5638 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005639 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005640 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005641 } else {
5642 S += '?';
5643 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005644 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005645 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005646 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005647 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005648 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005649 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005650 if (FD) {
5651 S += '"';
5652 S += Field->getNameAsString();
5653 S += '"';
5654 }
Mike Stump11289f42009-09-09 15:08:12 +00005655
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005656 // Special case bit-fields.
5657 if (Field->isBitField()) {
5658 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005659 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005660 } else {
5661 QualType qt = Field->getType();
5662 getLegacyIntegralTypeEncoding(qt);
5663 getObjCEncodingForTypeImpl(qt, S, false, true,
5664 FD, /*OutermostType*/false,
5665 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005666 /*StructField*/true,
5667 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005668 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005669 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005670 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005671 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005672 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005673 return;
5674 }
Mike Stump11289f42009-09-09 15:08:12 +00005675
John McCall393a78d2012-12-20 02:45:14 +00005676 case Type::BlockPointer: {
5677 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005678 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005679 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005680 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005681
5682 S += '<';
5683 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005684 getObjCEncodingForTypeImpl(
5685 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5686 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005687 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5688 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005689 // Block self
5690 S += "@?";
5691 // Block parameters
5692 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005693 for (const auto &I : FPT->param_types())
5694 getObjCEncodingForTypeImpl(
5695 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5696 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005697 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5698 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005699 }
5700 S += '>';
5701 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005702 return;
5703 }
Mike Stump11289f42009-09-09 15:08:12 +00005704
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005705 case Type::ObjCObject: {
5706 // hack to match legacy encoding of *id and *Class
5707 QualType Ty = getObjCObjectPointerType(CT);
5708 if (Ty->isObjCIdType()) {
5709 S += "{objc_object=}";
5710 return;
5711 }
5712 else if (Ty->isObjCClassType()) {
5713 S += "{objc_class=}";
5714 return;
5715 }
5716 }
5717
John McCall393a78d2012-12-20 02:45:14 +00005718 case Type::ObjCInterface: {
5719 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005720 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005721 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005722 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005723 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005724 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005725 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005726 DeepCollectObjCIvars(OI, true, Ivars);
5727 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005728 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005729 if (Field->isBitField())
5730 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005731 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005732 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5733 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005734 EncodePointerToObjCTypedef,
5735 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005736 }
5737 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005738 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005739 }
Mike Stump11289f42009-09-09 15:08:12 +00005740
John McCall393a78d2012-12-20 02:45:14 +00005741 case Type::ObjCObjectPointer: {
5742 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005743 if (OPT->isObjCIdType()) {
5744 S += '@';
5745 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005746 }
Mike Stump11289f42009-09-09 15:08:12 +00005747
Steve Narofff0c86112009-10-28 22:03:49 +00005748 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5749 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5750 // Since this is a binary compatibility issue, need to consult with runtime
5751 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005752 S += '#';
5753 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005754 }
Mike Stump11289f42009-09-09 15:08:12 +00005755
Chris Lattnere7cabb92009-07-13 00:10:46 +00005756 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005757 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005758 ExpandPointedToStructures,
5759 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005760 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005761 // Note that we do extended encoding of protocol qualifer list
5762 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005763 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005764 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005765 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005766 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005767 S += '>';
5768 }
5769 S += '"';
5770 }
5771 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005772 }
Mike Stump11289f42009-09-09 15:08:12 +00005773
Chris Lattnere7cabb92009-07-13 00:10:46 +00005774 QualType PointeeTy = OPT->getPointeeType();
5775 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005776 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5777 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005778 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005779 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005780 // {...};
5781 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005782 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005783 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005784 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5785 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5786 DeepCollectObjCIvars(OI, true, Ivars);
5787 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5788 if (cast<FieldDecl>(Ivars[i]) == FD) {
5789 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005790 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005791 S += '}';
5792 return;
5793 }
5794 }
5795 }
Mike Stump11289f42009-09-09 15:08:12 +00005796 getObjCEncodingForTypeImpl(PointeeTy, S,
5797 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005798 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005799 false, false, false, false, false,
5800 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005801 return;
5802 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005803
5804 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005805 if (OPT->getInterfaceDecl() &&
5806 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005807 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005808 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005809 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005810 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005811 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005812 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005813 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005814 S += '"';
5815 }
5816 return;
5817 }
Mike Stump11289f42009-09-09 15:08:12 +00005818
John McCalla9e6e8d2010-05-17 23:56:34 +00005819 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005820 // FIXME: we shoul do better than that. 'M' is available.
5821 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005822 // This matches gcc's encoding, even though technically it is insufficient.
5823 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005824 case Type::Vector:
5825 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005826 // Until we have a coherent encoding of these three types, issue warning.
5827 { if (NotEncodedT)
5828 *NotEncodedT = T;
5829 return;
5830 }
5831
5832 // We could see an undeduced auto type here during error recovery.
5833 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005834 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005835 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005836
Richard Smith27d807c2013-04-30 13:56:41 +00005837
John McCall393a78d2012-12-20 02:45:14 +00005838#define ABSTRACT_TYPE(KIND, BASE)
5839#define TYPE(KIND, BASE)
5840#define DEPENDENT_TYPE(KIND, BASE) \
5841 case Type::KIND:
5842#define NON_CANONICAL_TYPE(KIND, BASE) \
5843 case Type::KIND:
5844#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5845 case Type::KIND:
5846#include "clang/AST/TypeNodes.def"
5847 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005848 }
John McCall393a78d2012-12-20 02:45:14 +00005849 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005850}
5851
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005852void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5853 std::string &S,
5854 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005855 bool includeVBases,
5856 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005857 assert(RDecl && "Expected non-null RecordDecl");
5858 assert(!RDecl->isUnion() && "Should not be called for unions");
5859 if (!RDecl->getDefinition())
5860 return;
5861
5862 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5863 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5864 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5865
5866 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005867 for (const auto &BI : CXXRec->bases()) {
5868 if (!BI.isVirtual()) {
5869 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005870 if (base->isEmpty())
5871 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005872 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005873 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5874 std::make_pair(offs, base));
5875 }
5876 }
5877 }
5878
5879 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005880 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005881 uint64_t offs = layout.getFieldOffset(i);
5882 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005883 std::make_pair(offs, Field));
5884 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005885 }
5886
5887 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005888 for (const auto &BI : CXXRec->vbases()) {
5889 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005890 if (base->isEmpty())
5891 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005892 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005893 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5894 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005895 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5896 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005897 }
5898 }
5899
5900 CharUnits size;
5901 if (CXXRec) {
5902 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5903 } else {
5904 size = layout.getSize();
5905 }
5906
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005907#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005908 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005909#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005910 std::multimap<uint64_t, NamedDecl *>::iterator
5911 CurLayObj = FieldOrBaseOffsets.begin();
5912
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005913 if (CXXRec && CXXRec->isDynamicClass() &&
5914 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005915 if (FD) {
5916 S += "\"_vptr$";
5917 std::string recname = CXXRec->getNameAsString();
5918 if (recname.empty()) recname = "?";
5919 S += recname;
5920 S += '"';
5921 }
5922 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005923#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005924 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005925#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005926 }
5927
5928 if (!RDecl->hasFlexibleArrayMember()) {
5929 // Mark the end of the structure.
5930 uint64_t offs = toBits(size);
5931 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005932 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005933 }
5934
5935 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005936#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005937 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005938 if (CurOffs < CurLayObj->first) {
5939 uint64_t padding = CurLayObj->first - CurOffs;
5940 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5941 // packing/alignment of members is different that normal, in which case
5942 // the encoding will be out-of-sync with the real layout.
5943 // If the runtime switches to just consider the size of types without
5944 // taking into account alignment, we could make padding explicit in the
5945 // encoding (e.g. using arrays of chars). The encoding strings would be
5946 // longer then though.
5947 CurOffs += padding;
5948 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005949#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005950
5951 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005952 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005953 break; // reached end of structure.
5954
5955 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5956 // We expand the bases without their virtual bases since those are going
5957 // in the initial structure. Note that this differs from gcc which
5958 // expands virtual bases each time one is encountered in the hierarchy,
5959 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005960 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5961 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005962 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005963#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005964 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005965#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005966 } else {
5967 FieldDecl *field = cast<FieldDecl>(dcl);
5968 if (FD) {
5969 S += '"';
5970 S += field->getNameAsString();
5971 S += '"';
5972 }
5973
5974 if (field->isBitField()) {
5975 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005976#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005977 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005978#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005979 } else {
5980 QualType qt = field->getType();
5981 getLegacyIntegralTypeEncoding(qt);
5982 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5983 /*OutermostType*/false,
5984 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005985 /*StructField*/true,
5986 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005987#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005988 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005989#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005990 }
5991 }
5992 }
5993}
5994
Mike Stump11289f42009-09-09 15:08:12 +00005995void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005996 std::string& S) const {
5997 if (QT & Decl::OBJC_TQ_In)
5998 S += 'n';
5999 if (QT & Decl::OBJC_TQ_Inout)
6000 S += 'N';
6001 if (QT & Decl::OBJC_TQ_Out)
6002 S += 'o';
6003 if (QT & Decl::OBJC_TQ_Bycopy)
6004 S += 'O';
6005 if (QT & Decl::OBJC_TQ_Byref)
6006 S += 'R';
6007 if (QT & Decl::OBJC_TQ_Oneway)
6008 S += 'V';
6009}
6010
Douglas Gregor3ea72692011-08-12 05:46:01 +00006011TypedefDecl *ASTContext::getObjCIdDecl() const {
6012 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006013 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006014 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006015 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006016 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006017 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006018}
6019
Douglas Gregor52e02802011-08-12 06:17:30 +00006020TypedefDecl *ASTContext::getObjCSelDecl() const {
6021 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006022 QualType T = getPointerType(ObjCBuiltinSelTy);
6023 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006024 }
6025 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006026}
6027
Douglas Gregor0a586182011-08-12 05:59:41 +00006028TypedefDecl *ASTContext::getObjCClassDecl() const {
6029 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006030 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006031 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006032 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006033 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006034 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006035}
6036
Douglas Gregord53ae832012-01-17 18:09:05 +00006037ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6038 if (!ObjCProtocolClassDecl) {
6039 ObjCProtocolClassDecl
6040 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6041 SourceLocation(),
6042 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006043 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006044 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006045 SourceLocation(), true);
6046 }
6047
6048 return ObjCProtocolClassDecl;
6049}
6050
Meador Inge5d3fb222012-06-16 03:34:49 +00006051//===----------------------------------------------------------------------===//
6052// __builtin_va_list Construction Functions
6053//===----------------------------------------------------------------------===//
6054
Charles Davisc7d5c942015-09-17 20:55:33 +00006055static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6056 StringRef Name) {
6057 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006058 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006059 return Context->buildImplicitTypedef(T, Name);
6060}
6061
6062static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6063 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6064}
6065
6066static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6067 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006068}
6069
6070static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6071 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006072 QualType T = Context->getPointerType(Context->VoidTy);
6073 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006074}
6075
Tim Northover9bb857a2013-01-31 12:13:10 +00006076static TypedefDecl *
6077CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006078 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006079 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006080 if (Context->getLangOpts().CPlusPlus) {
6081 // namespace std { struct __va_list {
6082 NamespaceDecl *NS;
6083 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6084 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006085 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006086 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006087 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006088 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006089 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006090 }
6091
6092 VaListTagDecl->startDefinition();
6093
6094 const size_t NumFields = 5;
6095 QualType FieldTypes[NumFields];
6096 const char *FieldNames[NumFields];
6097
6098 // void *__stack;
6099 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6100 FieldNames[0] = "__stack";
6101
6102 // void *__gr_top;
6103 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6104 FieldNames[1] = "__gr_top";
6105
6106 // void *__vr_top;
6107 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6108 FieldNames[2] = "__vr_top";
6109
6110 // int __gr_offs;
6111 FieldTypes[3] = Context->IntTy;
6112 FieldNames[3] = "__gr_offs";
6113
6114 // int __vr_offs;
6115 FieldTypes[4] = Context->IntTy;
6116 FieldNames[4] = "__vr_offs";
6117
6118 // Create fields
6119 for (unsigned i = 0; i < NumFields; ++i) {
6120 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6121 VaListTagDecl,
6122 SourceLocation(),
6123 SourceLocation(),
6124 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006125 FieldTypes[i], /*TInfo=*/nullptr,
6126 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006127 /*Mutable=*/false,
6128 ICIS_NoInit);
6129 Field->setAccess(AS_public);
6130 VaListTagDecl->addDecl(Field);
6131 }
6132 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006133 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006134 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006135
6136 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006137 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006138}
6139
Meador Inge5d3fb222012-06-16 03:34:49 +00006140static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6141 // typedef struct __va_list_tag {
6142 RecordDecl *VaListTagDecl;
6143
Alp Toker2dea15b2013-12-17 01:22:38 +00006144 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006145 VaListTagDecl->startDefinition();
6146
6147 const size_t NumFields = 5;
6148 QualType FieldTypes[NumFields];
6149 const char *FieldNames[NumFields];
6150
6151 // unsigned char gpr;
6152 FieldTypes[0] = Context->UnsignedCharTy;
6153 FieldNames[0] = "gpr";
6154
6155 // unsigned char fpr;
6156 FieldTypes[1] = Context->UnsignedCharTy;
6157 FieldNames[1] = "fpr";
6158
6159 // unsigned short reserved;
6160 FieldTypes[2] = Context->UnsignedShortTy;
6161 FieldNames[2] = "reserved";
6162
6163 // void* overflow_arg_area;
6164 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6165 FieldNames[3] = "overflow_arg_area";
6166
6167 // void* reg_save_area;
6168 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6169 FieldNames[4] = "reg_save_area";
6170
6171 // Create fields
6172 for (unsigned i = 0; i < NumFields; ++i) {
6173 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6174 SourceLocation(),
6175 SourceLocation(),
6176 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006177 FieldTypes[i], /*TInfo=*/nullptr,
6178 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006179 /*Mutable=*/false,
6180 ICIS_NoInit);
6181 Field->setAccess(AS_public);
6182 VaListTagDecl->addDecl(Field);
6183 }
6184 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006185 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006186 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6187
6188 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006189 TypedefDecl *VaListTagTypedefDecl =
6190 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6191
Meador Inge5d3fb222012-06-16 03:34:49 +00006192 QualType VaListTagTypedefType =
6193 Context->getTypedefType(VaListTagTypedefDecl);
6194
6195 // typedef __va_list_tag __builtin_va_list[1];
6196 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6197 QualType VaListTagArrayType
6198 = Context->getConstantArrayType(VaListTagTypedefType,
6199 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006200 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006201}
6202
6203static TypedefDecl *
6204CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006205 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006206 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006207 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006208 VaListTagDecl->startDefinition();
6209
6210 const size_t NumFields = 4;
6211 QualType FieldTypes[NumFields];
6212 const char *FieldNames[NumFields];
6213
6214 // unsigned gp_offset;
6215 FieldTypes[0] = Context->UnsignedIntTy;
6216 FieldNames[0] = "gp_offset";
6217
6218 // unsigned fp_offset;
6219 FieldTypes[1] = Context->UnsignedIntTy;
6220 FieldNames[1] = "fp_offset";
6221
6222 // void* overflow_arg_area;
6223 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6224 FieldNames[2] = "overflow_arg_area";
6225
6226 // void* reg_save_area;
6227 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6228 FieldNames[3] = "reg_save_area";
6229
6230 // Create fields
6231 for (unsigned i = 0; i < NumFields; ++i) {
6232 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6233 VaListTagDecl,
6234 SourceLocation(),
6235 SourceLocation(),
6236 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006237 FieldTypes[i], /*TInfo=*/nullptr,
6238 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006239 /*Mutable=*/false,
6240 ICIS_NoInit);
6241 Field->setAccess(AS_public);
6242 VaListTagDecl->addDecl(Field);
6243 }
6244 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006245 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006246 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6247
Richard Smith9b88a4c2015-07-27 05:40:23 +00006248 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006249
Richard Smith9b88a4c2015-07-27 05:40:23 +00006250 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006251 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006252 QualType VaListTagArrayType =
6253 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006254 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006255}
6256
6257static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6258 // typedef int __builtin_va_list[4];
6259 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6260 QualType IntArrayType
6261 = Context->getConstantArrayType(Context->IntTy,
6262 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006263 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006264}
6265
Logan Chien57086ce2012-10-10 06:56:20 +00006266static TypedefDecl *
6267CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006268 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006269 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006270 if (Context->getLangOpts().CPlusPlus) {
6271 // namespace std { struct __va_list {
6272 NamespaceDecl *NS;
6273 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6274 Context->getTranslationUnitDecl(),
6275 /*Inline*/false, SourceLocation(),
6276 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006277 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006278 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006279 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006280 }
6281
6282 VaListDecl->startDefinition();
6283
6284 // void * __ap;
6285 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6286 VaListDecl,
6287 SourceLocation(),
6288 SourceLocation(),
6289 &Context->Idents.get("__ap"),
6290 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006291 /*TInfo=*/nullptr,
6292 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006293 /*Mutable=*/false,
6294 ICIS_NoInit);
6295 Field->setAccess(AS_public);
6296 VaListDecl->addDecl(Field);
6297
6298 // };
6299 VaListDecl->completeDefinition();
6300
6301 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006302 QualType T = Context->getRecordType(VaListDecl);
6303 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006304}
6305
Ulrich Weigand47445072013-05-06 16:26:41 +00006306static TypedefDecl *
6307CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006308 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006309 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006310 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006311 VaListTagDecl->startDefinition();
6312
6313 const size_t NumFields = 4;
6314 QualType FieldTypes[NumFields];
6315 const char *FieldNames[NumFields];
6316
6317 // long __gpr;
6318 FieldTypes[0] = Context->LongTy;
6319 FieldNames[0] = "__gpr";
6320
6321 // long __fpr;
6322 FieldTypes[1] = Context->LongTy;
6323 FieldNames[1] = "__fpr";
6324
6325 // void *__overflow_arg_area;
6326 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6327 FieldNames[2] = "__overflow_arg_area";
6328
6329 // void *__reg_save_area;
6330 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6331 FieldNames[3] = "__reg_save_area";
6332
6333 // Create fields
6334 for (unsigned i = 0; i < NumFields; ++i) {
6335 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6336 VaListTagDecl,
6337 SourceLocation(),
6338 SourceLocation(),
6339 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006340 FieldTypes[i], /*TInfo=*/nullptr,
6341 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006342 /*Mutable=*/false,
6343 ICIS_NoInit);
6344 Field->setAccess(AS_public);
6345 VaListTagDecl->addDecl(Field);
6346 }
6347 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006348 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006349 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006350
Richard Smith9b88a4c2015-07-27 05:40:23 +00006351 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006352
6353 // typedef __va_list_tag __builtin_va_list[1];
6354 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006355 QualType VaListTagArrayType =
6356 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006357
Alp Toker56b5cc92013-12-15 10:36:26 +00006358 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006359}
6360
Meador Inge5d3fb222012-06-16 03:34:49 +00006361static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6362 TargetInfo::BuiltinVaListKind Kind) {
6363 switch (Kind) {
6364 case TargetInfo::CharPtrBuiltinVaList:
6365 return CreateCharPtrBuiltinVaListDecl(Context);
6366 case TargetInfo::VoidPtrBuiltinVaList:
6367 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006368 case TargetInfo::AArch64ABIBuiltinVaList:
6369 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006370 case TargetInfo::PowerABIBuiltinVaList:
6371 return CreatePowerABIBuiltinVaListDecl(Context);
6372 case TargetInfo::X86_64ABIBuiltinVaList:
6373 return CreateX86_64ABIBuiltinVaListDecl(Context);
6374 case TargetInfo::PNaClABIBuiltinVaList:
6375 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006376 case TargetInfo::AAPCSABIBuiltinVaList:
6377 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006378 case TargetInfo::SystemZBuiltinVaList:
6379 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006380 }
6381
6382 llvm_unreachable("Unhandled __builtin_va_list type kind");
6383}
6384
6385TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006386 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006387 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006388 assert(BuiltinVaListDecl->isImplicit());
6389 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006390
6391 return BuiltinVaListDecl;
6392}
6393
Richard Smith9b88a4c2015-07-27 05:40:23 +00006394Decl *ASTContext::getVaListTagDecl() const {
6395 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006396 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006397 if (!VaListTagDecl)
6398 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006399
Richard Smith9b88a4c2015-07-27 05:40:23 +00006400 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006401}
6402
Charles Davisc7d5c942015-09-17 20:55:33 +00006403TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6404 if (!BuiltinMSVaListDecl)
6405 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6406
6407 return BuiltinMSVaListDecl;
6408}
6409
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006410void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006411 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006412 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006413
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006414 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006415}
6416
John McCalld28ae272009-12-02 08:04:21 +00006417/// \brief Retrieve the template name that corresponds to a non-empty
6418/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006419TemplateName
6420ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6421 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006422 unsigned size = End - Begin;
6423 assert(size > 1 && "set is not overloaded!");
6424
6425 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6426 size * sizeof(FunctionTemplateDecl*));
6427 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6428
6429 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006430 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006431 NamedDecl *D = *I;
6432 assert(isa<FunctionTemplateDecl>(D) ||
6433 (isa<UsingShadowDecl>(D) &&
6434 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6435 *Storage++ = D;
6436 }
6437
6438 return TemplateName(OT);
6439}
6440
Douglas Gregordc572a32009-03-30 22:58:21 +00006441/// \brief Retrieve the template name that represents a qualified
6442/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006443TemplateName
6444ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6445 bool TemplateKeyword,
6446 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006447 assert(NNS && "Missing nested-name-specifier in qualified template name");
6448
Douglas Gregorc42075a2010-02-04 18:10:26 +00006449 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006450 llvm::FoldingSetNodeID ID;
6451 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6452
Craig Topper36250ad2014-05-12 05:36:57 +00006453 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006454 QualifiedTemplateName *QTN =
6455 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6456 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006457 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6458 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006459 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6460 }
6461
6462 return TemplateName(QTN);
6463}
6464
6465/// \brief Retrieve the template name that represents a dependent
6466/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006467TemplateName
6468ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6469 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006470 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006471 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006472
6473 llvm::FoldingSetNodeID ID;
6474 DependentTemplateName::Profile(ID, NNS, Name);
6475
Craig Topper36250ad2014-05-12 05:36:57 +00006476 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006477 DependentTemplateName *QTN =
6478 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6479
6480 if (QTN)
6481 return TemplateName(QTN);
6482
6483 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6484 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006485 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6486 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006487 } else {
6488 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006489 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6490 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006491 DependentTemplateName *CheckQTN =
6492 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6493 assert(!CheckQTN && "Dependent type name canonicalization broken");
6494 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006495 }
6496
6497 DependentTemplateNames.InsertNode(QTN, InsertPos);
6498 return TemplateName(QTN);
6499}
6500
Douglas Gregor71395fa2009-11-04 00:56:37 +00006501/// \brief Retrieve the template name that represents a dependent
6502/// template name such as \c MetaFun::template operator+.
6503TemplateName
6504ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006505 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006506 assert((!NNS || NNS->isDependent()) &&
6507 "Nested name specifier must be dependent");
6508
6509 llvm::FoldingSetNodeID ID;
6510 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006511
6512 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006513 DependentTemplateName *QTN
6514 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006515
6516 if (QTN)
6517 return TemplateName(QTN);
6518
6519 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6520 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006521 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6522 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006523 } else {
6524 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006525 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6526 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006527
6528 DependentTemplateName *CheckQTN
6529 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6530 assert(!CheckQTN && "Dependent template name canonicalization broken");
6531 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006532 }
6533
6534 DependentTemplateNames.InsertNode(QTN, InsertPos);
6535 return TemplateName(QTN);
6536}
6537
Douglas Gregor5590be02011-01-15 06:45:20 +00006538TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006539ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6540 TemplateName replacement) const {
6541 llvm::FoldingSetNodeID ID;
6542 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006543
6544 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006545 SubstTemplateTemplateParmStorage *subst
6546 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6547
6548 if (!subst) {
6549 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6550 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6551 }
6552
6553 return TemplateName(subst);
6554}
6555
6556TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006557ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6558 const TemplateArgument &ArgPack) const {
6559 ASTContext &Self = const_cast<ASTContext &>(*this);
6560 llvm::FoldingSetNodeID ID;
6561 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006562
6563 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006564 SubstTemplateTemplateParmPackStorage *Subst
6565 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6566
6567 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006568 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006569 ArgPack.pack_size(),
6570 ArgPack.pack_begin());
6571 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6572 }
6573
6574 return TemplateName(Subst);
6575}
6576
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006577/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006578/// TargetInfo, produce the corresponding type. The unsigned @p Type
6579/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006580CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006581 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006582 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006583 case TargetInfo::SignedChar: return SignedCharTy;
6584 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006585 case TargetInfo::SignedShort: return ShortTy;
6586 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6587 case TargetInfo::SignedInt: return IntTy;
6588 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6589 case TargetInfo::SignedLong: return LongTy;
6590 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6591 case TargetInfo::SignedLongLong: return LongLongTy;
6592 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6593 }
6594
David Blaikie83d382b2011-09-23 05:06:16 +00006595 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006596}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006597
6598//===----------------------------------------------------------------------===//
6599// Type Predicates.
6600//===----------------------------------------------------------------------===//
6601
Fariborz Jahanian96207692009-02-18 21:49:28 +00006602/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6603/// garbage collection attribute.
6604///
John McCall553d45a2011-01-12 00:34:59 +00006605Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006606 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006607 return Qualifiers::GCNone;
6608
David Blaikiebbafb8a2012-03-11 07:00:24 +00006609 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006610 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6611
6612 // Default behaviour under objective-C's gc is for ObjC pointers
6613 // (or pointers to them) be treated as though they were declared
6614 // as __strong.
6615 if (GCAttrs == Qualifiers::GCNone) {
6616 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6617 return Qualifiers::Strong;
6618 else if (Ty->isPointerType())
6619 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6620 } else {
6621 // It's not valid to set GC attributes on anything that isn't a
6622 // pointer.
6623#ifndef NDEBUG
6624 QualType CT = Ty->getCanonicalTypeInternal();
6625 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6626 CT = AT->getElementType();
6627 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6628#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006629 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006630 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006631}
6632
Chris Lattner49af6a42008-04-07 06:51:04 +00006633//===----------------------------------------------------------------------===//
6634// Type Compatibility Testing
6635//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006636
Mike Stump11289f42009-09-09 15:08:12 +00006637/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006638/// compatible.
6639static bool areCompatVectorTypes(const VectorType *LHS,
6640 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006641 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006642 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006643 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006644}
6645
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006646bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6647 QualType SecondVec) {
6648 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6649 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6650
6651 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6652 return true;
6653
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006654 // Treat Neon vector types and most AltiVec vector types as if they are the
6655 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006656 const VectorType *First = FirstVec->getAs<VectorType>();
6657 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006658 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006659 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006660 First->getVectorKind() != VectorType::AltiVecPixel &&
6661 First->getVectorKind() != VectorType::AltiVecBool &&
6662 Second->getVectorKind() != VectorType::AltiVecPixel &&
6663 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006664 return true;
6665
6666 return false;
6667}
6668
Steve Naroff8e6aee52009-07-23 01:01:38 +00006669//===----------------------------------------------------------------------===//
6670// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6671//===----------------------------------------------------------------------===//
6672
6673/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6674/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006675bool
6676ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6677 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006678 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006679 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006680 for (auto *PI : rProto->protocols())
6681 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006682 return true;
6683 return false;
6684}
6685
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006686/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6687/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006688bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6689 QualType rhs) {
6690 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6691 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6692 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6693
Aaron Ballman83731462014-03-17 16:14:00 +00006694 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006695 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006696 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006697 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6698 match = true;
6699 break;
6700 }
6701 }
6702 if (!match)
6703 return false;
6704 }
6705 return true;
6706}
6707
Steve Naroff8e6aee52009-07-23 01:01:38 +00006708/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6709/// ObjCQualifiedIDType.
6710bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6711 bool compare) {
6712 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006713 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006714 lhs->isObjCIdType() || lhs->isObjCClassType())
6715 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006716 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006717 rhs->isObjCIdType() || rhs->isObjCClassType())
6718 return true;
6719
6720 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006721 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006722
Steve Naroff8e6aee52009-07-23 01:01:38 +00006723 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006724
Steve Naroff8e6aee52009-07-23 01:01:38 +00006725 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006726 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006727 // make sure we check the class hierarchy.
6728 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006729 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006730 // when comparing an id<P> on lhs with a static type on rhs,
6731 // see if static class implements all of id's protocols, directly or
6732 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006733 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006734 return false;
6735 }
6736 }
6737 // If there are no qualifiers and no interface, we have an 'id'.
6738 return true;
6739 }
Mike Stump11289f42009-09-09 15:08:12 +00006740 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006741 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006742 bool match = false;
6743
6744 // when comparing an id<P> on lhs with a static type on rhs,
6745 // see if static class implements all of id's protocols, directly or
6746 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006747 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006748 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6749 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6750 match = true;
6751 break;
6752 }
6753 }
Mike Stump11289f42009-09-09 15:08:12 +00006754 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006755 // make sure we check the class hierarchy.
6756 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006757 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006758 // when comparing an id<P> on lhs with a static type on rhs,
6759 // see if static class implements all of id's protocols, directly or
6760 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006761 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006762 match = true;
6763 break;
6764 }
6765 }
6766 }
6767 if (!match)
6768 return false;
6769 }
Mike Stump11289f42009-09-09 15:08:12 +00006770
Steve Naroff8e6aee52009-07-23 01:01:38 +00006771 return true;
6772 }
Mike Stump11289f42009-09-09 15:08:12 +00006773
Steve Naroff8e6aee52009-07-23 01:01:38 +00006774 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6775 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6776
Mike Stump11289f42009-09-09 15:08:12 +00006777 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006778 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006779 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006780 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006781 bool match = false;
6782
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006783 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006784 // see if static class implements all of id's protocols, directly or
6785 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006786 // First, lhs protocols in the qualifier list must be found, direct
6787 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006788 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006789 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6790 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6791 match = true;
6792 break;
6793 }
6794 }
6795 if (!match)
6796 return false;
6797 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006798
6799 // Static class's protocols, or its super class or category protocols
6800 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6801 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6802 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6803 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6804 // This is rather dubious but matches gcc's behavior. If lhs has
6805 // no type qualifier and its class has no static protocol(s)
6806 // assume that it is mismatch.
6807 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6808 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006809 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006810 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006811 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006812 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6813 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6814 match = true;
6815 break;
6816 }
6817 }
6818 if (!match)
6819 return false;
6820 }
6821 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006822 return true;
6823 }
6824 return false;
6825}
6826
Eli Friedman47f77112008-08-22 00:56:42 +00006827/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006828/// compatible for assignment from RHS to LHS. This handles validation of any
6829/// protocol qualifiers on the LHS or RHS.
6830///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006831bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6832 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006833 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6834 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6835
Steve Naroff1329fa02009-07-15 18:40:39 +00006836 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006837 if (LHS->isObjCUnqualifiedIdOrClass() ||
6838 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006839 return true;
6840
Douglas Gregorab209d82015-07-07 03:58:42 +00006841 // Function object that propagates a successful result or handles
6842 // __kindof types.
6843 auto finish = [&](bool succeeded) -> bool {
6844 if (succeeded)
6845 return true;
6846
6847 if (!RHS->isKindOfType())
6848 return false;
6849
6850 // Strip off __kindof and protocol qualifiers, then check whether
6851 // we can assign the other way.
6852 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6853 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6854 };
6855
6856 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6857 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6858 QualType(RHSOPT,0),
6859 false));
6860 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006861
Douglas Gregorab209d82015-07-07 03:58:42 +00006862 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6863 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6864 QualType(RHSOPT,0)));
6865 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006866
John McCall8b07ec22010-05-15 11:32:37 +00006867 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006868 if (LHS->getInterface() && RHS->getInterface()) {
6869 return finish(canAssignObjCInterfaces(LHS, RHS));
6870 }
Mike Stump11289f42009-09-09 15:08:12 +00006871
Steve Naroff8e6aee52009-07-23 01:01:38 +00006872 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006873}
6874
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006875/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006876/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006877/// arguments in block literals. When passed as arguments, passing 'A*' where
6878/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6879/// not OK. For the return type, the opposite is not OK.
6880bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6881 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006882 const ObjCObjectPointerType *RHSOPT,
6883 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006884
6885 // Function object that propagates a successful result or handles
6886 // __kindof types.
6887 auto finish = [&](bool succeeded) -> bool {
6888 if (succeeded)
6889 return true;
6890
6891 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6892 if (!Expected->isKindOfType())
6893 return false;
6894
6895 // Strip off __kindof and protocol qualifiers, then check whether
6896 // we can assign the other way.
6897 return canAssignObjCInterfacesInBlockPointer(
6898 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6899 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6900 BlockReturnType);
6901 };
6902
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006903 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006904 return true;
6905
6906 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006907 return finish(RHSOPT->isObjCBuiltinType() ||
6908 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006909 }
6910
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006911 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006912 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6913 QualType(RHSOPT,0),
6914 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006915
6916 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6917 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6918 if (LHS && RHS) { // We have 2 user-defined types.
6919 if (LHS != RHS) {
6920 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006921 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006922 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006923 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006924 }
6925 else
6926 return true;
6927 }
6928 return false;
6929}
6930
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006931/// Comparison routine for Objective-C protocols to be used with
6932/// llvm::array_pod_sort.
6933static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6934 ObjCProtocolDecl * const *rhs) {
6935 return (*lhs)->getName().compare((*rhs)->getName());
6936
6937}
6938
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006939/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006940/// of protocols inherited from two distinct objective-c pointer objects with
6941/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006942/// It is used to build composite qualifier list of the composite type of
6943/// the conditional expression involving two objective-c pointer objects.
6944static
6945void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006946 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006947 const ObjCObjectPointerType *LHSOPT,
6948 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006949 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006950
John McCall8b07ec22010-05-15 11:32:37 +00006951 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6952 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6953 assert(LHS->getInterface() && "LHS must have an interface base");
6954 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006955
6956 // Add all of the protocols for the LHS.
6957 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6958
6959 // Start with the protocol qualifiers.
6960 for (auto proto : LHS->quals()) {
6961 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006962 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006963
6964 // Also add the protocols associated with the LHS interface.
6965 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6966
6967 // Add all of the protocls for the RHS.
6968 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6969
6970 // Start with the protocol qualifiers.
6971 for (auto proto : RHS->quals()) {
6972 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006973 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006974
6975 // Also add the protocols associated with the RHS interface.
6976 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6977
6978 // Compute the intersection of the collected protocol sets.
6979 for (auto proto : LHSProtocolSet) {
6980 if (RHSProtocolSet.count(proto))
6981 IntersectionSet.push_back(proto);
6982 }
6983
6984 // Compute the set of protocols that is implied by either the common type or
6985 // the protocols within the intersection.
6986 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6987 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6988
6989 // Remove any implied protocols from the list of inherited protocols.
6990 if (!ImpliedProtocols.empty()) {
6991 IntersectionSet.erase(
6992 std::remove_if(IntersectionSet.begin(),
6993 IntersectionSet.end(),
6994 [&](ObjCProtocolDecl *proto) -> bool {
6995 return ImpliedProtocols.count(proto) > 0;
6996 }),
6997 IntersectionSet.end());
6998 }
6999
7000 // Sort the remaining protocols by name.
7001 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7002 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007003}
7004
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007005/// Determine whether the first type is a subtype of the second.
7006static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7007 QualType rhs) {
7008 // Common case: two object pointers.
7009 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7010 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7011 if (lhsOPT && rhsOPT)
7012 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7013
7014 // Two block pointers.
7015 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7016 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7017 if (lhsBlock && rhsBlock)
7018 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7019
7020 // If either is an unqualified 'id' and the other is a block, it's
7021 // acceptable.
7022 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7023 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7024 return true;
7025
7026 return false;
7027}
7028
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007029// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007030static bool sameObjCTypeArgs(ASTContext &ctx,
7031 const ObjCInterfaceDecl *iface,
7032 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007033 ArrayRef<QualType> rhsArgs,
7034 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007035 if (lhsArgs.size() != rhsArgs.size())
7036 return false;
7037
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007038 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007039 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007040 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7041 continue;
7042
7043 switch (typeParams->begin()[i]->getVariance()) {
7044 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007045 if (!stripKindOf ||
7046 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7047 rhsArgs[i].stripObjCKindOfType(ctx))) {
7048 return false;
7049 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007050 break;
7051
7052 case ObjCTypeParamVariance::Covariant:
7053 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7054 return false;
7055 break;
7056
7057 case ObjCTypeParamVariance::Contravariant:
7058 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7059 return false;
7060 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007061 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007062 }
7063
7064 return true;
7065}
7066
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007067QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007068 const ObjCObjectPointerType *Lptr,
7069 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007070 const ObjCObjectType *LHS = Lptr->getObjectType();
7071 const ObjCObjectType *RHS = Rptr->getObjectType();
7072 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7073 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007074
7075 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007076 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007077
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007078 // Follow the left-hand side up the class hierarchy until we either hit a
7079 // root or find the RHS. Record the ancestors in case we don't find it.
7080 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7081 LHSAncestors;
7082 while (true) {
7083 // Record this ancestor. We'll need this if the common type isn't in the
7084 // path from the LHS to the root.
7085 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007086
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007087 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7088 // Get the type arguments.
7089 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7090 bool anyChanges = false;
7091 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7092 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007093 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7094 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007095 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007096 return QualType();
7097 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7098 // If only one has type arguments, the result will not have type
7099 // arguments.
7100 LHSTypeArgs = { };
7101 anyChanges = true;
7102 }
7103
7104 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007105 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007106 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7107 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007108 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007109 anyChanges = true;
7110
7111 // If anything in the LHS will have changed, build a new result type.
7112 if (anyChanges) {
7113 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007114 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7115 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007116 return getObjCObjectPointerType(Result);
7117 }
7118
7119 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007120 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007121
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007122 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007123 QualType LHSSuperType = LHS->getSuperClassType();
7124 if (LHSSuperType.isNull())
7125 break;
7126
7127 LHS = LHSSuperType->castAs<ObjCObjectType>();
7128 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007129
7130 // We didn't find anything by following the LHS to its root; now check
7131 // the RHS against the cached set of ancestors.
7132 while (true) {
7133 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7134 if (KnownLHS != LHSAncestors.end()) {
7135 LHS = KnownLHS->second;
7136
7137 // Get the type arguments.
7138 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7139 bool anyChanges = false;
7140 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7141 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007142 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7143 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007144 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007145 return QualType();
7146 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7147 // If only one has type arguments, the result will not have type
7148 // arguments.
7149 RHSTypeArgs = { };
7150 anyChanges = true;
7151 }
7152
7153 // Compute the intersection of protocols.
7154 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7155 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7156 Protocols);
7157 if (!Protocols.empty())
7158 anyChanges = true;
7159
7160 if (anyChanges) {
7161 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007162 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7163 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007164 return getObjCObjectPointerType(Result);
7165 }
7166
7167 return getObjCObjectPointerType(QualType(RHS, 0));
7168 }
7169
7170 // Find the superclass of the RHS.
7171 QualType RHSSuperType = RHS->getSuperClassType();
7172 if (RHSSuperType.isNull())
7173 break;
7174
7175 RHS = RHSSuperType->castAs<ObjCObjectType>();
7176 }
7177
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007178 return QualType();
7179}
7180
John McCall8b07ec22010-05-15 11:32:37 +00007181bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7182 const ObjCObjectType *RHS) {
7183 assert(LHS->getInterface() && "LHS is not an interface type");
7184 assert(RHS->getInterface() && "RHS is not an interface type");
7185
Chris Lattner49af6a42008-04-07 06:51:04 +00007186 // Verify that the base decls are compatible: the RHS must be a subclass of
7187 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007188 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7189 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7190 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007191 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007192
Douglas Gregore83b9562015-07-07 03:57:53 +00007193 // If the LHS has protocol qualifiers, determine whether all of them are
7194 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7195 // LHS).
7196 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007197 // OK if conversion of LHS to SuperClass results in narrowing of types
7198 // ; i.e., SuperClass may implement at least one of the protocols
7199 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7200 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7201 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7202 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7203 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7204 // qualifiers.
7205 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007206 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007207 // If there is no protocols associated with RHS, it is not a match.
7208 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007209 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007210
7211 for (const auto *LHSProto : LHS->quals()) {
7212 bool SuperImplementsProtocol = false;
7213 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7214 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7215 SuperImplementsProtocol = true;
7216 break;
7217 }
7218 if (!SuperImplementsProtocol)
7219 return false;
7220 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007221 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007222
7223 // If the LHS is specialized, we may need to check type arguments.
7224 if (LHS->isSpecialized()) {
7225 // Follow the superclass chain until we've matched the LHS class in the
7226 // hierarchy. This substitutes type arguments through.
7227 const ObjCObjectType *RHSSuper = RHS;
7228 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7229 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7230
7231 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007232 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007233 !sameObjCTypeArgs(*this, LHS->getInterface(),
7234 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007235 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007236 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007237 }
7238 }
7239
7240 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007241}
7242
Steve Naroffb7605152009-02-12 17:52:19 +00007243bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7244 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007245 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7246 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007247
Steve Naroff7cae42b2009-07-10 23:34:53 +00007248 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007249 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007250
7251 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7252 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007253}
7254
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007255bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7256 return canAssignObjCInterfaces(
7257 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7258 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7259}
7260
Mike Stump11289f42009-09-09 15:08:12 +00007261/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007262/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007263/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007264/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007265bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7266 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007267 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007268 return hasSameType(LHS, RHS);
7269
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007270 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007271}
7272
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007273bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007274 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007275}
7276
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007277bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7278 return !mergeTypes(LHS, RHS, true).isNull();
7279}
7280
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007281/// mergeTransparentUnionType - if T is a transparent union type and a member
7282/// of T is compatible with SubType, return the merged type, else return
7283/// QualType()
7284QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7285 bool OfBlockPointer,
7286 bool Unqualified) {
7287 if (const RecordType *UT = T->getAsUnionType()) {
7288 RecordDecl *UD = UT->getDecl();
7289 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007290 for (const auto *I : UD->fields()) {
7291 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007292 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7293 if (!MT.isNull())
7294 return MT;
7295 }
7296 }
7297 }
7298
7299 return QualType();
7300}
7301
Alp Toker9cacbab2014-01-20 20:26:09 +00007302/// mergeFunctionParameterTypes - merge two types which appear as function
7303/// parameter types
7304QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7305 bool OfBlockPointer,
7306 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007307 // GNU extension: two types are compatible if they appear as a function
7308 // argument, one of the types is a transparent union type and the other
7309 // type is compatible with a union member
7310 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7311 Unqualified);
7312 if (!lmerge.isNull())
7313 return lmerge;
7314
7315 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7316 Unqualified);
7317 if (!rmerge.isNull())
7318 return rmerge;
7319
7320 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7321}
7322
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007323QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007324 bool OfBlockPointer,
7325 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007326 const FunctionType *lbase = lhs->getAs<FunctionType>();
7327 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007328 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7329 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007330 bool allLTypes = true;
7331 bool allRTypes = true;
7332
7333 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007334 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007335 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007336 QualType RHS = rbase->getReturnType();
7337 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007338 bool UnqualifiedResult = Unqualified;
7339 if (!UnqualifiedResult)
7340 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007341 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007342 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007343 else
Alp Toker314cc812014-01-25 16:55:45 +00007344 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007345 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007346 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007347
7348 if (Unqualified)
7349 retType = retType.getUnqualifiedType();
7350
Alp Toker314cc812014-01-25 16:55:45 +00007351 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7352 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007353 if (Unqualified) {
7354 LRetType = LRetType.getUnqualifiedType();
7355 RRetType = RRetType.getUnqualifiedType();
7356 }
7357
7358 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007359 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007360 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007361 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007362
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007363 // FIXME: double check this
7364 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7365 // rbase->getRegParmAttr() != 0 &&
7366 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007367 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7368 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007369
Douglas Gregor8c940862010-01-18 17:14:39 +00007370 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007371 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007372 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007373
John McCall8c6b56f2010-12-15 01:06:38 +00007374 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007375 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7376 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007377 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7378 return QualType();
7379
John McCall31168b02011-06-15 23:02:42 +00007380 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7381 return QualType();
7382
John McCall8c6b56f2010-12-15 01:06:38 +00007383 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7384 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007385
Rafael Espindola8778c282012-11-29 16:09:03 +00007386 if (lbaseInfo.getNoReturn() != NoReturn)
7387 allLTypes = false;
7388 if (rbaseInfo.getNoReturn() != NoReturn)
7389 allRTypes = false;
7390
John McCall31168b02011-06-15 23:02:42 +00007391 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007392
Eli Friedman47f77112008-08-22 00:56:42 +00007393 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007394 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7395 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007396 // Compatible functions must have the same number of parameters
7397 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007398 return QualType();
7399
7400 // Variadic and non-variadic functions aren't compatible
7401 if (lproto->isVariadic() != rproto->isVariadic())
7402 return QualType();
7403
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007404 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7405 return QualType();
7406
Fariborz Jahanian97676972011-09-28 21:52:05 +00007407 if (LangOpts.ObjCAutoRefCount &&
7408 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7409 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007410
7411 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007412 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007413 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7414 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7415 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7416 QualType paramType = mergeFunctionParameterTypes(
7417 lParamType, rParamType, OfBlockPointer, Unqualified);
7418 if (paramType.isNull())
7419 return QualType();
7420
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007421 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007422 paramType = paramType.getUnqualifiedType();
7423
7424 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007425 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007426 lParamType = lParamType.getUnqualifiedType();
7427 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007428 }
Alp Toker601b22c2014-01-21 23:35:24 +00007429
7430 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007431 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007432 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007433 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007434 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007435
Eli Friedman47f77112008-08-22 00:56:42 +00007436 if (allLTypes) return lhs;
7437 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007438
7439 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7440 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007441 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007442 }
7443
7444 if (lproto) allRTypes = false;
7445 if (rproto) allLTypes = false;
7446
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007447 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007448 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007449 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007450 if (proto->isVariadic()) return QualType();
7451 // Check that the types are compatible with the types that
7452 // would result from default argument promotions (C99 6.7.5.3p15).
7453 // The only types actually affected are promotable integer
7454 // types and floats, which would be passed as a different
7455 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007456 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7457 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007458
Eli Friedman448ce402012-08-30 00:44:15 +00007459 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007460 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007461 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7462 paramTy = Enum->getDecl()->getIntegerType();
7463 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007464 return QualType();
7465 }
Alp Toker601b22c2014-01-21 23:35:24 +00007466
7467 if (paramTy->isPromotableIntegerType() ||
7468 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007469 return QualType();
7470 }
7471
7472 if (allLTypes) return lhs;
7473 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007474
7475 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7476 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007477 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007478 }
7479
7480 if (allLTypes) return lhs;
7481 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007482 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007483}
7484
John McCall433c2e62013-03-21 00:10:07 +00007485/// Given that we have an enum type and a non-enum type, try to merge them.
7486static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7487 QualType other, bool isBlockReturnType) {
7488 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7489 // a signed integer type, or an unsigned integer type.
7490 // Compatibility is based on the underlying type, not the promotion
7491 // type.
7492 QualType underlyingType = ET->getDecl()->getIntegerType();
7493 if (underlyingType.isNull()) return QualType();
7494 if (Context.hasSameType(underlyingType, other))
7495 return other;
7496
7497 // In block return types, we're more permissive and accept any
7498 // integral type of the same size.
7499 if (isBlockReturnType && other->isIntegerType() &&
7500 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7501 return other;
7502
7503 return QualType();
7504}
7505
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007506QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007507 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007508 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007509 // C++ [expr]: If an expression initially has the type "reference to T", the
7510 // type is adjusted to "T" prior to any further analysis, the expression
7511 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007512 // expression is an lvalue unless the reference is an rvalue reference and
7513 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007514 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7515 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007516
7517 if (Unqualified) {
7518 LHS = LHS.getUnqualifiedType();
7519 RHS = RHS.getUnqualifiedType();
7520 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007521
Eli Friedman47f77112008-08-22 00:56:42 +00007522 QualType LHSCan = getCanonicalType(LHS),
7523 RHSCan = getCanonicalType(RHS);
7524
7525 // If two types are identical, they are compatible.
7526 if (LHSCan == RHSCan)
7527 return LHS;
7528
John McCall8ccfcb52009-09-24 19:53:00 +00007529 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007530 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7531 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007532 if (LQuals != RQuals) {
7533 // If any of these qualifiers are different, we have a type
7534 // mismatch.
7535 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007536 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7537 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007538 return QualType();
7539
7540 // Exactly one GC qualifier difference is allowed: __strong is
7541 // okay if the other type has no GC qualifier but is an Objective
7542 // C object pointer (i.e. implicitly strong by default). We fix
7543 // this by pretending that the unqualified type was actually
7544 // qualified __strong.
7545 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7546 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7547 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7548
7549 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7550 return QualType();
7551
7552 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7553 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7554 }
7555 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7556 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7557 }
Eli Friedman47f77112008-08-22 00:56:42 +00007558 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007559 }
7560
7561 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007562
Eli Friedmandcca6332009-06-01 01:22:52 +00007563 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7564 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007565
Chris Lattnerfd652912008-01-14 05:45:46 +00007566 // We want to consider the two function types to be the same for these
7567 // comparisons, just force one to the other.
7568 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7569 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007570
7571 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007572 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7573 LHSClass = Type::ConstantArray;
7574 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7575 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007576
John McCall8b07ec22010-05-15 11:32:37 +00007577 // ObjCInterfaces are just specialized ObjCObjects.
7578 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7579 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7580
Nate Begemance4d7fc2008-04-18 23:10:10 +00007581 // Canonicalize ExtVector -> Vector.
7582 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7583 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007584
Chris Lattner95554662008-04-07 05:43:21 +00007585 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007586 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007587 // Note that we only have special rules for turning block enum
7588 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007589 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007590 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007591 }
John McCall9dd450b2009-09-21 23:43:11 +00007592 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007593 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007594 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007595 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007596 if (OfBlockPointer && !BlockReturnType) {
7597 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7598 return LHS;
7599 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7600 return RHS;
7601 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007602
Eli Friedman47f77112008-08-22 00:56:42 +00007603 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007604 }
Eli Friedman47f77112008-08-22 00:56:42 +00007605
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007606 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007607 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007608#define TYPE(Class, Base)
7609#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007610#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007611#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7612#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7613#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007614 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007615
Richard Smith27d807c2013-04-30 13:56:41 +00007616 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007617 case Type::LValueReference:
7618 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007619 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007620 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007621
John McCall8b07ec22010-05-15 11:32:37 +00007622 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007623 case Type::IncompleteArray:
7624 case Type::VariableArray:
7625 case Type::FunctionProto:
7626 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007627 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007628
Chris Lattnerfd652912008-01-14 05:45:46 +00007629 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007630 {
7631 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007632 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7633 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007634 if (Unqualified) {
7635 LHSPointee = LHSPointee.getUnqualifiedType();
7636 RHSPointee = RHSPointee.getUnqualifiedType();
7637 }
7638 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7639 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007640 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007641 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007642 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007643 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007644 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007645 return getPointerType(ResultType);
7646 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007647 case Type::BlockPointer:
7648 {
7649 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007650 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7651 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007652 if (Unqualified) {
7653 LHSPointee = LHSPointee.getUnqualifiedType();
7654 RHSPointee = RHSPointee.getUnqualifiedType();
7655 }
7656 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7657 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007658 if (ResultType.isNull()) return QualType();
7659 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7660 return LHS;
7661 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7662 return RHS;
7663 return getBlockPointerType(ResultType);
7664 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007665 case Type::Atomic:
7666 {
7667 // Merge two pointer types, while trying to preserve typedef info
7668 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7669 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7670 if (Unqualified) {
7671 LHSValue = LHSValue.getUnqualifiedType();
7672 RHSValue = RHSValue.getUnqualifiedType();
7673 }
7674 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7675 Unqualified);
7676 if (ResultType.isNull()) return QualType();
7677 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7678 return LHS;
7679 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7680 return RHS;
7681 return getAtomicType(ResultType);
7682 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007683 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007684 {
7685 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7686 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7687 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7688 return QualType();
7689
7690 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7691 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007692 if (Unqualified) {
7693 LHSElem = LHSElem.getUnqualifiedType();
7694 RHSElem = RHSElem.getUnqualifiedType();
7695 }
7696
7697 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007698 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007699 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7700 return LHS;
7701 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7702 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007703 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7704 ArrayType::ArraySizeModifier(), 0);
7705 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7706 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007707 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7708 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007709 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7710 return LHS;
7711 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7712 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007713 if (LVAT) {
7714 // FIXME: This isn't correct! But tricky to implement because
7715 // the array's size has to be the size of LHS, but the type
7716 // has to be different.
7717 return LHS;
7718 }
7719 if (RVAT) {
7720 // FIXME: This isn't correct! But tricky to implement because
7721 // the array's size has to be the size of RHS, but the type
7722 // has to be different.
7723 return RHS;
7724 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007725 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7726 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007727 return getIncompleteArrayType(ResultType,
7728 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007729 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007730 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007731 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007732 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007733 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007734 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007735 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007736 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007737 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007738 case Type::Complex:
7739 // Distinct complex types are incompatible.
7740 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007741 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007742 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007743 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7744 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007745 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007746 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007747 case Type::ObjCObject: {
7748 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007749 // FIXME: This should be type compatibility, e.g. whether
7750 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007751 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7752 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7753 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007754 return LHS;
7755
Eli Friedman47f77112008-08-22 00:56:42 +00007756 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007757 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007758 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007759 if (OfBlockPointer) {
7760 if (canAssignObjCInterfacesInBlockPointer(
7761 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007762 RHS->getAs<ObjCObjectPointerType>(),
7763 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007764 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007765 return QualType();
7766 }
John McCall9dd450b2009-09-21 23:43:11 +00007767 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7768 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007769 return LHS;
7770
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007771 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007772 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007773 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007774
David Blaikie8a40f702012-01-17 06:56:22 +00007775 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007776}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007777
Fariborz Jahanian97676972011-09-28 21:52:05 +00007778bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7779 const FunctionProtoType *FromFunctionType,
7780 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007781 if (FromFunctionType->hasAnyConsumedParams() !=
7782 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007783 return false;
7784 FunctionProtoType::ExtProtoInfo FromEPI =
7785 FromFunctionType->getExtProtoInfo();
7786 FunctionProtoType::ExtProtoInfo ToEPI =
7787 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007788 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007789 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7790 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007791 return false;
7792 }
7793 return true;
7794}
7795
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007796/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7797/// 'RHS' attributes and returns the merged version; including for function
7798/// return types.
7799QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7800 QualType LHSCan = getCanonicalType(LHS),
7801 RHSCan = getCanonicalType(RHS);
7802 // If two types are identical, they are compatible.
7803 if (LHSCan == RHSCan)
7804 return LHS;
7805 if (RHSCan->isFunctionType()) {
7806 if (!LHSCan->isFunctionType())
7807 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007808 QualType OldReturnType =
7809 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007810 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007811 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007812 QualType ResReturnType =
7813 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7814 if (ResReturnType.isNull())
7815 return QualType();
7816 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7817 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7818 // In either case, use OldReturnType to build the new function type.
7819 const FunctionType *F = LHS->getAs<FunctionType>();
7820 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007821 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7822 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007823 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007824 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007825 return ResultType;
7826 }
7827 }
7828 return QualType();
7829 }
7830
7831 // If the qualifiers are different, the types can still be merged.
7832 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7833 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7834 if (LQuals != RQuals) {
7835 // If any of these qualifiers are different, we have a type mismatch.
7836 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7837 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7838 return QualType();
7839
7840 // Exactly one GC qualifier difference is allowed: __strong is
7841 // okay if the other type has no GC qualifier but is an Objective
7842 // C object pointer (i.e. implicitly strong by default). We fix
7843 // this by pretending that the unqualified type was actually
7844 // qualified __strong.
7845 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7846 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7847 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7848
7849 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7850 return QualType();
7851
7852 if (GC_L == Qualifiers::Strong)
7853 return LHS;
7854 if (GC_R == Qualifiers::Strong)
7855 return RHS;
7856 return QualType();
7857 }
7858
7859 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7860 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7861 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7862 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7863 if (ResQT == LHSBaseQT)
7864 return LHS;
7865 if (ResQT == RHSBaseQT)
7866 return RHS;
7867 }
7868 return QualType();
7869}
7870
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007871//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007872// Integer Predicates
7873//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007874
Jay Foad39c79802011-01-12 09:06:06 +00007875unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007876 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007877 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007878 if (T->isBooleanType())
7879 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007880 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007881 return (unsigned)getTypeSize(T);
7882}
7883
Abramo Bagnara13640492012-09-09 10:21:24 +00007884QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007885 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007886
7887 // Turn <4 x signed int> -> <4 x unsigned int>
7888 if (const VectorType *VTy = T->getAs<VectorType>())
7889 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007890 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007891
7892 // For enums, we return the unsigned version of the base type.
7893 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007894 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007895
7896 const BuiltinType *BTy = T->getAs<BuiltinType>();
7897 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007898 switch (BTy->getKind()) {
7899 case BuiltinType::Char_S:
7900 case BuiltinType::SChar:
7901 return UnsignedCharTy;
7902 case BuiltinType::Short:
7903 return UnsignedShortTy;
7904 case BuiltinType::Int:
7905 return UnsignedIntTy;
7906 case BuiltinType::Long:
7907 return UnsignedLongTy;
7908 case BuiltinType::LongLong:
7909 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007910 case BuiltinType::Int128:
7911 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007912 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007913 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007914 }
7915}
7916
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007917ASTMutationListener::~ASTMutationListener() { }
7918
Richard Smith1fa5d642013-05-11 05:45:24 +00007919void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7920 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007921
7922//===----------------------------------------------------------------------===//
7923// Builtin Type Computation
7924//===----------------------------------------------------------------------===//
7925
7926/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007927/// pointer over the consumed characters. This returns the resultant type. If
7928/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7929/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7930/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007931///
7932/// RequiresICE is filled in on return to indicate whether the value is required
7933/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007934static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007935 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007936 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007937 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007938 // Modifiers.
7939 int HowLong = 0;
7940 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007941 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007942
Chris Lattnerdc226c22010-10-01 22:42:38 +00007943 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007944 bool Done = false;
7945 while (!Done) {
7946 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007947 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007948 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007949 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007950 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007951 case 'S':
7952 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7953 assert(!Signed && "Can't use 'S' modifier multiple times!");
7954 Signed = true;
7955 break;
7956 case 'U':
7957 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007958 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007959 Unsigned = true;
7960 break;
7961 case 'L':
7962 assert(HowLong <= 2 && "Can't have LLLL modifier");
7963 ++HowLong;
7964 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007965 case 'W':
7966 // This modifier represents int64 type.
7967 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7968 switch (Context.getTargetInfo().getInt64Type()) {
7969 default:
7970 llvm_unreachable("Unexpected integer type");
7971 case TargetInfo::SignedLong:
7972 HowLong = 1;
7973 break;
7974 case TargetInfo::SignedLongLong:
7975 HowLong = 2;
7976 break;
7977 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007978 }
7979 }
7980
7981 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007982
Chris Lattnerecd79c62009-06-14 00:45:47 +00007983 // Read the base type.
7984 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007985 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007986 case 'v':
7987 assert(HowLong == 0 && !Signed && !Unsigned &&
7988 "Bad modifiers used with 'v'!");
7989 Type = Context.VoidTy;
7990 break;
Jack Carter24bef982013-08-15 15:16:57 +00007991 case 'h':
7992 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007993 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007994 Type = Context.HalfTy;
7995 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007996 case 'f':
7997 assert(HowLong == 0 && !Signed && !Unsigned &&
7998 "Bad modifiers used with 'f'!");
7999 Type = Context.FloatTy;
8000 break;
8001 case 'd':
8002 assert(HowLong < 2 && !Signed && !Unsigned &&
8003 "Bad modifiers used with 'd'!");
8004 if (HowLong)
8005 Type = Context.LongDoubleTy;
8006 else
8007 Type = Context.DoubleTy;
8008 break;
8009 case 's':
8010 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8011 if (Unsigned)
8012 Type = Context.UnsignedShortTy;
8013 else
8014 Type = Context.ShortTy;
8015 break;
8016 case 'i':
8017 if (HowLong == 3)
8018 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8019 else if (HowLong == 2)
8020 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8021 else if (HowLong == 1)
8022 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8023 else
8024 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8025 break;
8026 case 'c':
8027 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8028 if (Signed)
8029 Type = Context.SignedCharTy;
8030 else if (Unsigned)
8031 Type = Context.UnsignedCharTy;
8032 else
8033 Type = Context.CharTy;
8034 break;
8035 case 'b': // boolean
8036 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8037 Type = Context.BoolTy;
8038 break;
8039 case 'z': // size_t.
8040 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8041 Type = Context.getSizeType();
8042 break;
8043 case 'F':
8044 Type = Context.getCFConstantStringType();
8045 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008046 case 'G':
8047 Type = Context.getObjCIdType();
8048 break;
8049 case 'H':
8050 Type = Context.getObjCSelType();
8051 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008052 case 'M':
8053 Type = Context.getObjCSuperType();
8054 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008055 case 'a':
8056 Type = Context.getBuiltinVaListType();
8057 assert(!Type.isNull() && "builtin va list type not initialized!");
8058 break;
8059 case 'A':
8060 // This is a "reference" to a va_list; however, what exactly
8061 // this means depends on how va_list is defined. There are two
8062 // different kinds of va_list: ones passed by value, and ones
8063 // passed by reference. An example of a by-value va_list is
8064 // x86, where va_list is a char*. An example of by-ref va_list
8065 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8066 // we want this argument to be a char*&; for x86-64, we want
8067 // it to be a __va_list_tag*.
8068 Type = Context.getBuiltinVaListType();
8069 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008070 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008071 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008072 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008073 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008074 break;
8075 case 'V': {
8076 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008077 unsigned NumElements = strtoul(Str, &End, 10);
8078 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008079 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008080
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008081 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8082 RequiresICE, false);
8083 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008084
8085 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008086 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008087 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008088 break;
8089 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008090 case 'E': {
8091 char *End;
8092
8093 unsigned NumElements = strtoul(Str, &End, 10);
8094 assert(End != Str && "Missing vector size");
8095
8096 Str = End;
8097
8098 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8099 false);
8100 Type = Context.getExtVectorType(ElementType, NumElements);
8101 break;
8102 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008103 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008104 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8105 false);
8106 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008107 Type = Context.getComplexType(ElementType);
8108 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008109 }
8110 case 'Y' : {
8111 Type = Context.getPointerDiffType();
8112 break;
8113 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008114 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008115 Type = Context.getFILEType();
8116 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008117 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008118 return QualType();
8119 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008120 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008121 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008122 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008123 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008124 else
8125 Type = Context.getjmp_bufType();
8126
Mike Stump2adb4da2009-07-28 23:47:15 +00008127 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008128 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008129 return QualType();
8130 }
8131 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008132 case 'K':
8133 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8134 Type = Context.getucontext_tType();
8135
8136 if (Type.isNull()) {
8137 Error = ASTContext::GE_Missing_ucontext;
8138 return QualType();
8139 }
8140 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008141 case 'p':
8142 Type = Context.getProcessIDType();
8143 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008144 }
Mike Stump11289f42009-09-09 15:08:12 +00008145
Chris Lattnerdc226c22010-10-01 22:42:38 +00008146 // If there are modifiers and if we're allowed to parse them, go for it.
8147 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008148 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008149 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008150 default: Done = true; --Str; break;
8151 case '*':
8152 case '&': {
8153 // Both pointers and references can have their pointee types
8154 // qualified with an address space.
8155 char *End;
8156 unsigned AddrSpace = strtoul(Str, &End, 10);
8157 if (End != Str && AddrSpace != 0) {
8158 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8159 Str = End;
8160 }
8161 if (c == '*')
8162 Type = Context.getPointerType(Type);
8163 else
8164 Type = Context.getLValueReferenceType(Type);
8165 break;
8166 }
8167 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8168 case 'C':
8169 Type = Type.withConst();
8170 break;
8171 case 'D':
8172 Type = Context.getVolatileType(Type);
8173 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008174 case 'R':
8175 Type = Type.withRestrict();
8176 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008177 }
8178 }
Chris Lattner84733392010-10-01 07:13:18 +00008179
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008180 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008181 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008182
Chris Lattnerecd79c62009-06-14 00:45:47 +00008183 return Type;
8184}
8185
8186/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008187QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008188 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008189 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008190 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008191
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008192 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008193
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008194 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008195 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008196 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8197 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008198 if (Error != GE_None)
8199 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008200
8201 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8202
Chris Lattnerecd79c62009-06-14 00:45:47 +00008203 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008204 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008205 if (Error != GE_None)
8206 return QualType();
8207
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008208 // If this argument is required to be an IntegerConstantExpression and the
8209 // caller cares, fill in the bitmask we return.
8210 if (RequiresICE && IntegerConstantArgs)
8211 *IntegerConstantArgs |= 1 << ArgTypes.size();
8212
Chris Lattnerecd79c62009-06-14 00:45:47 +00008213 // Do array -> pointer decay. The builtin should use the decayed type.
8214 if (Ty->isArrayType())
8215 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008216
Chris Lattnerecd79c62009-06-14 00:45:47 +00008217 ArgTypes.push_back(Ty);
8218 }
8219
David Majnemerba3e5ec2015-03-13 18:26:17 +00008220 if (Id == Builtin::BI__GetExceptionInfo)
8221 return QualType();
8222
Chris Lattnerecd79c62009-06-14 00:45:47 +00008223 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8224 "'.' should only occur at end of builtin type list!");
8225
Reid Kleckner78af0702013-08-27 23:08:25 +00008226 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008227 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8228
8229 bool Variadic = (TypeStr[0] == '.');
8230
8231 // We really shouldn't be making a no-proto type here, especially in C++.
8232 if (ArgTypes.empty() && Variadic)
8233 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008234
John McCalldb40c7f2010-12-14 08:05:40 +00008235 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008236 EPI.ExtInfo = EI;
8237 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008238
Jordan Rose5c382722013-03-08 21:51:21 +00008239 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008240}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008241
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008242static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8243 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008244 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008245 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008246
Rafael Espindola3ae00052013-05-13 00:12:11 +00008247 GVALinkage External = GVA_StrongExternal;
8248 switch (FD->getTemplateSpecializationKind()) {
8249 case TSK_Undeclared:
8250 case TSK_ExplicitSpecialization:
8251 External = GVA_StrongExternal;
8252 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008253
Rafael Espindola3ae00052013-05-13 00:12:11 +00008254 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008255 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008256
David Majnemerc3d07332014-05-15 06:25:57 +00008257 // C++11 [temp.explicit]p10:
8258 // [ Note: The intent is that an inline function that is the subject of
8259 // an explicit instantiation declaration will still be implicitly
8260 // instantiated when used so that the body can be considered for
8261 // inlining, but that no out-of-line copy of the inline function would be
8262 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008263 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008264 return GVA_AvailableExternally;
8265
Rafael Espindola3ae00052013-05-13 00:12:11 +00008266 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008267 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008268 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008269 }
8270
8271 if (!FD->isInlined())
8272 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008273
David Majnemer3f021502015-10-08 04:53:31 +00008274 if ((!Context.getLangOpts().CPlusPlus &&
8275 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008276 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008277 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008278 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8279
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008280 // GNU or C99 inline semantics. Determine whether this symbol should be
8281 // externally visible.
8282 if (FD->isInlineDefinitionExternallyVisible())
8283 return External;
8284
8285 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008286 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008287 }
8288
David Majnemer54e3ba52014-04-02 23:17:29 +00008289 // Functions specified with extern and inline in -fms-compatibility mode
8290 // forcibly get emitted. While the body of the function cannot be later
8291 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008292 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008293 return GVA_StrongODR;
8294
David Majnemer27d69db2014-04-28 22:17:59 +00008295 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008296}
8297
Artem Belevich7b41f702015-09-23 17:44:53 +00008298static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008299 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8300 // dllexport/dllimport on inline functions.
8301 if (D->hasAttr<DLLImportAttr>()) {
8302 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8303 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008304 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008305 if (L == GVA_DiscardableODR)
8306 return GVA_StrongODR;
8307 }
8308 return L;
8309}
8310
8311GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008312 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8313 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008314}
8315
8316static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8317 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008318 if (!VD->isExternallyVisible())
8319 return GVA_Internal;
8320
David Majnemer27d69db2014-04-28 22:17:59 +00008321 if (VD->isStaticLocal()) {
8322 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8323 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8324 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8325 LexicalContext = LexicalContext->getLexicalParent();
8326
Richard Smith9e2341d2015-03-23 03:25:59 +00008327 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008328 // enclosing function.
8329 if (LexicalContext)
8330 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008331 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008332
8333 // GVA_StrongODR function linkage is stronger than what we need,
8334 // downgrade to GVA_DiscardableODR.
8335 // This allows us to discard the variable if we never end up needing it.
8336 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8337 : StaticLocalLinkage;
8338 }
8339
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008340 // MSVC treats in-class initialized static data members as definitions.
8341 // By giving them non-strong linkage, out-of-line definitions won't
8342 // cause link errors.
8343 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8344 return GVA_DiscardableODR;
8345
Richard Smith8809a0c2013-09-27 20:14:12 +00008346 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008347 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008348 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008349
David Majnemer6d1780c2015-07-17 23:36:49 +00008350 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008351 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8352 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008353 ? GVA_StrongODR
8354 : GVA_StrongExternal;
8355
Rafael Espindola3ae00052013-05-13 00:12:11 +00008356 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008357 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008358
David Majnemer27d69db2014-04-28 22:17:59 +00008359 case TSK_ExplicitInstantiationDeclaration:
8360 return GVA_AvailableExternally;
8361
Rafael Espindola3ae00052013-05-13 00:12:11 +00008362 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008363 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008364 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008365
8366 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008367}
8368
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008369GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008370 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8371 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008372}
8373
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008374bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008375 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8376 if (!VD->isFileVarDecl())
8377 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008378 // Global named register variables (GNU extension) are never emitted.
8379 if (VD->getStorageClass() == SC_Register)
8380 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008381 if (VD->getDescribedVarTemplate() ||
8382 isa<VarTemplatePartialSpecializationDecl>(VD))
8383 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008384 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8385 // We never need to emit an uninstantiated function template.
8386 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8387 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008388 } else if (isa<OMPThreadPrivateDecl>(D))
8389 return true;
8390 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008391 return false;
8392
8393 // If this is a member of a class template, we do not need to emit it.
8394 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008395 return false;
8396
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008397 // Weak references don't produce any output by themselves.
8398 if (D->hasAttr<WeakRefAttr>())
8399 return false;
8400
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008401 // Aliases and used decls are required.
8402 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8403 return true;
8404
8405 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8406 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008407 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008408 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008409
8410 // Constructors and destructors are required.
8411 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8412 return true;
8413
John McCall6bd2a892013-01-25 22:31:03 +00008414 // The key function for a class is required. This rule only comes
8415 // into play when inline functions can be key functions, though.
8416 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8417 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8418 const CXXRecordDecl *RD = MD->getParent();
8419 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8420 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8421 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8422 return true;
8423 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008424 }
8425 }
8426
8427 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8428
8429 // static, static inline, always_inline, and extern inline functions can
8430 // always be deferred. Normal inline functions can be deferred in C99/C++.
8431 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008432 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8433 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008434 return false;
8435 return true;
8436 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008437
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008438 const VarDecl *VD = cast<VarDecl>(D);
8439 assert(VD->isFileVarDecl() && "Expected file scoped var");
8440
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008441 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8442 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008443 return false;
8444
Richard Smitha0e5e542012-11-12 21:38:00 +00008445 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008446 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008447 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8448 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008449 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008450
Richard Smitha0e5e542012-11-12 21:38:00 +00008451 // Variables that have destruction with side-effects are required.
8452 if (VD->getType().isDestructedType())
8453 return true;
8454
8455 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008456 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8457 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008458 return true;
8459
8460 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008461}
Charles Davis53c59df2010-08-16 03:33:14 +00008462
Reid Kleckner78af0702013-08-27 23:08:25 +00008463CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8464 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008465 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008466 if (IsCXXMethod)
8467 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008468
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008469 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8470
8471 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008472}
8473
Jay Foad39c79802011-01-12 09:06:06 +00008474bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008475 // Pass through to the C++ ABI object
8476 return ABI->isNearlyEmpty(RD);
8477}
8478
Reid Kleckner96f8f932014-02-05 17:27:08 +00008479VTableContextBase *ASTContext::getVTableContext() {
8480 if (!VTContext.get()) {
8481 if (Target->getCXXABI().isMicrosoft())
8482 VTContext.reset(new MicrosoftVTableContext(*this));
8483 else
8484 VTContext.reset(new ItaniumVTableContext(*this));
8485 }
8486 return VTContext.get();
8487}
8488
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008489MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008490 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008491 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008492 case TargetCXXABI::GenericItanium:
8493 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008494 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008495 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008496 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008497 case TargetCXXABI::WebAssembly:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008498 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008499 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008500 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008501 }
David Blaikie83d382b2011-09-23 05:06:16 +00008502 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008503}
8504
Charles Davis53c59df2010-08-16 03:33:14 +00008505CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008506
8507size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008508 return ASTRecordLayouts.getMemorySize() +
8509 llvm::capacity_in_bytes(ObjCLayouts) +
8510 llvm::capacity_in_bytes(KeyFunctions) +
8511 llvm::capacity_in_bytes(ObjCImpls) +
8512 llvm::capacity_in_bytes(BlockVarCopyInits) +
8513 llvm::capacity_in_bytes(DeclAttrs) +
8514 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8515 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8516 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8517 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8518 llvm::capacity_in_bytes(OverriddenMethods) +
8519 llvm::capacity_in_bytes(Types) +
8520 llvm::capacity_in_bytes(VariableArrayTypes) +
8521 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008522}
Ted Kremenek540017e2011-10-06 05:00:56 +00008523
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008524/// getIntTypeForBitwidth -
8525/// sets integer QualTy according to specified details:
8526/// bitwidth, signed/unsigned.
8527/// Returns empty type if there is no appropriate target types.
8528QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8529 unsigned Signed) const {
8530 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8531 CanQualType QualTy = getFromTargetType(Ty);
8532 if (!QualTy && DestWidth == 128)
8533 return Signed ? Int128Ty : UnsignedInt128Ty;
8534 return QualTy;
8535}
8536
8537/// getRealTypeForBitwidth -
8538/// sets floating point QualTy according to specified bitwidth.
8539/// Returns empty type if there is no appropriate target types.
8540QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8541 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8542 switch (Ty) {
8543 case TargetInfo::Float:
8544 return FloatTy;
8545 case TargetInfo::Double:
8546 return DoubleTy;
8547 case TargetInfo::LongDouble:
8548 return LongDoubleTy;
8549 case TargetInfo::NoFloat:
8550 return QualType();
8551 }
8552
8553 llvm_unreachable("Unhandled TargetInfo::RealType value");
8554}
8555
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008556void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8557 if (Number > 1)
8558 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008559}
8560
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008561unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8562 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8563 MangleNumbers.find(ND);
8564 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008565}
8566
David Majnemer2206bf52014-03-05 08:57:59 +00008567void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8568 if (Number > 1)
8569 StaticLocalNumbers[VD] = Number;
8570}
8571
8572unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8573 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8574 StaticLocalNumbers.find(VD);
8575 return I != StaticLocalNumbers.end() ? I->second : 1;
8576}
8577
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008578MangleNumberingContext &
8579ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008580 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8581 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8582 if (!MCtx)
8583 MCtx = createMangleNumberingContext();
8584 return *MCtx;
8585}
8586
8587MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8588 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008589}
8590
David Majnemere7a818f2015-03-06 18:53:55 +00008591const CXXConstructorDecl *
8592ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8593 return ABI->getCopyConstructorForExceptionObject(
8594 cast<CXXRecordDecl>(RD->getFirstDecl()));
8595}
8596
8597void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8598 CXXConstructorDecl *CD) {
8599 return ABI->addCopyConstructorForExceptionObject(
8600 cast<CXXRecordDecl>(RD->getFirstDecl()),
8601 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8602}
8603
David Majnemerdfa6d202015-03-11 18:36:39 +00008604void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8605 unsigned ParmIdx, Expr *DAE) {
8606 ABI->addDefaultArgExprForConstructor(
8607 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8608}
8609
8610Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8611 unsigned ParmIdx) {
8612 return ABI->getDefaultArgExprForConstructor(
8613 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8614}
8615
David Majnemer00350522015-08-31 18:48:39 +00008616void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8617 TypedefNameDecl *DD) {
8618 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8619}
8620
8621TypedefNameDecl *
8622ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8623 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8624}
8625
8626void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8627 DeclaratorDecl *DD) {
8628 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8629}
8630
8631DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8632 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8633}
8634
Ted Kremenek540017e2011-10-06 05:00:56 +00008635void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8636 ParamIndices[D] = index;
8637}
8638
8639unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8640 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8641 assert(I != ParamIndices.end() &&
8642 "ParmIndices lacks entry set by ParmVarDecl");
8643 return I->second;
8644}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008645
Richard Smithe6c01442013-06-05 00:46:14 +00008646APValue *
8647ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8648 bool MayCreate) {
8649 assert(E && E->getStorageDuration() == SD_Static &&
8650 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008651 if (MayCreate) {
8652 APValue *&MTVI = MaterializedTemporaryValues[E];
8653 if (!MTVI)
8654 MTVI = new (*this) APValue;
8655 return MTVI;
8656 }
Richard Smithe6c01442013-06-05 00:46:14 +00008657
David Majnemer2dcef9e2015-08-13 23:50:15 +00008658 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008659}
8660
Fariborz Jahanian615de762013-05-28 17:37:39 +00008661bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8662 const llvm::Triple &T = getTargetInfo().getTriple();
8663 if (!T.isOSDarwin())
8664 return false;
8665
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008666 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8667 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8668 return false;
8669
Fariborz Jahanian615de762013-05-28 17:37:39 +00008670 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8671 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8672 uint64_t Size = sizeChars.getQuantity();
8673 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8674 unsigned Align = alignChars.getQuantity();
8675 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8676 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8677}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008678
8679namespace {
8680
8681 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8682 /// parents as defined by the \c RecursiveASTVisitor.
8683 ///
8684 /// Note that the relationship described here is purely in terms of AST
8685 /// traversal - there are other relationships (for example declaration context)
8686 /// in the AST that are better modeled by special matchers.
8687 ///
8688 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8689 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8690
8691 public:
8692 /// \brief Builds and returns the translation unit's parent map.
8693 ///
8694 /// The caller takes ownership of the returned \c ParentMap.
8695 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8696 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8697 Visitor.TraverseDecl(&TU);
8698 return Visitor.Parents;
8699 }
8700
8701 private:
8702 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8703
8704 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8705 }
8706
8707 bool shouldVisitTemplateInstantiations() const {
8708 return true;
8709 }
8710 bool shouldVisitImplicitCode() const {
8711 return true;
8712 }
8713 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8714 // are not triggered during data recursion.
8715 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8716 return false;
8717 }
8718
8719 template <typename T>
8720 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008721 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008722 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008723 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008724 // FIXME: Currently we add the same parent multiple times, but only
8725 // when no memoization data is available for the type.
8726 // For example when we visit all subexpressions of template
8727 // instantiations; this is suboptimal, but benign: the only way to
8728 // visit those is with hasAncestor / hasParent, and those do not create
8729 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008730 // The plan is to enable DynTypedNode to be storable in a map or hash
8731 // map. The main problem there is to implement hash functions /
8732 // comparison operators for all types that DynTypedNode supports that
8733 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008734 auto &NodeOrVector = (*Parents)[Node];
8735 if (NodeOrVector.isNull()) {
8736 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008737 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008738 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8739 auto *Node =
8740 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8741 auto *Vector = new ASTContext::ParentVector(1, *Node);
8742 NodeOrVector = Vector;
8743 delete Node;
8744 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008745 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008746
8747 auto *Vector =
8748 NodeOrVector.template get<ASTContext::ParentVector *>();
8749 // Skip duplicates for types that have memoization data.
8750 // We must check that the type has memoization data before calling
8751 // std::find() because DynTypedNode::operator== can't compare all
8752 // types.
8753 bool Found = ParentStack.back().getMemoizationData() &&
8754 std::find(Vector->begin(), Vector->end(),
8755 ParentStack.back()) != Vector->end();
8756 if (!Found)
8757 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008758 }
8759 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008760 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8761 bool Result = (this ->* traverse) (Node);
8762 ParentStack.pop_back();
8763 return Result;
8764 }
8765
8766 bool TraverseDecl(Decl *DeclNode) {
8767 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8768 }
8769
8770 bool TraverseStmt(Stmt *StmtNode) {
8771 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8772 }
8773
8774 ASTContext::ParentMap *Parents;
8775 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8776
8777 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8778 };
8779
8780} // end namespace
8781
Benjamin Kramer07935292014-10-04 17:01:26 +00008782ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008783ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8784 assert(Node.getMemoizationData() &&
8785 "Invariant broken: only nodes that support memoization may be "
8786 "used in the parent map.");
8787 if (!AllParents) {
8788 // We always need to run over the whole translation unit, as
8789 // hasAncestor can escape any subtree.
8790 AllParents.reset(
8791 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8792 }
8793 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8794 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008795 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008796 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008797 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8798 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008799 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008800 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008801}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008802
8803bool
8804ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8805 const ObjCMethodDecl *MethodImpl) {
8806 // No point trying to match an unavailable/deprecated mothod.
8807 if (MethodDecl->hasAttr<UnavailableAttr>()
8808 || MethodDecl->hasAttr<DeprecatedAttr>())
8809 return false;
8810 if (MethodDecl->getObjCDeclQualifier() !=
8811 MethodImpl->getObjCDeclQualifier())
8812 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008813 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008814 return false;
8815
8816 if (MethodDecl->param_size() != MethodImpl->param_size())
8817 return false;
8818
8819 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8820 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8821 EF = MethodDecl->param_end();
8822 IM != EM && IF != EF; ++IM, ++IF) {
8823 const ParmVarDecl *DeclVar = (*IF);
8824 const ParmVarDecl *ImplVar = (*IM);
8825 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8826 return false;
8827 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8828 return false;
8829 }
8830 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8831
8832}
Richard Smith053f6c62014-05-16 23:01:30 +00008833
8834// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8835// doesn't include ASTContext.h
8836template
8837clang::LazyGenerationalUpdatePtr<
8838 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8839clang::LazyGenerationalUpdatePtr<
8840 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8841 const clang::ASTContext &Ctx, Decl *Value);