blob: dd47d43ccb13bddaf86bee7179c2a27d3faf9cf6 [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
Craig Topper6a8c1512015-10-22 01:56:18 +00003641static void
3642SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003643 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003644 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003645
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003646 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003647 for (ObjCProtocolDecl *&P : Protocols)
3648 P = P->getCanonicalDecl();
3649
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003650 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003651 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3652 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003653}
3654
John McCall8b07ec22010-05-15 11:32:37 +00003655QualType ASTContext::getObjCObjectType(QualType BaseType,
3656 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003657 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003658 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003659 llvm::makeArrayRef(Protocols, NumProtocols),
3660 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003661}
3662
3663QualType ASTContext::getObjCObjectType(
3664 QualType baseType,
3665 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003666 ArrayRef<ObjCProtocolDecl *> protocols,
3667 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003668 // If the base type is an interface and there aren't any protocols or
3669 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003670 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3671 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003672 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003673
3674 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003675 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003676 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003677 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003678 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3679 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003680
Douglas Gregore9d95f12015-07-07 03:57:35 +00003681 // Determine the type arguments to be used for canonicalization,
3682 // which may be explicitly specified here or written on the base
3683 // type.
3684 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3685 if (effectiveTypeArgs.empty()) {
3686 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3687 effectiveTypeArgs = baseObject->getTypeArgs();
3688 }
John McCallfc93cf92009-10-22 22:37:11 +00003689
Douglas Gregore9d95f12015-07-07 03:57:35 +00003690 // Build the canonical type, which has the canonical base type and a
3691 // sorted-and-uniqued list of protocols and the type arguments
3692 // canonicalized.
3693 QualType canonical;
3694 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3695 effectiveTypeArgs.end(),
3696 [&](QualType type) {
3697 return type.isCanonical();
3698 });
3699 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3700 protocols.size());
3701 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3702 // Determine the canonical type arguments.
3703 ArrayRef<QualType> canonTypeArgs;
3704 SmallVector<QualType, 4> canonTypeArgsVec;
3705 if (!typeArgsAreCanonical) {
3706 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3707 for (auto typeArg : effectiveTypeArgs)
3708 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3709 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003710 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003711 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003712 }
3713
Douglas Gregore9d95f12015-07-07 03:57:35 +00003714 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3715 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3716 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003717 canonProtocolsVec.append(protocols.begin(), protocols.end());
3718 SortAndUniqueProtocols(canonProtocolsVec);
3719 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003720 } else {
3721 canonProtocols = protocols;
3722 }
3723
3724 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003725 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003726
John McCallfc93cf92009-10-22 22:37:11 +00003727 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003728 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3729 }
3730
Douglas Gregore9d95f12015-07-07 03:57:35 +00003731 unsigned size = sizeof(ObjCObjectTypeImpl);
3732 size += typeArgs.size() * sizeof(QualType);
3733 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3734 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003735 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003736 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3737 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003738
3739 Types.push_back(T);
3740 ObjCObjectTypes.InsertNode(T, InsertPos);
3741 return QualType(T, 0);
3742}
3743
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003744/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3745/// protocol list adopt all protocols in QT's qualified-id protocol
3746/// list.
3747bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3748 ObjCInterfaceDecl *IC) {
3749 if (!QT->isObjCQualifiedIdType())
3750 return false;
3751
3752 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3753 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003754 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003755 if (!IC->ClassImplementsProtocol(Proto, false))
3756 return false;
3757 }
3758 return true;
3759 }
3760 return false;
3761}
3762
3763/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3764/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3765/// of protocols.
3766bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3767 ObjCInterfaceDecl *IDecl) {
3768 if (!QT->isObjCQualifiedIdType())
3769 return false;
3770 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3771 if (!OPT)
3772 return false;
3773 if (!IDecl->hasDefinition())
3774 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003775 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3776 CollectInheritedProtocols(IDecl, InheritedProtocols);
3777 if (InheritedProtocols.empty())
3778 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003779 // Check that if every protocol in list of id<plist> conforms to a protcol
3780 // of IDecl's, then bridge casting is ok.
3781 bool Conforms = false;
3782 for (auto *Proto : OPT->quals()) {
3783 Conforms = false;
3784 for (auto *PI : InheritedProtocols) {
3785 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3786 Conforms = true;
3787 break;
3788 }
3789 }
3790 if (!Conforms)
3791 break;
3792 }
3793 if (Conforms)
3794 return true;
3795
Aaron Ballman83731462014-03-17 16:14:00 +00003796 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003797 // If both the right and left sides have qualifiers.
3798 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003799 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003800 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003801 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003802 break;
3803 }
3804 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003805 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003806 }
3807 return true;
3808}
3809
John McCall8b07ec22010-05-15 11:32:37 +00003810/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3811/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003812QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003813 llvm::FoldingSetNodeID ID;
3814 ObjCObjectPointerType::Profile(ID, ObjectT);
3815
Craig Topper36250ad2014-05-12 05:36:57 +00003816 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003817 if (ObjCObjectPointerType *QT =
3818 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3819 return QualType(QT, 0);
3820
3821 // Find the canonical object type.
3822 QualType Canonical;
3823 if (!ObjectT.isCanonical()) {
3824 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3825
3826 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003827 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3828 }
3829
Douglas Gregorf85bee62010-02-08 22:59:26 +00003830 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003831 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3832 ObjCObjectPointerType *QType =
3833 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003834
Steve Narofffb4330f2009-06-17 22:40:22 +00003835 Types.push_back(QType);
3836 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003837 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003838}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003839
Douglas Gregor1c283312010-08-11 12:19:30 +00003840/// getObjCInterfaceType - Return the unique reference to the type for the
3841/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003842QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3843 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003844 if (Decl->TypeForDecl)
3845 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003846
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003847 if (PrevDecl) {
3848 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3849 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3850 return QualType(PrevDecl->TypeForDecl, 0);
3851 }
3852
Douglas Gregor7671e532011-12-16 16:34:57 +00003853 // Prefer the definition, if there is one.
3854 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3855 Decl = Def;
3856
Douglas Gregor1c283312010-08-11 12:19:30 +00003857 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3858 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3859 Decl->TypeForDecl = T;
3860 Types.push_back(T);
3861 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003862}
3863
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003864/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3865/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003866/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003867/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003868/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003869QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003870 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003871 if (tofExpr->isTypeDependent()) {
3872 llvm::FoldingSetNodeID ID;
3873 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003874
Craig Topper36250ad2014-05-12 05:36:57 +00003875 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003876 DependentTypeOfExprType *Canon
3877 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3878 if (Canon) {
3879 // We already have a "canonical" version of an identical, dependent
3880 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003881 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003882 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003883 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003884 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003885 Canon
3886 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003887 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3888 toe = Canon;
3889 }
3890 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003891 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003892 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003893 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003894 Types.push_back(toe);
3895 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003896}
3897
Steve Naroffa773cd52007-08-01 18:02:17 +00003898/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003899/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003900/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003901/// an issue. This doesn't affect the type checker, since it operates
3902/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003903QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003904 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003905 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003906 Types.push_back(tot);
3907 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003908}
3909
Anders Carlssonad6bd352009-06-24 21:24:56 +00003910
Richard Smith8eb1d322014-06-05 20:13:13 +00003911/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3912/// nodes. This would never be helpful, since each such type has its own
3913/// expression, and would not give a significant memory saving, since there
3914/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003915QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003916 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003917
3918 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003919 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003920 // unique dependent type. Two such decltype-specifiers refer to the same
3921 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003922 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003923 llvm::FoldingSetNodeID ID;
3924 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003925
Craig Topper36250ad2014-05-12 05:36:57 +00003926 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003927 DependentDecltypeType *Canon
3928 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003929 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003930 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003931 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003932 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003933 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003934 dt = new (*this, TypeAlignment)
3935 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003936 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003937 dt = new (*this, TypeAlignment)
3938 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003939 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003940 Types.push_back(dt);
3941 return QualType(dt, 0);
3942}
3943
Alexis Hunte852b102011-05-24 22:41:36 +00003944/// getUnaryTransformationType - We don't unique these, since the memory
3945/// savings are minimal and these are rare.
3946QualType ASTContext::getUnaryTransformType(QualType BaseType,
3947 QualType UnderlyingType,
3948 UnaryTransformType::UTTKind Kind)
3949 const {
3950 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003951 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3952 Kind,
3953 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003954 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003955 Types.push_back(Ty);
3956 return QualType(Ty, 0);
3957}
3958
Richard Smith2a7d4812013-05-04 07:00:32 +00003959/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3960/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3961/// canonical deduced-but-dependent 'auto' type.
3962QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003963 bool IsDependent) const {
3964 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003965 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003966
Richard Smith2a7d4812013-05-04 07:00:32 +00003967 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003968 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003969 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003970 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003971 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3972 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003973
Richard Smith74aeef52013-04-26 16:15:35 +00003974 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003975 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003976 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003977 Types.push_back(AT);
3978 if (InsertPos)
3979 AutoTypes.InsertNode(AT, InsertPos);
3980 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003981}
3982
Eli Friedman0dfb8892011-10-06 23:00:33 +00003983/// getAtomicType - Return the uniqued reference to the atomic type for
3984/// the given value type.
3985QualType ASTContext::getAtomicType(QualType T) const {
3986 // Unique pointers, to guarantee there is only one pointer of a particular
3987 // structure.
3988 llvm::FoldingSetNodeID ID;
3989 AtomicType::Profile(ID, T);
3990
Craig Topper36250ad2014-05-12 05:36:57 +00003991 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003992 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3993 return QualType(AT, 0);
3994
3995 // If the atomic value type isn't canonical, this won't be a canonical type
3996 // either, so fill in the canonical type field.
3997 QualType Canonical;
3998 if (!T.isCanonical()) {
3999 Canonical = getAtomicType(getCanonicalType(T));
4000
4001 // Get the new insert position for the node we care about.
4002 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004003 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004004 }
4005 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4006 Types.push_back(New);
4007 AtomicTypes.InsertNode(New, InsertPos);
4008 return QualType(New, 0);
4009}
4010
Richard Smith02e85f32011-04-14 22:09:26 +00004011/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4012QualType ASTContext::getAutoDeductType() const {
4013 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004014 AutoDeductTy = QualType(
4015 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004016 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004017 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004018 return AutoDeductTy;
4019}
4020
4021/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4022QualType ASTContext::getAutoRRefDeductType() const {
4023 if (AutoRRefDeductTy.isNull())
4024 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4025 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4026 return AutoRRefDeductTy;
4027}
4028
Chris Lattnerfb072462007-01-23 05:45:31 +00004029/// getTagDeclType - Return the unique reference to the type for the
4030/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004031QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004032 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004033 // FIXME: What is the design on getTagDeclType when it requires casting
4034 // away const? mutable?
4035 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004036}
4037
Mike Stump11289f42009-09-09 15:08:12 +00004038/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4039/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4040/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004041CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004042 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004043}
Chris Lattnerfb072462007-01-23 05:45:31 +00004044
Hans Wennborg27541db2011-10-27 08:29:09 +00004045/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4046CanQualType ASTContext::getIntMaxType() const {
4047 return getFromTargetType(Target->getIntMaxType());
4048}
4049
4050/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4051CanQualType ASTContext::getUIntMaxType() const {
4052 return getFromTargetType(Target->getUIntMaxType());
4053}
4054
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004055/// getSignedWCharType - Return the type of "signed wchar_t".
4056/// Used when in C++, as a GCC extension.
4057QualType ASTContext::getSignedWCharType() const {
4058 // FIXME: derive from "Target" ?
4059 return WCharTy;
4060}
4061
4062/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4063/// Used when in C++, as a GCC extension.
4064QualType ASTContext::getUnsignedWCharType() const {
4065 // FIXME: derive from "Target" ?
4066 return UnsignedIntTy;
4067}
4068
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004069QualType ASTContext::getIntPtrType() const {
4070 return getFromTargetType(Target->getIntPtrType());
4071}
4072
4073QualType ASTContext::getUIntPtrType() const {
4074 return getCorrespondingUnsignedType(getIntPtrType());
4075}
4076
Hans Wennborg27541db2011-10-27 08:29:09 +00004077/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004078/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4079QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004080 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004081}
4082
Eli Friedman4e91899e2012-11-27 02:58:24 +00004083/// \brief Return the unique type for "pid_t" defined in
4084/// <sys/types.h>. We need this to compute the correct type for vfork().
4085QualType ASTContext::getProcessIDType() const {
4086 return getFromTargetType(Target->getProcessIDType());
4087}
4088
Chris Lattnera21ad802008-04-02 05:18:44 +00004089//===----------------------------------------------------------------------===//
4090// Type Operators
4091//===----------------------------------------------------------------------===//
4092
Jay Foad39c79802011-01-12 09:06:06 +00004093CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004094 // Push qualifiers into arrays, and then discard any remaining
4095 // qualifiers.
4096 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004097 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004098 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004099 QualType Result;
4100 if (isa<ArrayType>(Ty)) {
4101 Result = getArrayDecayedType(QualType(Ty,0));
4102 } else if (isa<FunctionType>(Ty)) {
4103 Result = getPointerType(QualType(Ty, 0));
4104 } else {
4105 Result = QualType(Ty, 0);
4106 }
4107
4108 return CanQualType::CreateUnsafe(Result);
4109}
4110
John McCall6c9dd522011-01-18 07:41:22 +00004111QualType ASTContext::getUnqualifiedArrayType(QualType type,
4112 Qualifiers &quals) {
4113 SplitQualType splitType = type.getSplitUnqualifiedType();
4114
4115 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4116 // the unqualified desugared type and then drops it on the floor.
4117 // We then have to strip that sugar back off with
4118 // getUnqualifiedDesugaredType(), which is silly.
4119 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004120 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004121
4122 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004123 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004124 quals = splitType.Quals;
4125 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004126 }
4127
John McCall6c9dd522011-01-18 07:41:22 +00004128 // Otherwise, recurse on the array's element type.
4129 QualType elementType = AT->getElementType();
4130 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4131
4132 // If that didn't change the element type, AT has no qualifiers, so we
4133 // can just use the results in splitType.
4134 if (elementType == unqualElementType) {
4135 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004136 quals = splitType.Quals;
4137 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004138 }
4139
4140 // Otherwise, add in the qualifiers from the outermost type, then
4141 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004142 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004143
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004144 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004145 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004146 CAT->getSizeModifier(), 0);
4147 }
4148
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004149 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004150 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004151 }
4152
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004153 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004154 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004155 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004156 VAT->getSizeModifier(),
4157 VAT->getIndexTypeCVRQualifiers(),
4158 VAT->getBracketsRange());
4159 }
4160
4161 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004162 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004163 DSAT->getSizeModifier(), 0,
4164 SourceRange());
4165}
4166
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004167/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4168/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4169/// they point to and return true. If T1 and T2 aren't pointer types
4170/// or pointer-to-member types, or if they are not similar at this
4171/// level, returns false and leaves T1 and T2 unchanged. Top-level
4172/// qualifiers on T1 and T2 are ignored. This function will typically
4173/// be called in a loop that successively "unwraps" pointer and
4174/// pointer-to-member types to compare them at each level.
4175bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4176 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4177 *T2PtrType = T2->getAs<PointerType>();
4178 if (T1PtrType && T2PtrType) {
4179 T1 = T1PtrType->getPointeeType();
4180 T2 = T2PtrType->getPointeeType();
4181 return true;
4182 }
4183
4184 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4185 *T2MPType = T2->getAs<MemberPointerType>();
4186 if (T1MPType && T2MPType &&
4187 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4188 QualType(T2MPType->getClass(), 0))) {
4189 T1 = T1MPType->getPointeeType();
4190 T2 = T2MPType->getPointeeType();
4191 return true;
4192 }
4193
David Blaikiebbafb8a2012-03-11 07:00:24 +00004194 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004195 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4196 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4197 if (T1OPType && T2OPType) {
4198 T1 = T1OPType->getPointeeType();
4199 T2 = T2OPType->getPointeeType();
4200 return true;
4201 }
4202 }
4203
4204 // FIXME: Block pointers, too?
4205
4206 return false;
4207}
4208
Jay Foad39c79802011-01-12 09:06:06 +00004209DeclarationNameInfo
4210ASTContext::getNameForTemplate(TemplateName Name,
4211 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004212 switch (Name.getKind()) {
4213 case TemplateName::QualifiedTemplate:
4214 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004215 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004216 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4217 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004218
John McCalld9dfe3a2011-06-30 08:33:18 +00004219 case TemplateName::OverloadedTemplate: {
4220 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4221 // DNInfo work in progress: CHECKME: what about DNLoc?
4222 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4223 }
4224
4225 case TemplateName::DependentTemplate: {
4226 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004227 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004228 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004229 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4230 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004231 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004232 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4233 // DNInfo work in progress: FIXME: source locations?
4234 DeclarationNameLoc DNLoc;
4235 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4236 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4237 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004238 }
4239 }
4240
John McCalld9dfe3a2011-06-30 08:33:18 +00004241 case TemplateName::SubstTemplateTemplateParm: {
4242 SubstTemplateTemplateParmStorage *subst
4243 = Name.getAsSubstTemplateTemplateParm();
4244 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4245 NameLoc);
4246 }
4247
4248 case TemplateName::SubstTemplateTemplateParmPack: {
4249 SubstTemplateTemplateParmPackStorage *subst
4250 = Name.getAsSubstTemplateTemplateParmPack();
4251 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4252 NameLoc);
4253 }
4254 }
4255
4256 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004257}
4258
Jay Foad39c79802011-01-12 09:06:06 +00004259TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004260 switch (Name.getKind()) {
4261 case TemplateName::QualifiedTemplate:
4262 case TemplateName::Template: {
4263 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004264 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004265 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004266 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4267
4268 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004269 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004270 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004271
John McCalld9dfe3a2011-06-30 08:33:18 +00004272 case TemplateName::OverloadedTemplate:
4273 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004274
John McCalld9dfe3a2011-06-30 08:33:18 +00004275 case TemplateName::DependentTemplate: {
4276 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4277 assert(DTN && "Non-dependent template names must refer to template decls.");
4278 return DTN->CanonicalTemplateName;
4279 }
4280
4281 case TemplateName::SubstTemplateTemplateParm: {
4282 SubstTemplateTemplateParmStorage *subst
4283 = Name.getAsSubstTemplateTemplateParm();
4284 return getCanonicalTemplateName(subst->getReplacement());
4285 }
4286
4287 case TemplateName::SubstTemplateTemplateParmPack: {
4288 SubstTemplateTemplateParmPackStorage *subst
4289 = Name.getAsSubstTemplateTemplateParmPack();
4290 TemplateTemplateParmDecl *canonParameter
4291 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4292 TemplateArgument canonArgPack
4293 = getCanonicalTemplateArgument(subst->getArgumentPack());
4294 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4295 }
4296 }
4297
4298 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004299}
4300
Douglas Gregoradee3e32009-11-11 23:06:43 +00004301bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4302 X = getCanonicalTemplateName(X);
4303 Y = getCanonicalTemplateName(Y);
4304 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4305}
4306
Mike Stump11289f42009-09-09 15:08:12 +00004307TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004308ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004309 switch (Arg.getKind()) {
4310 case TemplateArgument::Null:
4311 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004312
Douglas Gregora8e02e72009-07-28 23:00:59 +00004313 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004314 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004315
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004316 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004317 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004318 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
Eli Friedmanb826a002012-09-26 02:36:12 +00004321 case TemplateArgument::NullPtr:
4322 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4323 /*isNullPtr*/true);
4324
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004325 case TemplateArgument::Template:
4326 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004327
4328 case TemplateArgument::TemplateExpansion:
4329 return TemplateArgument(getCanonicalTemplateName(
4330 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004331 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004332
Douglas Gregora8e02e72009-07-28 23:00:59 +00004333 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004334 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004335
Douglas Gregora8e02e72009-07-28 23:00:59 +00004336 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004337 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004338
Douglas Gregora8e02e72009-07-28 23:00:59 +00004339 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004340 if (Arg.pack_size() == 0)
4341 return Arg;
4342
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004343 TemplateArgument *CanonArgs
4344 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004345 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004346 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004347 AEnd = Arg.pack_end();
4348 A != AEnd; (void)++A, ++Idx)
4349 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004350
Benjamin Kramercce63472015-08-05 09:40:22 +00004351 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004352 }
4353 }
4354
4355 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004356 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004357}
4358
Douglas Gregor333489b2009-03-27 23:10:48 +00004359NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004360ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004361 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004362 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004363
4364 switch (NNS->getKind()) {
4365 case NestedNameSpecifier::Identifier:
4366 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004367 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004368 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4369 NNS->getAsIdentifier());
4370
4371 case NestedNameSpecifier::Namespace:
4372 // A namespace is canonical; build a nested-name-specifier with
4373 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004374 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004375 NNS->getAsNamespace()->getOriginalNamespace());
4376
4377 case NestedNameSpecifier::NamespaceAlias:
4378 // A namespace is canonical; build a nested-name-specifier with
4379 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004380 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004381 NNS->getAsNamespaceAlias()->getNamespace()
4382 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004383
4384 case NestedNameSpecifier::TypeSpec:
4385 case NestedNameSpecifier::TypeSpecWithTemplate: {
4386 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004387
4388 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4389 // break it apart into its prefix and identifier, then reconsititute those
4390 // as the canonical nested-name-specifier. This is required to canonicalize
4391 // a dependent nested-name-specifier involving typedefs of dependent-name
4392 // types, e.g.,
4393 // typedef typename T::type T1;
4394 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004395 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4396 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004397 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004398
Eli Friedman5358a0a2012-03-03 04:09:56 +00004399 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4400 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4401 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004402 return NestedNameSpecifier::Create(*this, nullptr, false,
4403 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004404 }
4405
4406 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004407 case NestedNameSpecifier::Super:
4408 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004409 return NNS;
4410 }
4411
David Blaikie8a40f702012-01-17 06:56:22 +00004412 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004413}
4414
Chris Lattner7adf0762008-08-04 07:31:14 +00004415
Jay Foad39c79802011-01-12 09:06:06 +00004416const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004417 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004418 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004419 // Handle the common positive case fast.
4420 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4421 return AT;
4422 }
Mike Stump11289f42009-09-09 15:08:12 +00004423
John McCall8ccfcb52009-09-24 19:53:00 +00004424 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004425 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004426 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004427
John McCall8ccfcb52009-09-24 19:53:00 +00004428 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004429 // implements C99 6.7.3p8: "If the specification of an array type includes
4430 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004431
Chris Lattner7adf0762008-08-04 07:31:14 +00004432 // If we get here, we either have type qualifiers on the type, or we have
4433 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004434 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004435
John McCall33ddac02011-01-19 10:06:00 +00004436 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004437 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004438
Chris Lattner7adf0762008-08-04 07:31:14 +00004439 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004440 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004441 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004442 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004443
Chris Lattner7adf0762008-08-04 07:31:14 +00004444 // Otherwise, we have an array and we have qualifiers on it. Push the
4445 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004446 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004447
Chris Lattner7adf0762008-08-04 07:31:14 +00004448 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4449 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4450 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004451 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004452 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4453 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4454 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004455 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004456
Mike Stump11289f42009-09-09 15:08:12 +00004457 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004458 = dyn_cast<DependentSizedArrayType>(ATy))
4459 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004460 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004461 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004462 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004463 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004464 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004465
Chris Lattner7adf0762008-08-04 07:31:14 +00004466 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004467 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004468 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004469 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004470 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004471 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004472}
4473
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004474QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004475 if (T->isArrayType() || T->isFunctionType())
4476 return getDecayedType(T);
4477 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004478}
4479
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004480QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004481 T = getVariableArrayDecayedType(T);
4482 T = getAdjustedParameterType(T);
4483 return T.getUnqualifiedType();
4484}
4485
David Majnemerd09a51c2015-03-03 01:50:05 +00004486QualType ASTContext::getExceptionObjectType(QualType T) const {
4487 // C++ [except.throw]p3:
4488 // A throw-expression initializes a temporary object, called the exception
4489 // object, the type of which is determined by removing any top-level
4490 // cv-qualifiers from the static type of the operand of throw and adjusting
4491 // the type from "array of T" or "function returning T" to "pointer to T"
4492 // or "pointer to function returning T", [...]
4493 T = getVariableArrayDecayedType(T);
4494 if (T->isArrayType() || T->isFunctionType())
4495 T = getDecayedType(T);
4496 return T.getUnqualifiedType();
4497}
4498
Chris Lattnera21ad802008-04-02 05:18:44 +00004499/// getArrayDecayedType - Return the properly qualified result of decaying the
4500/// specified array type to a pointer. This operation is non-trivial when
4501/// handling typedefs etc. The canonical type of "T" must be an array type,
4502/// this returns a pointer to a properly qualified element of the array.
4503///
4504/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004505QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004506 // Get the element type with 'getAsArrayType' so that we don't lose any
4507 // typedefs in the element type of the array. This also handles propagation
4508 // of type qualifiers from the array type into the element type if present
4509 // (C99 6.7.3p8).
4510 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4511 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004512
Chris Lattner7adf0762008-08-04 07:31:14 +00004513 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004514
4515 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004516 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004517}
4518
John McCall33ddac02011-01-19 10:06:00 +00004519QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4520 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004521}
4522
John McCall33ddac02011-01-19 10:06:00 +00004523QualType ASTContext::getBaseElementType(QualType type) const {
4524 Qualifiers qs;
4525 while (true) {
4526 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004527 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004528 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004529
John McCall33ddac02011-01-19 10:06:00 +00004530 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004531 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533
John McCall33ddac02011-01-19 10:06:00 +00004534 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004535}
4536
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004537/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004538uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004539ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4540 uint64_t ElementCount = 1;
4541 do {
4542 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004543 CA = dyn_cast_or_null<ConstantArrayType>(
4544 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004545 } while (CA);
4546 return ElementCount;
4547}
4548
Steve Naroff0af91202007-04-27 21:51:21 +00004549/// getFloatingRank - Return a relative rank for floating point types.
4550/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004551static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004552 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004553 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004554
John McCall9dd450b2009-09-21 23:43:11 +00004555 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4556 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004557 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004558 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004559 case BuiltinType::Float: return FloatRank;
4560 case BuiltinType::Double: return DoubleRank;
4561 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004562 }
4563}
4564
Mike Stump11289f42009-09-09 15:08:12 +00004565/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4566/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004567/// 'typeDomain' is a real floating point or complex type.
4568/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004569QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4570 QualType Domain) const {
4571 FloatingRank EltRank = getFloatingRank(Size);
4572 if (Domain->isComplexType()) {
4573 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004574 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004575 case FloatRank: return FloatComplexTy;
4576 case DoubleRank: return DoubleComplexTy;
4577 case LongDoubleRank: return LongDoubleComplexTy;
4578 }
Steve Naroff0af91202007-04-27 21:51:21 +00004579 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004580
4581 assert(Domain->isRealFloatingType() && "Unknown domain!");
4582 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004583 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004584 case FloatRank: return FloatTy;
4585 case DoubleRank: return DoubleTy;
4586 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004587 }
David Blaikief47fa302012-01-17 02:30:50 +00004588 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004589}
4590
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004591/// getFloatingTypeOrder - Compare the rank of the two specified floating
4592/// point types, ignoring the domain of the type (i.e. 'double' ==
4593/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004594/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004595int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004596 FloatingRank LHSR = getFloatingRank(LHS);
4597 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004598
Chris Lattnerb90739d2008-04-06 23:38:49 +00004599 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004600 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004601 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004602 return 1;
4603 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004604}
4605
Chris Lattner76a00cf2008-04-06 22:59:24 +00004606/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4607/// routine will assert if passed a built-in type that isn't an integer or enum,
4608/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004609unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004610 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004611
Chris Lattner76a00cf2008-04-06 22:59:24 +00004612 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004613 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004614 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004615 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004616 case BuiltinType::Char_S:
4617 case BuiltinType::Char_U:
4618 case BuiltinType::SChar:
4619 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004620 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004621 case BuiltinType::Short:
4622 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004623 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004624 case BuiltinType::Int:
4625 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004626 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004627 case BuiltinType::Long:
4628 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004629 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004630 case BuiltinType::LongLong:
4631 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004632 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004633 case BuiltinType::Int128:
4634 case BuiltinType::UInt128:
4635 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004636 }
4637}
4638
Eli Friedman629ffb92009-08-20 04:21:42 +00004639/// \brief Whether this is a promotable bitfield reference according
4640/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4641///
4642/// \returns the type this bit-field will promote to, or NULL if no
4643/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004644QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004645 if (E->isTypeDependent() || E->isValueDependent())
4646 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004647
4648 // FIXME: We should not do this unless E->refersToBitField() is true. This
4649 // matters in C where getSourceBitField() will find bit-fields for various
4650 // cases where the source expression is not a bit-field designator.
4651
John McCalld25db7e2013-05-06 21:39:12 +00004652 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004653 if (!Field)
4654 return QualType();
4655
4656 QualType FT = Field->getType();
4657
Richard Smithcaf33902011-10-10 18:28:20 +00004658 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004659 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004660 // C++ [conv.prom]p5:
4661 // A prvalue for an integral bit-field can be converted to a prvalue of type
4662 // int if int can represent all the values of the bit-field; otherwise, it
4663 // can be converted to unsigned int if unsigned int can represent all the
4664 // values of the bit-field. If the bit-field is larger yet, no integral
4665 // promotion applies to it.
4666 // C11 6.3.1.1/2:
4667 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4668 // If an int can represent all values of the original type (as restricted by
4669 // the width, for a bit-field), the value is converted to an int; otherwise,
4670 // it is converted to an unsigned int.
4671 //
4672 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4673 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004674 if (BitWidth < IntSize)
4675 return IntTy;
4676
4677 if (BitWidth == IntSize)
4678 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4679
4680 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004681 // like the base type. GCC has some weird bugs in this area that we
4682 // deliberately do not follow (GCC follows a pre-standard resolution to
4683 // C's DR315 which treats bit-width as being part of the type, and this leaks
4684 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004685 return QualType();
4686}
4687
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004688/// getPromotedIntegerType - Returns the type that Promotable will
4689/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4690/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004691QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004692 assert(!Promotable.isNull());
4693 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004694 if (const EnumType *ET = Promotable->getAs<EnumType>())
4695 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004696
4697 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4698 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4699 // (3.9.1) can be converted to a prvalue of the first of the following
4700 // types that can represent all the values of its underlying type:
4701 // int, unsigned int, long int, unsigned long int, long long int, or
4702 // unsigned long long int [...]
4703 // FIXME: Is there some better way to compute this?
4704 if (BT->getKind() == BuiltinType::WChar_S ||
4705 BT->getKind() == BuiltinType::WChar_U ||
4706 BT->getKind() == BuiltinType::Char16 ||
4707 BT->getKind() == BuiltinType::Char32) {
4708 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4709 uint64_t FromSize = getTypeSize(BT);
4710 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4711 LongLongTy, UnsignedLongLongTy };
4712 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4713 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4714 if (FromSize < ToSize ||
4715 (FromSize == ToSize &&
4716 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4717 return PromoteTypes[Idx];
4718 }
4719 llvm_unreachable("char type should fit into long long");
4720 }
4721 }
4722
4723 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004724 if (Promotable->isSignedIntegerType())
4725 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004726 uint64_t PromotableSize = getIntWidth(Promotable);
4727 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004728 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4729 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4730}
4731
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004732/// \brief Recurses in pointer/array types until it finds an objc retainable
4733/// type and returns its ownership.
4734Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4735 while (!T.isNull()) {
4736 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4737 return T.getObjCLifetime();
4738 if (T->isArrayType())
4739 T = getBaseElementType(T);
4740 else if (const PointerType *PT = T->getAs<PointerType>())
4741 T = PT->getPointeeType();
4742 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004743 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004744 else
4745 break;
4746 }
4747
4748 return Qualifiers::OCL_None;
4749}
4750
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004751static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4752 // Incomplete enum types are not treated as integer types.
4753 // FIXME: In C++, enum types are never integer types.
4754 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4755 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004756 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004757}
4758
Mike Stump11289f42009-09-09 15:08:12 +00004759/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004760/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004761/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004762int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004763 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4764 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004765
4766 // Unwrap enums to their underlying type.
4767 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4768 LHSC = getIntegerTypeForEnum(ET);
4769 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4770 RHSC = getIntegerTypeForEnum(ET);
4771
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004772 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004773
Chris Lattner76a00cf2008-04-06 22:59:24 +00004774 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4775 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004776
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004777 unsigned LHSRank = getIntegerRank(LHSC);
4778 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004779
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004780 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4781 if (LHSRank == RHSRank) return 0;
4782 return LHSRank > RHSRank ? 1 : -1;
4783 }
Mike Stump11289f42009-09-09 15:08:12 +00004784
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004785 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4786 if (LHSUnsigned) {
4787 // If the unsigned [LHS] type is larger, return it.
4788 if (LHSRank >= RHSRank)
4789 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004790
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004791 // If the signed type can represent all values of the unsigned type, it
4792 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004793 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004794 return -1;
4795 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004796
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004797 // If the unsigned [RHS] type is larger, return it.
4798 if (RHSRank >= LHSRank)
4799 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004800
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004801 // If the signed type can represent all values of the unsigned type, it
4802 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004803 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004804 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004805}
Anders Carlsson98f07902007-08-17 05:31:46 +00004806
Mike Stump11289f42009-09-09 15:08:12 +00004807// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004808QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004809 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004810 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004811 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004812
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004813 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004814
Anders Carlsson98f07902007-08-17 05:31:46 +00004815 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004816 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004817 // int flags;
4818 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004819 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004820 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004821 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004822 FieldTypes[3] = LongTy;
4823
Anders Carlsson98f07902007-08-17 05:31:46 +00004824 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004825 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004826 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004827 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004828 SourceLocation(), nullptr,
4829 FieldTypes[i], /*TInfo=*/nullptr,
4830 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004831 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004832 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004833 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004834 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004835 }
4836
Douglas Gregord5058122010-02-11 01:19:42 +00004837 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004838 }
Mike Stump11289f42009-09-09 15:08:12 +00004839
Anders Carlsson98f07902007-08-17 05:31:46 +00004840 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004841}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004842
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004843QualType ASTContext::getObjCSuperType() const {
4844 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004845 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004846 TUDecl->addDecl(ObjCSuperTypeDecl);
4847 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4848 }
4849 return ObjCSuperType;
4850}
4851
Douglas Gregor512b0772009-04-23 22:29:11 +00004852void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004853 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004854 assert(Rec && "Invalid CFConstantStringType");
4855 CFConstantStringTypeDecl = Rec->getDecl();
4856}
4857
Jay Foad39c79802011-01-12 09:06:06 +00004858QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004859 if (BlockDescriptorType)
4860 return getTagDeclType(BlockDescriptorType);
4861
Alp Toker2dea15b2013-12-17 01:22:38 +00004862 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004863 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004864 RD = buildImplicitRecord("__block_descriptor");
4865 RD->startDefinition();
4866
Mike Stumpd0153282009-10-20 02:12:22 +00004867 QualType FieldTypes[] = {
4868 UnsignedLongTy,
4869 UnsignedLongTy,
4870 };
4871
Craig Topperd6d31ac2013-07-15 08:24:27 +00004872 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004873 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004874 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004875 };
4876
4877 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004878 FieldDecl *Field = FieldDecl::Create(
4879 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004880 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4881 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004882 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004883 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004884 }
4885
Alp Toker2dea15b2013-12-17 01:22:38 +00004886 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004887
Alp Toker2dea15b2013-12-17 01:22:38 +00004888 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004889
4890 return getTagDeclType(BlockDescriptorType);
4891}
4892
Jay Foad39c79802011-01-12 09:06:06 +00004893QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004894 if (BlockDescriptorExtendedType)
4895 return getTagDeclType(BlockDescriptorExtendedType);
4896
Alp Toker2dea15b2013-12-17 01:22:38 +00004897 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004898 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004899 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4900 RD->startDefinition();
4901
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004902 QualType FieldTypes[] = {
4903 UnsignedLongTy,
4904 UnsignedLongTy,
4905 getPointerType(VoidPtrTy),
4906 getPointerType(VoidPtrTy)
4907 };
4908
Craig Topperd6d31ac2013-07-15 08:24:27 +00004909 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004910 "reserved",
4911 "Size",
4912 "CopyFuncPtr",
4913 "DestroyFuncPtr"
4914 };
4915
4916 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004917 FieldDecl *Field = FieldDecl::Create(
4918 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004919 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4920 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004921 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004922 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004923 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004924 }
4925
Alp Toker2dea15b2013-12-17 01:22:38 +00004926 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004927
Alp Toker2dea15b2013-12-17 01:22:38 +00004928 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004929 return getTagDeclType(BlockDescriptorExtendedType);
4930}
4931
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004932/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4933/// requires copy/dispose. Note that this must match the logic
4934/// in buildByrefHelpers.
4935bool ASTContext::BlockRequiresCopying(QualType Ty,
4936 const VarDecl *D) {
4937 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4938 const Expr *copyExpr = getBlockVarCopyInits(D);
4939 if (!copyExpr && record->hasTrivialDestructor()) return false;
4940
Mike Stump94967902009-10-21 18:16:27 +00004941 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004942 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004943
4944 if (!Ty->isObjCRetainableType()) return false;
4945
4946 Qualifiers qs = Ty.getQualifiers();
4947
4948 // If we have lifetime, that dominates.
4949 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4950 assert(getLangOpts().ObjCAutoRefCount);
4951
4952 switch (lifetime) {
4953 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4954
4955 // These are just bits as far as the runtime is concerned.
4956 case Qualifiers::OCL_ExplicitNone:
4957 case Qualifiers::OCL_Autoreleasing:
4958 return false;
4959
4960 // Tell the runtime that this is ARC __weak, called by the
4961 // byref routines.
4962 case Qualifiers::OCL_Weak:
4963 // ARC __strong __block variables need to be retained.
4964 case Qualifiers::OCL_Strong:
4965 return true;
4966 }
4967 llvm_unreachable("fell out of lifetime switch!");
4968 }
4969 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4970 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004971}
4972
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004973bool ASTContext::getByrefLifetime(QualType Ty,
4974 Qualifiers::ObjCLifetime &LifeTime,
4975 bool &HasByrefExtendedLayout) const {
4976
4977 if (!getLangOpts().ObjC1 ||
4978 getLangOpts().getGC() != LangOptions::NonGC)
4979 return false;
4980
4981 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004982 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004983 HasByrefExtendedLayout = true;
4984 LifeTime = Qualifiers::OCL_None;
4985 }
4986 else if (getLangOpts().ObjCAutoRefCount)
4987 LifeTime = Ty.getObjCLifetime();
4988 // MRR.
4989 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4990 LifeTime = Qualifiers::OCL_ExplicitNone;
4991 else
4992 LifeTime = Qualifiers::OCL_None;
4993 return true;
4994}
4995
Douglas Gregorbab8a962011-09-08 01:46:34 +00004996TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4997 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004998 ObjCInstanceTypeDecl =
4999 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005000 return ObjCInstanceTypeDecl;
5001}
5002
Anders Carlsson18acd442007-10-29 06:33:42 +00005003// This returns true if a type has been typedefed to BOOL:
5004// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005005static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005006 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005007 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5008 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005009
Anders Carlssond8499822007-10-29 05:01:08 +00005010 return false;
5011}
5012
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005013/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005014/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005015CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005016 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5017 return CharUnits::Zero();
5018
Ken Dyck40775002010-01-11 17:06:35 +00005019 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005020
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005021 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005022 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005023 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005024 // Treat arrays as pointers, since that's how they're passed in.
5025 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005026 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005027 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005028}
5029
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005030bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005031 return getTargetInfo().getCXXABI().isMicrosoft() &&
5032 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005033 VD->getType()->isIntegralOrEnumerationType() &&
5034 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005035}
5036
Ken Dyck40775002010-01-11 17:06:35 +00005037static inline
5038std::string charUnitsToString(const CharUnits &CU) {
5039 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005040}
5041
John McCall351762c2011-02-07 10:33:21 +00005042/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005043/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005044std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5045 std::string S;
5046
David Chisnall950a9512009-11-17 19:33:30 +00005047 const BlockDecl *Decl = Expr->getBlockDecl();
5048 QualType BlockTy =
5049 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5050 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005051 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005052 getObjCEncodingForMethodParameter(
5053 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5054 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005055 else
Alp Toker314cc812014-01-25 16:55:45 +00005056 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005057 // Compute size of all parameters.
5058 // Start with computing size of a pointer in number of bytes.
5059 // FIXME: There might(should) be a better way of doing this computation!
5060 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005061 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5062 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005063 for (auto PI : Decl->params()) {
5064 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005065 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005066 if (sz.isZero())
5067 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005068 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005069 ParmOffset += sz;
5070 }
5071 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005072 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005073 // Block pointer and offset.
5074 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005075
5076 // Argument types.
5077 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005078 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005079 QualType PType = PVDecl->getOriginalType();
5080 if (const ArrayType *AT =
5081 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5082 // Use array's original type only if it has known number of
5083 // elements.
5084 if (!isa<ConstantArrayType>(AT))
5085 PType = PVDecl->getType();
5086 } else if (PType->isFunctionType())
5087 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005088 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005089 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5090 S, true /*Extended*/);
5091 else
5092 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005093 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005094 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005095 }
John McCall351762c2011-02-07 10:33:21 +00005096
5097 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005098}
5099
Douglas Gregora9d84932011-05-27 01:19:52 +00005100bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005101 std::string& S) {
5102 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005103 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005104 CharUnits ParmOffset;
5105 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005106 for (auto PI : Decl->params()) {
5107 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005108 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005109 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005110 continue;
5111
David Chisnall50e4eba2010-12-30 14:05:53 +00005112 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005113 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005114 ParmOffset += sz;
5115 }
5116 S += charUnitsToString(ParmOffset);
5117 ParmOffset = CharUnits::Zero();
5118
5119 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005120 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005121 QualType PType = PVDecl->getOriginalType();
5122 if (const ArrayType *AT =
5123 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5124 // Use array's original type only if it has known number of
5125 // elements.
5126 if (!isa<ConstantArrayType>(AT))
5127 PType = PVDecl->getType();
5128 } else if (PType->isFunctionType())
5129 PType = PVDecl->getType();
5130 getObjCEncodingForType(PType, S);
5131 S += charUnitsToString(ParmOffset);
5132 ParmOffset += getObjCEncodingTypeSize(PType);
5133 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005134
5135 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005136}
5137
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005138/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5139/// method parameter or return type. If Extended, include class names and
5140/// block object types.
5141void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5142 QualType T, std::string& S,
5143 bool Extended) const {
5144 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5145 getObjCEncodingForTypeQualifier(QT, S);
5146 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005147 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005148 true /*OutermostType*/,
5149 false /*EncodingProperty*/,
5150 false /*StructField*/,
5151 Extended /*EncodeBlockParameters*/,
5152 Extended /*EncodeClassNames*/);
5153}
5154
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005155/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005156/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005157bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005158 std::string& S,
5159 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005160 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005161 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005162 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5163 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005164 // Compute size of all parameters.
5165 // Start with computing size of a pointer in number of bytes.
5166 // FIXME: There might(should) be a better way of doing this computation!
5167 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005168 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005169 // The first two arguments (self and _cmd) are pointers; account for
5170 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005171 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005172 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005173 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005174 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005175 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005176 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005177 continue;
5178
Ken Dyck40775002010-01-11 17:06:35 +00005179 assert (sz.isPositive() &&
5180 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005181 ParmOffset += sz;
5182 }
Ken Dyck40775002010-01-11 17:06:35 +00005183 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005184 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005185 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005186
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005187 // Argument types.
5188 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005189 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005190 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005191 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005192 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005193 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005194 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5195 // Use array's original type only if it has known number of
5196 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005197 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005198 PType = PVDecl->getType();
5199 } else if (PType->isFunctionType())
5200 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005201 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5202 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005203 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005204 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005205 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005206
5207 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005208}
5209
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005210ObjCPropertyImplDecl *
5211ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5212 const ObjCPropertyDecl *PD,
5213 const Decl *Container) const {
5214 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005215 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005216 if (const ObjCCategoryImplDecl *CID =
5217 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005218 for (auto *PID : CID->property_impls())
5219 if (PID->getPropertyDecl() == PD)
5220 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005221 } else {
5222 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5223 for (auto *PID : OID->property_impls())
5224 if (PID->getPropertyDecl() == PD)
5225 return PID;
5226 }
5227 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005228}
5229
Daniel Dunbar4932b362008-08-28 04:38:10 +00005230/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005231/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005232/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5233/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005234/// Property attributes are stored as a comma-delimited C string. The simple
5235/// attributes readonly and bycopy are encoded as single characters. The
5236/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5237/// encoded as single characters, followed by an identifier. Property types
5238/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005239/// these attributes are defined by the following enumeration:
5240/// @code
5241/// enum PropertyAttributes {
5242/// kPropertyReadOnly = 'R', // property is read-only.
5243/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5244/// kPropertyByref = '&', // property is a reference to the value last assigned
5245/// kPropertyDynamic = 'D', // property is dynamic
5246/// kPropertyGetter = 'G', // followed by getter selector name
5247/// kPropertySetter = 'S', // followed by setter selector name
5248/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005249/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005250/// kPropertyWeak = 'W' // 'weak' property
5251/// kPropertyStrong = 'P' // property GC'able
5252/// kPropertyNonAtomic = 'N' // property non-atomic
5253/// };
5254/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005255void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005256 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005257 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005258 // Collect information from the property implementation decl(s).
5259 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005260 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005261
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005262 if (ObjCPropertyImplDecl *PropertyImpDecl =
5263 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5264 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5265 Dynamic = true;
5266 else
5267 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005268 }
5269
5270 // FIXME: This is not very efficient.
5271 S = "T";
5272
5273 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005274 // GCC has some special rules regarding encoding of properties which
5275 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005276 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005277
5278 if (PD->isReadOnly()) {
5279 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005280 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5281 S += ",C";
5282 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5283 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005284 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5285 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005286 } else {
5287 switch (PD->getSetterKind()) {
5288 case ObjCPropertyDecl::Assign: break;
5289 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005290 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005291 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005292 }
5293 }
5294
5295 // It really isn't clear at all what this means, since properties
5296 // are "dynamic by default".
5297 if (Dynamic)
5298 S += ",D";
5299
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005300 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5301 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005302
Daniel Dunbar4932b362008-08-28 04:38:10 +00005303 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5304 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005305 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005306 }
5307
5308 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5309 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005310 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005311 }
5312
5313 if (SynthesizePID) {
5314 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5315 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005316 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005317 }
5318
5319 // FIXME: OBJCGC: weak & strong
5320}
5321
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005322/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005323/// Another legacy compatibility encoding: 32-bit longs are encoded as
5324/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005325/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5326///
5327void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005328 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005329 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005330 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005331 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005332 else
Jay Foad39c79802011-01-12 09:06:06 +00005333 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005334 PointeeTy = IntTy;
5335 }
5336 }
5337}
5338
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005339void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005340 const FieldDecl *Field,
5341 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005342 // We follow the behavior of gcc, expanding structures which are
5343 // directly pointed to, and expanding embedded structures. Note that
5344 // these rules are sufficient to prevent recursive encoding of the
5345 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005346 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005347 true /* outermost type */, false, false,
5348 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005349}
5350
Joe Groff98ac7d22014-07-07 22:25:15 +00005351void ASTContext::getObjCEncodingForPropertyType(QualType T,
5352 std::string& S) const {
5353 // Encode result type.
5354 // GCC has some special rules regarding encoding of properties which
5355 // closely resembles encoding of ivars.
5356 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5357 true /* outermost type */,
5358 true /* encoding property */);
5359}
5360
John McCall393a78d2012-12-20 02:45:14 +00005361static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5362 BuiltinType::Kind kind) {
5363 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005364 case BuiltinType::Void: return 'v';
5365 case BuiltinType::Bool: return 'B';
5366 case BuiltinType::Char_U:
5367 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005368 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005369 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005370 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005371 case BuiltinType::UInt: return 'I';
5372 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005373 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005374 case BuiltinType::UInt128: return 'T';
5375 case BuiltinType::ULongLong: return 'Q';
5376 case BuiltinType::Char_S:
5377 case BuiltinType::SChar: return 'c';
5378 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005379 case BuiltinType::WChar_S:
5380 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005381 case BuiltinType::Int: return 'i';
5382 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005383 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005384 case BuiltinType::LongLong: return 'q';
5385 case BuiltinType::Int128: return 't';
5386 case BuiltinType::Float: return 'f';
5387 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005388 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005389 case BuiltinType::NullPtr: return '*'; // like char*
5390
5391 case BuiltinType::Half:
5392 // FIXME: potentially need @encodes for these!
5393 return ' ';
5394
5395 case BuiltinType::ObjCId:
5396 case BuiltinType::ObjCClass:
5397 case BuiltinType::ObjCSel:
5398 llvm_unreachable("@encoding ObjC primitive type");
5399
5400 // OpenCL and placeholder types don't need @encodings.
5401 case BuiltinType::OCLImage1d:
5402 case BuiltinType::OCLImage1dArray:
5403 case BuiltinType::OCLImage1dBuffer:
5404 case BuiltinType::OCLImage2d:
5405 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005406 case BuiltinType::OCLImage2dDepth:
5407 case BuiltinType::OCLImage2dArrayDepth:
5408 case BuiltinType::OCLImage2dMSAA:
5409 case BuiltinType::OCLImage2dArrayMSAA:
5410 case BuiltinType::OCLImage2dMSAADepth:
5411 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005412 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005413 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005414 case BuiltinType::OCLClkEvent:
5415 case BuiltinType::OCLQueue:
5416 case BuiltinType::OCLNDRange:
5417 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005418 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005419 case BuiltinType::Dependent:
5420#define BUILTIN_TYPE(KIND, ID)
5421#define PLACEHOLDER_TYPE(KIND, ID) \
5422 case BuiltinType::KIND:
5423#include "clang/AST/BuiltinTypes.def"
5424 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005425 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005426 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005427}
5428
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005429static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5430 EnumDecl *Enum = ET->getDecl();
5431
5432 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5433 if (!Enum->isFixed())
5434 return 'i';
5435
5436 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005437 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5438 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005439}
5440
Jay Foad39c79802011-01-12 09:06:06 +00005441static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005442 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005443 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005444 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005445 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5446 // The GNU runtime requires more information; bitfields are encoded as b,
5447 // then the offset (in bits) of the first element, then the type of the
5448 // bitfield, then the size in bits. For example, in this structure:
5449 //
5450 // struct
5451 // {
5452 // int integer;
5453 // int flags:2;
5454 // };
5455 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5456 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5457 // information is not especially sensible, but we're stuck with it for
5458 // compatibility with GCC, although providing it breaks anything that
5459 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005460 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005461 const RecordDecl *RD = FD->getParent();
5462 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005463 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005464 if (const EnumType *ET = T->getAs<EnumType>())
5465 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005466 else {
5467 const BuiltinType *BT = T->castAs<BuiltinType>();
5468 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5469 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005470 }
Richard Smithcaf33902011-10-10 18:28:20 +00005471 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005472}
5473
Daniel Dunbar07d07852009-10-18 21:17:35 +00005474// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005475void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5476 bool ExpandPointedToStructures,
5477 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005478 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005479 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005480 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005481 bool StructField,
5482 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005483 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005484 bool EncodePointerToObjCTypedef,
5485 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005486 CanQualType CT = getCanonicalType(T);
5487 switch (CT->getTypeClass()) {
5488 case Type::Builtin:
5489 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005490 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005491 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005492 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5493 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5494 else
5495 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005496 return;
Mike Stump11289f42009-09-09 15:08:12 +00005497
John McCall393a78d2012-12-20 02:45:14 +00005498 case Type::Complex: {
5499 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005500 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005501 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005502 return;
5503 }
John McCall393a78d2012-12-20 02:45:14 +00005504
5505 case Type::Atomic: {
5506 const AtomicType *AT = T->castAs<AtomicType>();
5507 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005508 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005509 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005510 }
John McCall393a78d2012-12-20 02:45:14 +00005511
5512 // encoding for pointer or reference types.
5513 case Type::Pointer:
5514 case Type::LValueReference:
5515 case Type::RValueReference: {
5516 QualType PointeeTy;
5517 if (isa<PointerType>(CT)) {
5518 const PointerType *PT = T->castAs<PointerType>();
5519 if (PT->isObjCSelType()) {
5520 S += ':';
5521 return;
5522 }
5523 PointeeTy = PT->getPointeeType();
5524 } else {
5525 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5526 }
5527
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005528 bool isReadOnly = false;
5529 // For historical/compatibility reasons, the read-only qualifier of the
5530 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5531 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005532 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005533 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005534 if (OutermostType && T.isConstQualified()) {
5535 isReadOnly = true;
5536 S += 'r';
5537 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005538 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005539 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005540 while (P->getAs<PointerType>())
5541 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005542 if (P.isConstQualified()) {
5543 isReadOnly = true;
5544 S += 'r';
5545 }
5546 }
5547 if (isReadOnly) {
5548 // Another legacy compatibility encoding. Some ObjC qualifier and type
5549 // combinations need to be rearranged.
5550 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005551 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005552 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005553 }
Mike Stump11289f42009-09-09 15:08:12 +00005554
Anders Carlssond8499822007-10-29 05:01:08 +00005555 if (PointeeTy->isCharType()) {
5556 // char pointer types should be encoded as '*' unless it is a
5557 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005558 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005559 S += '*';
5560 return;
5561 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005562 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005563 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5564 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5565 S += '#';
5566 return;
5567 }
5568 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5569 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5570 S += '@';
5571 return;
5572 }
5573 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005574 }
Anders Carlssond8499822007-10-29 05:01:08 +00005575 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005576 getLegacyIntegralTypeEncoding(PointeeTy);
5577
Mike Stump11289f42009-09-09 15:08:12 +00005578 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005579 nullptr, false, false, false, false, false, false,
5580 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005581 return;
5582 }
John McCall393a78d2012-12-20 02:45:14 +00005583
5584 case Type::ConstantArray:
5585 case Type::IncompleteArray:
5586 case Type::VariableArray: {
5587 const ArrayType *AT = cast<ArrayType>(CT);
5588
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005589 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005590 // Incomplete arrays are encoded as a pointer to the array element.
5591 S += '^';
5592
Mike Stump11289f42009-09-09 15:08:12 +00005593 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005594 false, ExpandStructures, FD);
5595 } else {
5596 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005597
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005598 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5599 S += llvm::utostr(CAT->getSize().getZExtValue());
5600 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005601 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005602 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5603 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005604 S += '0';
5605 }
Mike Stump11289f42009-09-09 15:08:12 +00005606
5607 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005608 false, ExpandStructures, FD,
5609 false, false, false, false, false, false,
5610 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005611 S += ']';
5612 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005613 return;
5614 }
Mike Stump11289f42009-09-09 15:08:12 +00005615
John McCall393a78d2012-12-20 02:45:14 +00005616 case Type::FunctionNoProto:
5617 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005618 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005619 return;
Mike Stump11289f42009-09-09 15:08:12 +00005620
John McCall393a78d2012-12-20 02:45:14 +00005621 case Type::Record: {
5622 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005623 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005624 // Anonymous structures print as '?'
5625 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5626 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005627 if (ClassTemplateSpecializationDecl *Spec
5628 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5629 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005630 llvm::raw_string_ostream OS(S);
5631 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005632 TemplateArgs.data(),
5633 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005634 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005635 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005636 } else {
5637 S += '?';
5638 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005639 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005640 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005641 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005642 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005643 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005644 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005645 if (FD) {
5646 S += '"';
5647 S += Field->getNameAsString();
5648 S += '"';
5649 }
Mike Stump11289f42009-09-09 15:08:12 +00005650
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005651 // Special case bit-fields.
5652 if (Field->isBitField()) {
5653 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005654 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005655 } else {
5656 QualType qt = Field->getType();
5657 getLegacyIntegralTypeEncoding(qt);
5658 getObjCEncodingForTypeImpl(qt, S, false, true,
5659 FD, /*OutermostType*/false,
5660 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005661 /*StructField*/true,
5662 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005663 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005664 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005665 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005666 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005667 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005668 return;
5669 }
Mike Stump11289f42009-09-09 15:08:12 +00005670
John McCall393a78d2012-12-20 02:45:14 +00005671 case Type::BlockPointer: {
5672 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005673 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005674 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005675 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005676
5677 S += '<';
5678 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005679 getObjCEncodingForTypeImpl(
5680 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5681 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005682 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5683 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005684 // Block self
5685 S += "@?";
5686 // Block parameters
5687 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005688 for (const auto &I : FPT->param_types())
5689 getObjCEncodingForTypeImpl(
5690 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5691 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005692 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5693 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005694 }
5695 S += '>';
5696 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005697 return;
5698 }
Mike Stump11289f42009-09-09 15:08:12 +00005699
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005700 case Type::ObjCObject: {
5701 // hack to match legacy encoding of *id and *Class
5702 QualType Ty = getObjCObjectPointerType(CT);
5703 if (Ty->isObjCIdType()) {
5704 S += "{objc_object=}";
5705 return;
5706 }
5707 else if (Ty->isObjCClassType()) {
5708 S += "{objc_class=}";
5709 return;
5710 }
5711 }
5712
John McCall393a78d2012-12-20 02:45:14 +00005713 case Type::ObjCInterface: {
5714 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005715 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005716 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005717 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005718 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005719 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005720 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005721 DeepCollectObjCIvars(OI, true, Ivars);
5722 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005723 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005724 if (Field->isBitField())
5725 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005726 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005727 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5728 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005729 EncodePointerToObjCTypedef,
5730 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005731 }
5732 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005733 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005734 }
Mike Stump11289f42009-09-09 15:08:12 +00005735
John McCall393a78d2012-12-20 02:45:14 +00005736 case Type::ObjCObjectPointer: {
5737 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005738 if (OPT->isObjCIdType()) {
5739 S += '@';
5740 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005741 }
Mike Stump11289f42009-09-09 15:08:12 +00005742
Steve Narofff0c86112009-10-28 22:03:49 +00005743 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5744 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5745 // Since this is a binary compatibility issue, need to consult with runtime
5746 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005747 S += '#';
5748 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005749 }
Mike Stump11289f42009-09-09 15:08:12 +00005750
Chris Lattnere7cabb92009-07-13 00:10:46 +00005751 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005752 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005753 ExpandPointedToStructures,
5754 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005755 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005756 // Note that we do extended encoding of protocol qualifer list
5757 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005758 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005759 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005760 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005761 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005762 S += '>';
5763 }
5764 S += '"';
5765 }
5766 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005767 }
Mike Stump11289f42009-09-09 15:08:12 +00005768
Chris Lattnere7cabb92009-07-13 00:10:46 +00005769 QualType PointeeTy = OPT->getPointeeType();
5770 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005771 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5772 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005773 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005774 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005775 // {...};
5776 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005777 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005778 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005779 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5780 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5781 DeepCollectObjCIvars(OI, true, Ivars);
5782 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5783 if (cast<FieldDecl>(Ivars[i]) == FD) {
5784 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005785 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005786 S += '}';
5787 return;
5788 }
5789 }
5790 }
Mike Stump11289f42009-09-09 15:08:12 +00005791 getObjCEncodingForTypeImpl(PointeeTy, S,
5792 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005793 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005794 false, false, false, false, false,
5795 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005796 return;
5797 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005798
5799 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005800 if (OPT->getInterfaceDecl() &&
5801 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005802 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005803 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005804 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005805 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005806 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005807 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005808 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005809 S += '"';
5810 }
5811 return;
5812 }
Mike Stump11289f42009-09-09 15:08:12 +00005813
John McCalla9e6e8d2010-05-17 23:56:34 +00005814 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005815 // FIXME: we shoul do better than that. 'M' is available.
5816 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005817 // This matches gcc's encoding, even though technically it is insufficient.
5818 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005819 case Type::Vector:
5820 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005821 // Until we have a coherent encoding of these three types, issue warning.
5822 { if (NotEncodedT)
5823 *NotEncodedT = T;
5824 return;
5825 }
5826
5827 // We could see an undeduced auto type here during error recovery.
5828 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005829 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005830 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005831
Richard Smith27d807c2013-04-30 13:56:41 +00005832
John McCall393a78d2012-12-20 02:45:14 +00005833#define ABSTRACT_TYPE(KIND, BASE)
5834#define TYPE(KIND, BASE)
5835#define DEPENDENT_TYPE(KIND, BASE) \
5836 case Type::KIND:
5837#define NON_CANONICAL_TYPE(KIND, BASE) \
5838 case Type::KIND:
5839#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5840 case Type::KIND:
5841#include "clang/AST/TypeNodes.def"
5842 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005843 }
John McCall393a78d2012-12-20 02:45:14 +00005844 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005845}
5846
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005847void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5848 std::string &S,
5849 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005850 bool includeVBases,
5851 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005852 assert(RDecl && "Expected non-null RecordDecl");
5853 assert(!RDecl->isUnion() && "Should not be called for unions");
5854 if (!RDecl->getDefinition())
5855 return;
5856
5857 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5858 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5859 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5860
5861 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005862 for (const auto &BI : CXXRec->bases()) {
5863 if (!BI.isVirtual()) {
5864 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005865 if (base->isEmpty())
5866 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005867 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005868 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5869 std::make_pair(offs, base));
5870 }
5871 }
5872 }
5873
5874 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005875 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005876 uint64_t offs = layout.getFieldOffset(i);
5877 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005878 std::make_pair(offs, Field));
5879 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005880 }
5881
5882 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005883 for (const auto &BI : CXXRec->vbases()) {
5884 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005885 if (base->isEmpty())
5886 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005887 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005888 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5889 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005890 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5891 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005892 }
5893 }
5894
5895 CharUnits size;
5896 if (CXXRec) {
5897 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5898 } else {
5899 size = layout.getSize();
5900 }
5901
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005902#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005903 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005904#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005905 std::multimap<uint64_t, NamedDecl *>::iterator
5906 CurLayObj = FieldOrBaseOffsets.begin();
5907
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005908 if (CXXRec && CXXRec->isDynamicClass() &&
5909 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005910 if (FD) {
5911 S += "\"_vptr$";
5912 std::string recname = CXXRec->getNameAsString();
5913 if (recname.empty()) recname = "?";
5914 S += recname;
5915 S += '"';
5916 }
5917 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005918#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005919 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005920#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005921 }
5922
5923 if (!RDecl->hasFlexibleArrayMember()) {
5924 // Mark the end of the structure.
5925 uint64_t offs = toBits(size);
5926 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005927 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005928 }
5929
5930 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005931#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005932 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005933 if (CurOffs < CurLayObj->first) {
5934 uint64_t padding = CurLayObj->first - CurOffs;
5935 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5936 // packing/alignment of members is different that normal, in which case
5937 // the encoding will be out-of-sync with the real layout.
5938 // If the runtime switches to just consider the size of types without
5939 // taking into account alignment, we could make padding explicit in the
5940 // encoding (e.g. using arrays of chars). The encoding strings would be
5941 // longer then though.
5942 CurOffs += padding;
5943 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005944#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005945
5946 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005947 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005948 break; // reached end of structure.
5949
5950 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5951 // We expand the bases without their virtual bases since those are going
5952 // in the initial structure. Note that this differs from gcc which
5953 // expands virtual bases each time one is encountered in the hierarchy,
5954 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005955 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5956 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005957 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005958#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005959 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005960#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005961 } else {
5962 FieldDecl *field = cast<FieldDecl>(dcl);
5963 if (FD) {
5964 S += '"';
5965 S += field->getNameAsString();
5966 S += '"';
5967 }
5968
5969 if (field->isBitField()) {
5970 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005971#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005972 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005973#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005974 } else {
5975 QualType qt = field->getType();
5976 getLegacyIntegralTypeEncoding(qt);
5977 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5978 /*OutermostType*/false,
5979 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005980 /*StructField*/true,
5981 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005982#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005983 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005984#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005985 }
5986 }
5987 }
5988}
5989
Mike Stump11289f42009-09-09 15:08:12 +00005990void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005991 std::string& S) const {
5992 if (QT & Decl::OBJC_TQ_In)
5993 S += 'n';
5994 if (QT & Decl::OBJC_TQ_Inout)
5995 S += 'N';
5996 if (QT & Decl::OBJC_TQ_Out)
5997 S += 'o';
5998 if (QT & Decl::OBJC_TQ_Bycopy)
5999 S += 'O';
6000 if (QT & Decl::OBJC_TQ_Byref)
6001 S += 'R';
6002 if (QT & Decl::OBJC_TQ_Oneway)
6003 S += 'V';
6004}
6005
Douglas Gregor3ea72692011-08-12 05:46:01 +00006006TypedefDecl *ASTContext::getObjCIdDecl() const {
6007 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006008 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006009 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006010 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006011 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006012 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006013}
6014
Douglas Gregor52e02802011-08-12 06:17:30 +00006015TypedefDecl *ASTContext::getObjCSelDecl() const {
6016 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006017 QualType T = getPointerType(ObjCBuiltinSelTy);
6018 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006019 }
6020 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006021}
6022
Douglas Gregor0a586182011-08-12 05:59:41 +00006023TypedefDecl *ASTContext::getObjCClassDecl() const {
6024 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006025 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006026 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006027 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006028 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006029 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006030}
6031
Douglas Gregord53ae832012-01-17 18:09:05 +00006032ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6033 if (!ObjCProtocolClassDecl) {
6034 ObjCProtocolClassDecl
6035 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6036 SourceLocation(),
6037 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006038 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006039 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006040 SourceLocation(), true);
6041 }
6042
6043 return ObjCProtocolClassDecl;
6044}
6045
Meador Inge5d3fb222012-06-16 03:34:49 +00006046//===----------------------------------------------------------------------===//
6047// __builtin_va_list Construction Functions
6048//===----------------------------------------------------------------------===//
6049
Charles Davisc7d5c942015-09-17 20:55:33 +00006050static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6051 StringRef Name) {
6052 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006053 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006054 return Context->buildImplicitTypedef(T, Name);
6055}
6056
6057static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6058 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6059}
6060
6061static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6062 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006063}
6064
6065static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6066 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006067 QualType T = Context->getPointerType(Context->VoidTy);
6068 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006069}
6070
Tim Northover9bb857a2013-01-31 12:13:10 +00006071static TypedefDecl *
6072CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006073 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006074 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006075 if (Context->getLangOpts().CPlusPlus) {
6076 // namespace std { struct __va_list {
6077 NamespaceDecl *NS;
6078 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6079 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006080 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006081 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006082 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006083 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006084 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006085 }
6086
6087 VaListTagDecl->startDefinition();
6088
6089 const size_t NumFields = 5;
6090 QualType FieldTypes[NumFields];
6091 const char *FieldNames[NumFields];
6092
6093 // void *__stack;
6094 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6095 FieldNames[0] = "__stack";
6096
6097 // void *__gr_top;
6098 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6099 FieldNames[1] = "__gr_top";
6100
6101 // void *__vr_top;
6102 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6103 FieldNames[2] = "__vr_top";
6104
6105 // int __gr_offs;
6106 FieldTypes[3] = Context->IntTy;
6107 FieldNames[3] = "__gr_offs";
6108
6109 // int __vr_offs;
6110 FieldTypes[4] = Context->IntTy;
6111 FieldNames[4] = "__vr_offs";
6112
6113 // Create fields
6114 for (unsigned i = 0; i < NumFields; ++i) {
6115 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6116 VaListTagDecl,
6117 SourceLocation(),
6118 SourceLocation(),
6119 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006120 FieldTypes[i], /*TInfo=*/nullptr,
6121 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006122 /*Mutable=*/false,
6123 ICIS_NoInit);
6124 Field->setAccess(AS_public);
6125 VaListTagDecl->addDecl(Field);
6126 }
6127 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006128 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006129 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006130
6131 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006132 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006133}
6134
Meador Inge5d3fb222012-06-16 03:34:49 +00006135static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6136 // typedef struct __va_list_tag {
6137 RecordDecl *VaListTagDecl;
6138
Alp Toker2dea15b2013-12-17 01:22:38 +00006139 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006140 VaListTagDecl->startDefinition();
6141
6142 const size_t NumFields = 5;
6143 QualType FieldTypes[NumFields];
6144 const char *FieldNames[NumFields];
6145
6146 // unsigned char gpr;
6147 FieldTypes[0] = Context->UnsignedCharTy;
6148 FieldNames[0] = "gpr";
6149
6150 // unsigned char fpr;
6151 FieldTypes[1] = Context->UnsignedCharTy;
6152 FieldNames[1] = "fpr";
6153
6154 // unsigned short reserved;
6155 FieldTypes[2] = Context->UnsignedShortTy;
6156 FieldNames[2] = "reserved";
6157
6158 // void* overflow_arg_area;
6159 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6160 FieldNames[3] = "overflow_arg_area";
6161
6162 // void* reg_save_area;
6163 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6164 FieldNames[4] = "reg_save_area";
6165
6166 // Create fields
6167 for (unsigned i = 0; i < NumFields; ++i) {
6168 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6169 SourceLocation(),
6170 SourceLocation(),
6171 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006172 FieldTypes[i], /*TInfo=*/nullptr,
6173 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006174 /*Mutable=*/false,
6175 ICIS_NoInit);
6176 Field->setAccess(AS_public);
6177 VaListTagDecl->addDecl(Field);
6178 }
6179 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006180 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006181 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6182
6183 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006184 TypedefDecl *VaListTagTypedefDecl =
6185 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6186
Meador Inge5d3fb222012-06-16 03:34:49 +00006187 QualType VaListTagTypedefType =
6188 Context->getTypedefType(VaListTagTypedefDecl);
6189
6190 // typedef __va_list_tag __builtin_va_list[1];
6191 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6192 QualType VaListTagArrayType
6193 = Context->getConstantArrayType(VaListTagTypedefType,
6194 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006195 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006196}
6197
6198static TypedefDecl *
6199CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006200 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006201 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006202 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006203 VaListTagDecl->startDefinition();
6204
6205 const size_t NumFields = 4;
6206 QualType FieldTypes[NumFields];
6207 const char *FieldNames[NumFields];
6208
6209 // unsigned gp_offset;
6210 FieldTypes[0] = Context->UnsignedIntTy;
6211 FieldNames[0] = "gp_offset";
6212
6213 // unsigned fp_offset;
6214 FieldTypes[1] = Context->UnsignedIntTy;
6215 FieldNames[1] = "fp_offset";
6216
6217 // void* overflow_arg_area;
6218 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6219 FieldNames[2] = "overflow_arg_area";
6220
6221 // void* reg_save_area;
6222 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6223 FieldNames[3] = "reg_save_area";
6224
6225 // Create fields
6226 for (unsigned i = 0; i < NumFields; ++i) {
6227 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6228 VaListTagDecl,
6229 SourceLocation(),
6230 SourceLocation(),
6231 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006232 FieldTypes[i], /*TInfo=*/nullptr,
6233 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006234 /*Mutable=*/false,
6235 ICIS_NoInit);
6236 Field->setAccess(AS_public);
6237 VaListTagDecl->addDecl(Field);
6238 }
6239 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006240 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006241 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6242
Richard Smith9b88a4c2015-07-27 05:40:23 +00006243 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006244
Richard Smith9b88a4c2015-07-27 05:40:23 +00006245 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006246 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006247 QualType VaListTagArrayType =
6248 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006249 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006250}
6251
6252static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6253 // typedef int __builtin_va_list[4];
6254 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6255 QualType IntArrayType
6256 = Context->getConstantArrayType(Context->IntTy,
6257 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006258 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006259}
6260
Logan Chien57086ce2012-10-10 06:56:20 +00006261static TypedefDecl *
6262CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006263 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006264 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006265 if (Context->getLangOpts().CPlusPlus) {
6266 // namespace std { struct __va_list {
6267 NamespaceDecl *NS;
6268 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6269 Context->getTranslationUnitDecl(),
6270 /*Inline*/false, SourceLocation(),
6271 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006272 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006273 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006274 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006275 }
6276
6277 VaListDecl->startDefinition();
6278
6279 // void * __ap;
6280 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6281 VaListDecl,
6282 SourceLocation(),
6283 SourceLocation(),
6284 &Context->Idents.get("__ap"),
6285 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006286 /*TInfo=*/nullptr,
6287 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006288 /*Mutable=*/false,
6289 ICIS_NoInit);
6290 Field->setAccess(AS_public);
6291 VaListDecl->addDecl(Field);
6292
6293 // };
6294 VaListDecl->completeDefinition();
6295
6296 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006297 QualType T = Context->getRecordType(VaListDecl);
6298 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006299}
6300
Ulrich Weigand47445072013-05-06 16:26:41 +00006301static TypedefDecl *
6302CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006303 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006304 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006305 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006306 VaListTagDecl->startDefinition();
6307
6308 const size_t NumFields = 4;
6309 QualType FieldTypes[NumFields];
6310 const char *FieldNames[NumFields];
6311
6312 // long __gpr;
6313 FieldTypes[0] = Context->LongTy;
6314 FieldNames[0] = "__gpr";
6315
6316 // long __fpr;
6317 FieldTypes[1] = Context->LongTy;
6318 FieldNames[1] = "__fpr";
6319
6320 // void *__overflow_arg_area;
6321 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6322 FieldNames[2] = "__overflow_arg_area";
6323
6324 // void *__reg_save_area;
6325 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6326 FieldNames[3] = "__reg_save_area";
6327
6328 // Create fields
6329 for (unsigned i = 0; i < NumFields; ++i) {
6330 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6331 VaListTagDecl,
6332 SourceLocation(),
6333 SourceLocation(),
6334 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006335 FieldTypes[i], /*TInfo=*/nullptr,
6336 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006337 /*Mutable=*/false,
6338 ICIS_NoInit);
6339 Field->setAccess(AS_public);
6340 VaListTagDecl->addDecl(Field);
6341 }
6342 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006343 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006344 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006345
Richard Smith9b88a4c2015-07-27 05:40:23 +00006346 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006347
6348 // typedef __va_list_tag __builtin_va_list[1];
6349 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006350 QualType VaListTagArrayType =
6351 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006352
Alp Toker56b5cc92013-12-15 10:36:26 +00006353 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006354}
6355
Meador Inge5d3fb222012-06-16 03:34:49 +00006356static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6357 TargetInfo::BuiltinVaListKind Kind) {
6358 switch (Kind) {
6359 case TargetInfo::CharPtrBuiltinVaList:
6360 return CreateCharPtrBuiltinVaListDecl(Context);
6361 case TargetInfo::VoidPtrBuiltinVaList:
6362 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006363 case TargetInfo::AArch64ABIBuiltinVaList:
6364 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006365 case TargetInfo::PowerABIBuiltinVaList:
6366 return CreatePowerABIBuiltinVaListDecl(Context);
6367 case TargetInfo::X86_64ABIBuiltinVaList:
6368 return CreateX86_64ABIBuiltinVaListDecl(Context);
6369 case TargetInfo::PNaClABIBuiltinVaList:
6370 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006371 case TargetInfo::AAPCSABIBuiltinVaList:
6372 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006373 case TargetInfo::SystemZBuiltinVaList:
6374 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006375 }
6376
6377 llvm_unreachable("Unhandled __builtin_va_list type kind");
6378}
6379
6380TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006381 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006382 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006383 assert(BuiltinVaListDecl->isImplicit());
6384 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006385
6386 return BuiltinVaListDecl;
6387}
6388
Richard Smith9b88a4c2015-07-27 05:40:23 +00006389Decl *ASTContext::getVaListTagDecl() const {
6390 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006391 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006392 if (!VaListTagDecl)
6393 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006394
Richard Smith9b88a4c2015-07-27 05:40:23 +00006395 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006396}
6397
Charles Davisc7d5c942015-09-17 20:55:33 +00006398TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6399 if (!BuiltinMSVaListDecl)
6400 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6401
6402 return BuiltinMSVaListDecl;
6403}
6404
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006405void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006406 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006407 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006408
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006409 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006410}
6411
John McCalld28ae272009-12-02 08:04:21 +00006412/// \brief Retrieve the template name that corresponds to a non-empty
6413/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006414TemplateName
6415ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6416 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006417 unsigned size = End - Begin;
6418 assert(size > 1 && "set is not overloaded!");
6419
6420 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6421 size * sizeof(FunctionTemplateDecl*));
6422 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6423
6424 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006425 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006426 NamedDecl *D = *I;
6427 assert(isa<FunctionTemplateDecl>(D) ||
6428 (isa<UsingShadowDecl>(D) &&
6429 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6430 *Storage++ = D;
6431 }
6432
6433 return TemplateName(OT);
6434}
6435
Douglas Gregordc572a32009-03-30 22:58:21 +00006436/// \brief Retrieve the template name that represents a qualified
6437/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006438TemplateName
6439ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6440 bool TemplateKeyword,
6441 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006442 assert(NNS && "Missing nested-name-specifier in qualified template name");
6443
Douglas Gregorc42075a2010-02-04 18:10:26 +00006444 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006445 llvm::FoldingSetNodeID ID;
6446 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6447
Craig Topper36250ad2014-05-12 05:36:57 +00006448 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006449 QualifiedTemplateName *QTN =
6450 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6451 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006452 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6453 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006454 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6455 }
6456
6457 return TemplateName(QTN);
6458}
6459
6460/// \brief Retrieve the template name that represents a dependent
6461/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006462TemplateName
6463ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6464 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006465 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006466 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006467
6468 llvm::FoldingSetNodeID ID;
6469 DependentTemplateName::Profile(ID, NNS, Name);
6470
Craig Topper36250ad2014-05-12 05:36:57 +00006471 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006472 DependentTemplateName *QTN =
6473 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6474
6475 if (QTN)
6476 return TemplateName(QTN);
6477
6478 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6479 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006480 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6481 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006482 } else {
6483 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006484 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6485 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006486 DependentTemplateName *CheckQTN =
6487 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6488 assert(!CheckQTN && "Dependent type name canonicalization broken");
6489 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006490 }
6491
6492 DependentTemplateNames.InsertNode(QTN, InsertPos);
6493 return TemplateName(QTN);
6494}
6495
Douglas Gregor71395fa2009-11-04 00:56:37 +00006496/// \brief Retrieve the template name that represents a dependent
6497/// template name such as \c MetaFun::template operator+.
6498TemplateName
6499ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006500 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006501 assert((!NNS || NNS->isDependent()) &&
6502 "Nested name specifier must be dependent");
6503
6504 llvm::FoldingSetNodeID ID;
6505 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006506
6507 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006508 DependentTemplateName *QTN
6509 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006510
6511 if (QTN)
6512 return TemplateName(QTN);
6513
6514 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6515 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006516 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6517 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006518 } else {
6519 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006520 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6521 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006522
6523 DependentTemplateName *CheckQTN
6524 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6525 assert(!CheckQTN && "Dependent template name canonicalization broken");
6526 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006527 }
6528
6529 DependentTemplateNames.InsertNode(QTN, InsertPos);
6530 return TemplateName(QTN);
6531}
6532
Douglas Gregor5590be02011-01-15 06:45:20 +00006533TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006534ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6535 TemplateName replacement) const {
6536 llvm::FoldingSetNodeID ID;
6537 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006538
6539 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006540 SubstTemplateTemplateParmStorage *subst
6541 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6542
6543 if (!subst) {
6544 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6545 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6546 }
6547
6548 return TemplateName(subst);
6549}
6550
6551TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006552ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6553 const TemplateArgument &ArgPack) const {
6554 ASTContext &Self = const_cast<ASTContext &>(*this);
6555 llvm::FoldingSetNodeID ID;
6556 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006557
6558 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006559 SubstTemplateTemplateParmPackStorage *Subst
6560 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6561
6562 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006563 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006564 ArgPack.pack_size(),
6565 ArgPack.pack_begin());
6566 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6567 }
6568
6569 return TemplateName(Subst);
6570}
6571
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006572/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006573/// TargetInfo, produce the corresponding type. The unsigned @p Type
6574/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006575CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006576 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006577 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006578 case TargetInfo::SignedChar: return SignedCharTy;
6579 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006580 case TargetInfo::SignedShort: return ShortTy;
6581 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6582 case TargetInfo::SignedInt: return IntTy;
6583 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6584 case TargetInfo::SignedLong: return LongTy;
6585 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6586 case TargetInfo::SignedLongLong: return LongLongTy;
6587 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6588 }
6589
David Blaikie83d382b2011-09-23 05:06:16 +00006590 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006591}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006592
6593//===----------------------------------------------------------------------===//
6594// Type Predicates.
6595//===----------------------------------------------------------------------===//
6596
Fariborz Jahanian96207692009-02-18 21:49:28 +00006597/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6598/// garbage collection attribute.
6599///
John McCall553d45a2011-01-12 00:34:59 +00006600Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006601 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006602 return Qualifiers::GCNone;
6603
David Blaikiebbafb8a2012-03-11 07:00:24 +00006604 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006605 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6606
6607 // Default behaviour under objective-C's gc is for ObjC pointers
6608 // (or pointers to them) be treated as though they were declared
6609 // as __strong.
6610 if (GCAttrs == Qualifiers::GCNone) {
6611 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6612 return Qualifiers::Strong;
6613 else if (Ty->isPointerType())
6614 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6615 } else {
6616 // It's not valid to set GC attributes on anything that isn't a
6617 // pointer.
6618#ifndef NDEBUG
6619 QualType CT = Ty->getCanonicalTypeInternal();
6620 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6621 CT = AT->getElementType();
6622 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6623#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006624 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006625 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006626}
6627
Chris Lattner49af6a42008-04-07 06:51:04 +00006628//===----------------------------------------------------------------------===//
6629// Type Compatibility Testing
6630//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006631
Mike Stump11289f42009-09-09 15:08:12 +00006632/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006633/// compatible.
6634static bool areCompatVectorTypes(const VectorType *LHS,
6635 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006636 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006637 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006638 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006639}
6640
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006641bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6642 QualType SecondVec) {
6643 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6644 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6645
6646 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6647 return true;
6648
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006649 // Treat Neon vector types and most AltiVec vector types as if they are the
6650 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006651 const VectorType *First = FirstVec->getAs<VectorType>();
6652 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006653 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006654 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006655 First->getVectorKind() != VectorType::AltiVecPixel &&
6656 First->getVectorKind() != VectorType::AltiVecBool &&
6657 Second->getVectorKind() != VectorType::AltiVecPixel &&
6658 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006659 return true;
6660
6661 return false;
6662}
6663
Steve Naroff8e6aee52009-07-23 01:01:38 +00006664//===----------------------------------------------------------------------===//
6665// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6666//===----------------------------------------------------------------------===//
6667
6668/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6669/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006670bool
6671ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6672 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006673 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006674 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006675 for (auto *PI : rProto->protocols())
6676 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006677 return true;
6678 return false;
6679}
6680
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006681/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6682/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006683bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6684 QualType rhs) {
6685 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6686 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6687 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6688
Aaron Ballman83731462014-03-17 16:14:00 +00006689 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006690 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006691 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006692 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6693 match = true;
6694 break;
6695 }
6696 }
6697 if (!match)
6698 return false;
6699 }
6700 return true;
6701}
6702
Steve Naroff8e6aee52009-07-23 01:01:38 +00006703/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6704/// ObjCQualifiedIDType.
6705bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6706 bool compare) {
6707 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006708 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006709 lhs->isObjCIdType() || lhs->isObjCClassType())
6710 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006711 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006712 rhs->isObjCIdType() || rhs->isObjCClassType())
6713 return true;
6714
6715 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006716 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006717
Steve Naroff8e6aee52009-07-23 01:01:38 +00006718 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006719
Steve Naroff8e6aee52009-07-23 01:01:38 +00006720 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006721 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006722 // make sure we check the class hierarchy.
6723 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006724 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006725 // when comparing an id<P> on lhs with a static type on rhs,
6726 // see if static class implements all of id's protocols, directly or
6727 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006728 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006729 return false;
6730 }
6731 }
6732 // If there are no qualifiers and no interface, we have an 'id'.
6733 return true;
6734 }
Mike Stump11289f42009-09-09 15:08:12 +00006735 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006736 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006737 bool match = false;
6738
6739 // when comparing an id<P> on lhs with a static type on rhs,
6740 // see if static class implements all of id's protocols, directly or
6741 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006742 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006743 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6744 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6745 match = true;
6746 break;
6747 }
6748 }
Mike Stump11289f42009-09-09 15:08:12 +00006749 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006750 // make sure we check the class hierarchy.
6751 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006752 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006753 // when comparing an id<P> on lhs with a static type on rhs,
6754 // see if static class implements all of id's protocols, directly or
6755 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006756 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006757 match = true;
6758 break;
6759 }
6760 }
6761 }
6762 if (!match)
6763 return false;
6764 }
Mike Stump11289f42009-09-09 15:08:12 +00006765
Steve Naroff8e6aee52009-07-23 01:01:38 +00006766 return true;
6767 }
Mike Stump11289f42009-09-09 15:08:12 +00006768
Steve Naroff8e6aee52009-07-23 01:01:38 +00006769 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6770 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6771
Mike Stump11289f42009-09-09 15:08:12 +00006772 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006773 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006774 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006775 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006776 bool match = false;
6777
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006778 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006779 // see if static class implements all of id's protocols, directly or
6780 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006781 // First, lhs protocols in the qualifier list must be found, direct
6782 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006783 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006784 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6785 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6786 match = true;
6787 break;
6788 }
6789 }
6790 if (!match)
6791 return false;
6792 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006793
6794 // Static class's protocols, or its super class or category protocols
6795 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6796 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6797 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6798 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6799 // This is rather dubious but matches gcc's behavior. If lhs has
6800 // no type qualifier and its class has no static protocol(s)
6801 // assume that it is mismatch.
6802 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6803 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006804 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006805 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006806 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006807 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6808 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6809 match = true;
6810 break;
6811 }
6812 }
6813 if (!match)
6814 return false;
6815 }
6816 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006817 return true;
6818 }
6819 return false;
6820}
6821
Eli Friedman47f77112008-08-22 00:56:42 +00006822/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006823/// compatible for assignment from RHS to LHS. This handles validation of any
6824/// protocol qualifiers on the LHS or RHS.
6825///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006826bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6827 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006828 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6829 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6830
Steve Naroff1329fa02009-07-15 18:40:39 +00006831 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006832 if (LHS->isObjCUnqualifiedIdOrClass() ||
6833 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006834 return true;
6835
Douglas Gregorab209d82015-07-07 03:58:42 +00006836 // Function object that propagates a successful result or handles
6837 // __kindof types.
6838 auto finish = [&](bool succeeded) -> bool {
6839 if (succeeded)
6840 return true;
6841
6842 if (!RHS->isKindOfType())
6843 return false;
6844
6845 // Strip off __kindof and protocol qualifiers, then check whether
6846 // we can assign the other way.
6847 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6848 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6849 };
6850
6851 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6852 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6853 QualType(RHSOPT,0),
6854 false));
6855 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006856
Douglas Gregorab209d82015-07-07 03:58:42 +00006857 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6858 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6859 QualType(RHSOPT,0)));
6860 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006861
John McCall8b07ec22010-05-15 11:32:37 +00006862 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006863 if (LHS->getInterface() && RHS->getInterface()) {
6864 return finish(canAssignObjCInterfaces(LHS, RHS));
6865 }
Mike Stump11289f42009-09-09 15:08:12 +00006866
Steve Naroff8e6aee52009-07-23 01:01:38 +00006867 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006868}
6869
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006870/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006871/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006872/// arguments in block literals. When passed as arguments, passing 'A*' where
6873/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6874/// not OK. For the return type, the opposite is not OK.
6875bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6876 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006877 const ObjCObjectPointerType *RHSOPT,
6878 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006879
6880 // Function object that propagates a successful result or handles
6881 // __kindof types.
6882 auto finish = [&](bool succeeded) -> bool {
6883 if (succeeded)
6884 return true;
6885
6886 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6887 if (!Expected->isKindOfType())
6888 return false;
6889
6890 // Strip off __kindof and protocol qualifiers, then check whether
6891 // we can assign the other way.
6892 return canAssignObjCInterfacesInBlockPointer(
6893 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6894 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6895 BlockReturnType);
6896 };
6897
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006898 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006899 return true;
6900
6901 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006902 return finish(RHSOPT->isObjCBuiltinType() ||
6903 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006904 }
6905
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006906 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006907 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6908 QualType(RHSOPT,0),
6909 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006910
6911 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6912 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6913 if (LHS && RHS) { // We have 2 user-defined types.
6914 if (LHS != RHS) {
6915 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006916 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006917 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006918 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006919 }
6920 else
6921 return true;
6922 }
6923 return false;
6924}
6925
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006926/// Comparison routine for Objective-C protocols to be used with
6927/// llvm::array_pod_sort.
6928static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6929 ObjCProtocolDecl * const *rhs) {
6930 return (*lhs)->getName().compare((*rhs)->getName());
6931
6932}
6933
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006934/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006935/// of protocols inherited from two distinct objective-c pointer objects with
6936/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006937/// It is used to build composite qualifier list of the composite type of
6938/// the conditional expression involving two objective-c pointer objects.
6939static
6940void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006941 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006942 const ObjCObjectPointerType *LHSOPT,
6943 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006944 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006945
John McCall8b07ec22010-05-15 11:32:37 +00006946 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6947 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6948 assert(LHS->getInterface() && "LHS must have an interface base");
6949 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006950
6951 // Add all of the protocols for the LHS.
6952 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6953
6954 // Start with the protocol qualifiers.
6955 for (auto proto : LHS->quals()) {
6956 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006957 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006958
6959 // Also add the protocols associated with the LHS interface.
6960 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6961
6962 // Add all of the protocls for the RHS.
6963 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6964
6965 // Start with the protocol qualifiers.
6966 for (auto proto : RHS->quals()) {
6967 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006968 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006969
6970 // Also add the protocols associated with the RHS interface.
6971 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6972
6973 // Compute the intersection of the collected protocol sets.
6974 for (auto proto : LHSProtocolSet) {
6975 if (RHSProtocolSet.count(proto))
6976 IntersectionSet.push_back(proto);
6977 }
6978
6979 // Compute the set of protocols that is implied by either the common type or
6980 // the protocols within the intersection.
6981 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6982 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6983
6984 // Remove any implied protocols from the list of inherited protocols.
6985 if (!ImpliedProtocols.empty()) {
6986 IntersectionSet.erase(
6987 std::remove_if(IntersectionSet.begin(),
6988 IntersectionSet.end(),
6989 [&](ObjCProtocolDecl *proto) -> bool {
6990 return ImpliedProtocols.count(proto) > 0;
6991 }),
6992 IntersectionSet.end());
6993 }
6994
6995 // Sort the remaining protocols by name.
6996 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
6997 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006998}
6999
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007000/// Determine whether the first type is a subtype of the second.
7001static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7002 QualType rhs) {
7003 // Common case: two object pointers.
7004 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7005 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7006 if (lhsOPT && rhsOPT)
7007 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7008
7009 // Two block pointers.
7010 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7011 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7012 if (lhsBlock && rhsBlock)
7013 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7014
7015 // If either is an unqualified 'id' and the other is a block, it's
7016 // acceptable.
7017 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7018 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7019 return true;
7020
7021 return false;
7022}
7023
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007024// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007025static bool sameObjCTypeArgs(ASTContext &ctx,
7026 const ObjCInterfaceDecl *iface,
7027 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007028 ArrayRef<QualType> rhsArgs,
7029 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007030 if (lhsArgs.size() != rhsArgs.size())
7031 return false;
7032
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007033 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007034 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007035 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7036 continue;
7037
7038 switch (typeParams->begin()[i]->getVariance()) {
7039 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007040 if (!stripKindOf ||
7041 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7042 rhsArgs[i].stripObjCKindOfType(ctx))) {
7043 return false;
7044 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007045 break;
7046
7047 case ObjCTypeParamVariance::Covariant:
7048 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7049 return false;
7050 break;
7051
7052 case ObjCTypeParamVariance::Contravariant:
7053 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7054 return false;
7055 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007056 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007057 }
7058
7059 return true;
7060}
7061
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007062QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007063 const ObjCObjectPointerType *Lptr,
7064 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007065 const ObjCObjectType *LHS = Lptr->getObjectType();
7066 const ObjCObjectType *RHS = Rptr->getObjectType();
7067 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7068 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007069
7070 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007071 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007072
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007073 // Follow the left-hand side up the class hierarchy until we either hit a
7074 // root or find the RHS. Record the ancestors in case we don't find it.
7075 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7076 LHSAncestors;
7077 while (true) {
7078 // Record this ancestor. We'll need this if the common type isn't in the
7079 // path from the LHS to the root.
7080 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007081
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007082 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7083 // Get the type arguments.
7084 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7085 bool anyChanges = false;
7086 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7087 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007088 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7089 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007090 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007091 return QualType();
7092 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7093 // If only one has type arguments, the result will not have type
7094 // arguments.
7095 LHSTypeArgs = { };
7096 anyChanges = true;
7097 }
7098
7099 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007100 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007101 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7102 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007103 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007104 anyChanges = true;
7105
7106 // If anything in the LHS will have changed, build a new result type.
7107 if (anyChanges) {
7108 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007109 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7110 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007111 return getObjCObjectPointerType(Result);
7112 }
7113
7114 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007115 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007116
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007117 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007118 QualType LHSSuperType = LHS->getSuperClassType();
7119 if (LHSSuperType.isNull())
7120 break;
7121
7122 LHS = LHSSuperType->castAs<ObjCObjectType>();
7123 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007124
7125 // We didn't find anything by following the LHS to its root; now check
7126 // the RHS against the cached set of ancestors.
7127 while (true) {
7128 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7129 if (KnownLHS != LHSAncestors.end()) {
7130 LHS = KnownLHS->second;
7131
7132 // Get the type arguments.
7133 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7134 bool anyChanges = false;
7135 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7136 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007137 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7138 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007139 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007140 return QualType();
7141 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7142 // If only one has type arguments, the result will not have type
7143 // arguments.
7144 RHSTypeArgs = { };
7145 anyChanges = true;
7146 }
7147
7148 // Compute the intersection of protocols.
7149 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7150 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7151 Protocols);
7152 if (!Protocols.empty())
7153 anyChanges = true;
7154
7155 if (anyChanges) {
7156 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007157 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7158 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007159 return getObjCObjectPointerType(Result);
7160 }
7161
7162 return getObjCObjectPointerType(QualType(RHS, 0));
7163 }
7164
7165 // Find the superclass of the RHS.
7166 QualType RHSSuperType = RHS->getSuperClassType();
7167 if (RHSSuperType.isNull())
7168 break;
7169
7170 RHS = RHSSuperType->castAs<ObjCObjectType>();
7171 }
7172
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007173 return QualType();
7174}
7175
John McCall8b07ec22010-05-15 11:32:37 +00007176bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7177 const ObjCObjectType *RHS) {
7178 assert(LHS->getInterface() && "LHS is not an interface type");
7179 assert(RHS->getInterface() && "RHS is not an interface type");
7180
Chris Lattner49af6a42008-04-07 06:51:04 +00007181 // Verify that the base decls are compatible: the RHS must be a subclass of
7182 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007183 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7184 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7185 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007186 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007187
Douglas Gregore83b9562015-07-07 03:57:53 +00007188 // If the LHS has protocol qualifiers, determine whether all of them are
7189 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7190 // LHS).
7191 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007192 // OK if conversion of LHS to SuperClass results in narrowing of types
7193 // ; i.e., SuperClass may implement at least one of the protocols
7194 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7195 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7196 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7197 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7198 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7199 // qualifiers.
7200 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007201 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007202 // If there is no protocols associated with RHS, it is not a match.
7203 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007204 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007205
7206 for (const auto *LHSProto : LHS->quals()) {
7207 bool SuperImplementsProtocol = false;
7208 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7209 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7210 SuperImplementsProtocol = true;
7211 break;
7212 }
7213 if (!SuperImplementsProtocol)
7214 return false;
7215 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007216 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007217
7218 // If the LHS is specialized, we may need to check type arguments.
7219 if (LHS->isSpecialized()) {
7220 // Follow the superclass chain until we've matched the LHS class in the
7221 // hierarchy. This substitutes type arguments through.
7222 const ObjCObjectType *RHSSuper = RHS;
7223 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7224 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7225
7226 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007227 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007228 !sameObjCTypeArgs(*this, LHS->getInterface(),
7229 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007230 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007231 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007232 }
7233 }
7234
7235 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007236}
7237
Steve Naroffb7605152009-02-12 17:52:19 +00007238bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7239 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007240 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7241 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007242
Steve Naroff7cae42b2009-07-10 23:34:53 +00007243 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007244 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007245
7246 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7247 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007248}
7249
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007250bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7251 return canAssignObjCInterfaces(
7252 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7253 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7254}
7255
Mike Stump11289f42009-09-09 15:08:12 +00007256/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007257/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007258/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007259/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007260bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7261 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007262 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007263 return hasSameType(LHS, RHS);
7264
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007265 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007266}
7267
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007268bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007269 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007270}
7271
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007272bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7273 return !mergeTypes(LHS, RHS, true).isNull();
7274}
7275
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007276/// mergeTransparentUnionType - if T is a transparent union type and a member
7277/// of T is compatible with SubType, return the merged type, else return
7278/// QualType()
7279QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7280 bool OfBlockPointer,
7281 bool Unqualified) {
7282 if (const RecordType *UT = T->getAsUnionType()) {
7283 RecordDecl *UD = UT->getDecl();
7284 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007285 for (const auto *I : UD->fields()) {
7286 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007287 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7288 if (!MT.isNull())
7289 return MT;
7290 }
7291 }
7292 }
7293
7294 return QualType();
7295}
7296
Alp Toker9cacbab2014-01-20 20:26:09 +00007297/// mergeFunctionParameterTypes - merge two types which appear as function
7298/// parameter types
7299QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7300 bool OfBlockPointer,
7301 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007302 // GNU extension: two types are compatible if they appear as a function
7303 // argument, one of the types is a transparent union type and the other
7304 // type is compatible with a union member
7305 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7306 Unqualified);
7307 if (!lmerge.isNull())
7308 return lmerge;
7309
7310 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7311 Unqualified);
7312 if (!rmerge.isNull())
7313 return rmerge;
7314
7315 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7316}
7317
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007318QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007319 bool OfBlockPointer,
7320 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007321 const FunctionType *lbase = lhs->getAs<FunctionType>();
7322 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007323 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7324 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007325 bool allLTypes = true;
7326 bool allRTypes = true;
7327
7328 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007329 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007330 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007331 QualType RHS = rbase->getReturnType();
7332 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007333 bool UnqualifiedResult = Unqualified;
7334 if (!UnqualifiedResult)
7335 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007336 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007337 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007338 else
Alp Toker314cc812014-01-25 16:55:45 +00007339 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007340 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007341 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007342
7343 if (Unqualified)
7344 retType = retType.getUnqualifiedType();
7345
Alp Toker314cc812014-01-25 16:55:45 +00007346 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7347 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007348 if (Unqualified) {
7349 LRetType = LRetType.getUnqualifiedType();
7350 RRetType = RRetType.getUnqualifiedType();
7351 }
7352
7353 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007354 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007355 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007356 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007357
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007358 // FIXME: double check this
7359 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7360 // rbase->getRegParmAttr() != 0 &&
7361 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007362 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7363 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007364
Douglas Gregor8c940862010-01-18 17:14:39 +00007365 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007366 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007367 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007368
John McCall8c6b56f2010-12-15 01:06:38 +00007369 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007370 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7371 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007372 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7373 return QualType();
7374
John McCall31168b02011-06-15 23:02:42 +00007375 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7376 return QualType();
7377
John McCall8c6b56f2010-12-15 01:06:38 +00007378 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7379 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007380
Rafael Espindola8778c282012-11-29 16:09:03 +00007381 if (lbaseInfo.getNoReturn() != NoReturn)
7382 allLTypes = false;
7383 if (rbaseInfo.getNoReturn() != NoReturn)
7384 allRTypes = false;
7385
John McCall31168b02011-06-15 23:02:42 +00007386 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007387
Eli Friedman47f77112008-08-22 00:56:42 +00007388 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007389 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7390 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007391 // Compatible functions must have the same number of parameters
7392 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007393 return QualType();
7394
7395 // Variadic and non-variadic functions aren't compatible
7396 if (lproto->isVariadic() != rproto->isVariadic())
7397 return QualType();
7398
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007399 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7400 return QualType();
7401
Fariborz Jahanian97676972011-09-28 21:52:05 +00007402 if (LangOpts.ObjCAutoRefCount &&
7403 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7404 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007405
7406 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007407 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007408 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7409 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7410 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7411 QualType paramType = mergeFunctionParameterTypes(
7412 lParamType, rParamType, OfBlockPointer, Unqualified);
7413 if (paramType.isNull())
7414 return QualType();
7415
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007416 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007417 paramType = paramType.getUnqualifiedType();
7418
7419 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007420 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007421 lParamType = lParamType.getUnqualifiedType();
7422 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007423 }
Alp Toker601b22c2014-01-21 23:35:24 +00007424
7425 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007426 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007427 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007428 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007429 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007430
Eli Friedman47f77112008-08-22 00:56:42 +00007431 if (allLTypes) return lhs;
7432 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007433
7434 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7435 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007436 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007437 }
7438
7439 if (lproto) allRTypes = false;
7440 if (rproto) allLTypes = false;
7441
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007442 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007443 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007444 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007445 if (proto->isVariadic()) return QualType();
7446 // Check that the types are compatible with the types that
7447 // would result from default argument promotions (C99 6.7.5.3p15).
7448 // The only types actually affected are promotable integer
7449 // types and floats, which would be passed as a different
7450 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007451 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7452 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007453
Eli Friedman448ce402012-08-30 00:44:15 +00007454 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007455 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007456 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7457 paramTy = Enum->getDecl()->getIntegerType();
7458 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007459 return QualType();
7460 }
Alp Toker601b22c2014-01-21 23:35:24 +00007461
7462 if (paramTy->isPromotableIntegerType() ||
7463 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007464 return QualType();
7465 }
7466
7467 if (allLTypes) return lhs;
7468 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007469
7470 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7471 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007472 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007473 }
7474
7475 if (allLTypes) return lhs;
7476 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007477 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007478}
7479
John McCall433c2e62013-03-21 00:10:07 +00007480/// Given that we have an enum type and a non-enum type, try to merge them.
7481static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7482 QualType other, bool isBlockReturnType) {
7483 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7484 // a signed integer type, or an unsigned integer type.
7485 // Compatibility is based on the underlying type, not the promotion
7486 // type.
7487 QualType underlyingType = ET->getDecl()->getIntegerType();
7488 if (underlyingType.isNull()) return QualType();
7489 if (Context.hasSameType(underlyingType, other))
7490 return other;
7491
7492 // In block return types, we're more permissive and accept any
7493 // integral type of the same size.
7494 if (isBlockReturnType && other->isIntegerType() &&
7495 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7496 return other;
7497
7498 return QualType();
7499}
7500
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007501QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007502 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007503 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007504 // C++ [expr]: If an expression initially has the type "reference to T", the
7505 // type is adjusted to "T" prior to any further analysis, the expression
7506 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007507 // expression is an lvalue unless the reference is an rvalue reference and
7508 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007509 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7510 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007511
7512 if (Unqualified) {
7513 LHS = LHS.getUnqualifiedType();
7514 RHS = RHS.getUnqualifiedType();
7515 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007516
Eli Friedman47f77112008-08-22 00:56:42 +00007517 QualType LHSCan = getCanonicalType(LHS),
7518 RHSCan = getCanonicalType(RHS);
7519
7520 // If two types are identical, they are compatible.
7521 if (LHSCan == RHSCan)
7522 return LHS;
7523
John McCall8ccfcb52009-09-24 19:53:00 +00007524 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007525 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7526 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007527 if (LQuals != RQuals) {
7528 // If any of these qualifiers are different, we have a type
7529 // mismatch.
7530 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007531 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7532 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007533 return QualType();
7534
7535 // Exactly one GC qualifier difference is allowed: __strong is
7536 // okay if the other type has no GC qualifier but is an Objective
7537 // C object pointer (i.e. implicitly strong by default). We fix
7538 // this by pretending that the unqualified type was actually
7539 // qualified __strong.
7540 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7541 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7542 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7543
7544 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7545 return QualType();
7546
7547 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7548 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7549 }
7550 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7551 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7552 }
Eli Friedman47f77112008-08-22 00:56:42 +00007553 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007554 }
7555
7556 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007557
Eli Friedmandcca6332009-06-01 01:22:52 +00007558 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7559 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007560
Chris Lattnerfd652912008-01-14 05:45:46 +00007561 // We want to consider the two function types to be the same for these
7562 // comparisons, just force one to the other.
7563 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7564 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007565
7566 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007567 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7568 LHSClass = Type::ConstantArray;
7569 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7570 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007571
John McCall8b07ec22010-05-15 11:32:37 +00007572 // ObjCInterfaces are just specialized ObjCObjects.
7573 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7574 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7575
Nate Begemance4d7fc2008-04-18 23:10:10 +00007576 // Canonicalize ExtVector -> Vector.
7577 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7578 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007579
Chris Lattner95554662008-04-07 05:43:21 +00007580 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007581 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007582 // Note that we only have special rules for turning block enum
7583 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007584 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007585 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007586 }
John McCall9dd450b2009-09-21 23:43:11 +00007587 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007588 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007589 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007590 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007591 if (OfBlockPointer && !BlockReturnType) {
7592 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7593 return LHS;
7594 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7595 return RHS;
7596 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007597
Eli Friedman47f77112008-08-22 00:56:42 +00007598 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007599 }
Eli Friedman47f77112008-08-22 00:56:42 +00007600
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007601 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007602 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007603#define TYPE(Class, Base)
7604#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007605#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007606#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7607#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7608#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007609 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007610
Richard Smith27d807c2013-04-30 13:56:41 +00007611 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007612 case Type::LValueReference:
7613 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007614 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007615 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007616
John McCall8b07ec22010-05-15 11:32:37 +00007617 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007618 case Type::IncompleteArray:
7619 case Type::VariableArray:
7620 case Type::FunctionProto:
7621 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007622 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007623
Chris Lattnerfd652912008-01-14 05:45:46 +00007624 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007625 {
7626 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007627 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7628 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007629 if (Unqualified) {
7630 LHSPointee = LHSPointee.getUnqualifiedType();
7631 RHSPointee = RHSPointee.getUnqualifiedType();
7632 }
7633 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7634 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007635 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007636 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007637 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007638 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007639 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007640 return getPointerType(ResultType);
7641 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007642 case Type::BlockPointer:
7643 {
7644 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007645 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7646 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007647 if (Unqualified) {
7648 LHSPointee = LHSPointee.getUnqualifiedType();
7649 RHSPointee = RHSPointee.getUnqualifiedType();
7650 }
7651 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7652 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007653 if (ResultType.isNull()) return QualType();
7654 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7655 return LHS;
7656 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7657 return RHS;
7658 return getBlockPointerType(ResultType);
7659 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007660 case Type::Atomic:
7661 {
7662 // Merge two pointer types, while trying to preserve typedef info
7663 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7664 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7665 if (Unqualified) {
7666 LHSValue = LHSValue.getUnqualifiedType();
7667 RHSValue = RHSValue.getUnqualifiedType();
7668 }
7669 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7670 Unqualified);
7671 if (ResultType.isNull()) return QualType();
7672 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7673 return LHS;
7674 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7675 return RHS;
7676 return getAtomicType(ResultType);
7677 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007678 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007679 {
7680 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7681 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7682 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7683 return QualType();
7684
7685 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7686 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007687 if (Unqualified) {
7688 LHSElem = LHSElem.getUnqualifiedType();
7689 RHSElem = RHSElem.getUnqualifiedType();
7690 }
7691
7692 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007693 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007694 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7695 return LHS;
7696 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7697 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007698 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7699 ArrayType::ArraySizeModifier(), 0);
7700 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7701 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007702 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7703 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007704 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7705 return LHS;
7706 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7707 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007708 if (LVAT) {
7709 // FIXME: This isn't correct! But tricky to implement because
7710 // the array's size has to be the size of LHS, but the type
7711 // has to be different.
7712 return LHS;
7713 }
7714 if (RVAT) {
7715 // FIXME: This isn't correct! But tricky to implement because
7716 // the array's size has to be the size of RHS, but the type
7717 // has to be different.
7718 return RHS;
7719 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007720 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7721 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007722 return getIncompleteArrayType(ResultType,
7723 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007724 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007725 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007726 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007727 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007728 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007729 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007730 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007731 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007732 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007733 case Type::Complex:
7734 // Distinct complex types are incompatible.
7735 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007736 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007737 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007738 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7739 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007740 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007741 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007742 case Type::ObjCObject: {
7743 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007744 // FIXME: This should be type compatibility, e.g. whether
7745 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007746 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7747 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7748 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007749 return LHS;
7750
Eli Friedman47f77112008-08-22 00:56:42 +00007751 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007752 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007753 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007754 if (OfBlockPointer) {
7755 if (canAssignObjCInterfacesInBlockPointer(
7756 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007757 RHS->getAs<ObjCObjectPointerType>(),
7758 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007759 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007760 return QualType();
7761 }
John McCall9dd450b2009-09-21 23:43:11 +00007762 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7763 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007764 return LHS;
7765
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007766 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007767 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007768 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007769
David Blaikie8a40f702012-01-17 06:56:22 +00007770 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007771}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007772
Fariborz Jahanian97676972011-09-28 21:52:05 +00007773bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7774 const FunctionProtoType *FromFunctionType,
7775 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007776 if (FromFunctionType->hasAnyConsumedParams() !=
7777 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007778 return false;
7779 FunctionProtoType::ExtProtoInfo FromEPI =
7780 FromFunctionType->getExtProtoInfo();
7781 FunctionProtoType::ExtProtoInfo ToEPI =
7782 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007783 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007784 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7785 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007786 return false;
7787 }
7788 return true;
7789}
7790
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007791/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7792/// 'RHS' attributes and returns the merged version; including for function
7793/// return types.
7794QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7795 QualType LHSCan = getCanonicalType(LHS),
7796 RHSCan = getCanonicalType(RHS);
7797 // If two types are identical, they are compatible.
7798 if (LHSCan == RHSCan)
7799 return LHS;
7800 if (RHSCan->isFunctionType()) {
7801 if (!LHSCan->isFunctionType())
7802 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007803 QualType OldReturnType =
7804 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007805 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007806 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007807 QualType ResReturnType =
7808 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7809 if (ResReturnType.isNull())
7810 return QualType();
7811 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7812 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7813 // In either case, use OldReturnType to build the new function type.
7814 const FunctionType *F = LHS->getAs<FunctionType>();
7815 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007816 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7817 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007818 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007819 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007820 return ResultType;
7821 }
7822 }
7823 return QualType();
7824 }
7825
7826 // If the qualifiers are different, the types can still be merged.
7827 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7828 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7829 if (LQuals != RQuals) {
7830 // If any of these qualifiers are different, we have a type mismatch.
7831 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7832 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7833 return QualType();
7834
7835 // Exactly one GC qualifier difference is allowed: __strong is
7836 // okay if the other type has no GC qualifier but is an Objective
7837 // C object pointer (i.e. implicitly strong by default). We fix
7838 // this by pretending that the unqualified type was actually
7839 // qualified __strong.
7840 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7841 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7842 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7843
7844 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7845 return QualType();
7846
7847 if (GC_L == Qualifiers::Strong)
7848 return LHS;
7849 if (GC_R == Qualifiers::Strong)
7850 return RHS;
7851 return QualType();
7852 }
7853
7854 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7855 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7856 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7857 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7858 if (ResQT == LHSBaseQT)
7859 return LHS;
7860 if (ResQT == RHSBaseQT)
7861 return RHS;
7862 }
7863 return QualType();
7864}
7865
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007866//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007867// Integer Predicates
7868//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007869
Jay Foad39c79802011-01-12 09:06:06 +00007870unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007871 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007872 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007873 if (T->isBooleanType())
7874 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007875 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007876 return (unsigned)getTypeSize(T);
7877}
7878
Abramo Bagnara13640492012-09-09 10:21:24 +00007879QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007880 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007881
7882 // Turn <4 x signed int> -> <4 x unsigned int>
7883 if (const VectorType *VTy = T->getAs<VectorType>())
7884 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007885 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007886
7887 // For enums, we return the unsigned version of the base type.
7888 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007889 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007890
7891 const BuiltinType *BTy = T->getAs<BuiltinType>();
7892 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007893 switch (BTy->getKind()) {
7894 case BuiltinType::Char_S:
7895 case BuiltinType::SChar:
7896 return UnsignedCharTy;
7897 case BuiltinType::Short:
7898 return UnsignedShortTy;
7899 case BuiltinType::Int:
7900 return UnsignedIntTy;
7901 case BuiltinType::Long:
7902 return UnsignedLongTy;
7903 case BuiltinType::LongLong:
7904 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007905 case BuiltinType::Int128:
7906 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007907 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007908 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007909 }
7910}
7911
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00007912ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007913
Richard Smith1fa5d642013-05-11 05:45:24 +00007914void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7915 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007916
7917//===----------------------------------------------------------------------===//
7918// Builtin Type Computation
7919//===----------------------------------------------------------------------===//
7920
7921/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007922/// pointer over the consumed characters. This returns the resultant type. If
7923/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7924/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7925/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007926///
7927/// RequiresICE is filled in on return to indicate whether the value is required
7928/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007929static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007930 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007931 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007932 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007933 // Modifiers.
7934 int HowLong = 0;
7935 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007936 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007937
Chris Lattnerdc226c22010-10-01 22:42:38 +00007938 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007939 bool Done = false;
7940 while (!Done) {
7941 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007942 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007943 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007944 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007945 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007946 case 'S':
7947 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7948 assert(!Signed && "Can't use 'S' modifier multiple times!");
7949 Signed = true;
7950 break;
7951 case 'U':
7952 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007953 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007954 Unsigned = true;
7955 break;
7956 case 'L':
7957 assert(HowLong <= 2 && "Can't have LLLL modifier");
7958 ++HowLong;
7959 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007960 case 'W':
7961 // This modifier represents int64 type.
7962 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7963 switch (Context.getTargetInfo().getInt64Type()) {
7964 default:
7965 llvm_unreachable("Unexpected integer type");
7966 case TargetInfo::SignedLong:
7967 HowLong = 1;
7968 break;
7969 case TargetInfo::SignedLongLong:
7970 HowLong = 2;
7971 break;
7972 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007973 }
7974 }
7975
7976 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007977
Chris Lattnerecd79c62009-06-14 00:45:47 +00007978 // Read the base type.
7979 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007980 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007981 case 'v':
7982 assert(HowLong == 0 && !Signed && !Unsigned &&
7983 "Bad modifiers used with 'v'!");
7984 Type = Context.VoidTy;
7985 break;
Jack Carter24bef982013-08-15 15:16:57 +00007986 case 'h':
7987 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007988 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007989 Type = Context.HalfTy;
7990 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007991 case 'f':
7992 assert(HowLong == 0 && !Signed && !Unsigned &&
7993 "Bad modifiers used with 'f'!");
7994 Type = Context.FloatTy;
7995 break;
7996 case 'd':
7997 assert(HowLong < 2 && !Signed && !Unsigned &&
7998 "Bad modifiers used with 'd'!");
7999 if (HowLong)
8000 Type = Context.LongDoubleTy;
8001 else
8002 Type = Context.DoubleTy;
8003 break;
8004 case 's':
8005 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8006 if (Unsigned)
8007 Type = Context.UnsignedShortTy;
8008 else
8009 Type = Context.ShortTy;
8010 break;
8011 case 'i':
8012 if (HowLong == 3)
8013 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8014 else if (HowLong == 2)
8015 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8016 else if (HowLong == 1)
8017 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8018 else
8019 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8020 break;
8021 case 'c':
8022 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8023 if (Signed)
8024 Type = Context.SignedCharTy;
8025 else if (Unsigned)
8026 Type = Context.UnsignedCharTy;
8027 else
8028 Type = Context.CharTy;
8029 break;
8030 case 'b': // boolean
8031 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8032 Type = Context.BoolTy;
8033 break;
8034 case 'z': // size_t.
8035 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8036 Type = Context.getSizeType();
8037 break;
8038 case 'F':
8039 Type = Context.getCFConstantStringType();
8040 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008041 case 'G':
8042 Type = Context.getObjCIdType();
8043 break;
8044 case 'H':
8045 Type = Context.getObjCSelType();
8046 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008047 case 'M':
8048 Type = Context.getObjCSuperType();
8049 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008050 case 'a':
8051 Type = Context.getBuiltinVaListType();
8052 assert(!Type.isNull() && "builtin va list type not initialized!");
8053 break;
8054 case 'A':
8055 // This is a "reference" to a va_list; however, what exactly
8056 // this means depends on how va_list is defined. There are two
8057 // different kinds of va_list: ones passed by value, and ones
8058 // passed by reference. An example of a by-value va_list is
8059 // x86, where va_list is a char*. An example of by-ref va_list
8060 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8061 // we want this argument to be a char*&; for x86-64, we want
8062 // it to be a __va_list_tag*.
8063 Type = Context.getBuiltinVaListType();
8064 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008065 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008066 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008067 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008068 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008069 break;
8070 case 'V': {
8071 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008072 unsigned NumElements = strtoul(Str, &End, 10);
8073 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008074 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008075
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008076 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8077 RequiresICE, false);
8078 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008079
8080 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008081 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008082 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008083 break;
8084 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008085 case 'E': {
8086 char *End;
8087
8088 unsigned NumElements = strtoul(Str, &End, 10);
8089 assert(End != Str && "Missing vector size");
8090
8091 Str = End;
8092
8093 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8094 false);
8095 Type = Context.getExtVectorType(ElementType, NumElements);
8096 break;
8097 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008098 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008099 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8100 false);
8101 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008102 Type = Context.getComplexType(ElementType);
8103 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008104 }
8105 case 'Y' : {
8106 Type = Context.getPointerDiffType();
8107 break;
8108 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008109 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008110 Type = Context.getFILEType();
8111 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008112 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008113 return QualType();
8114 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008115 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008116 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008117 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008118 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008119 else
8120 Type = Context.getjmp_bufType();
8121
Mike Stump2adb4da2009-07-28 23:47:15 +00008122 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008123 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008124 return QualType();
8125 }
8126 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008127 case 'K':
8128 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8129 Type = Context.getucontext_tType();
8130
8131 if (Type.isNull()) {
8132 Error = ASTContext::GE_Missing_ucontext;
8133 return QualType();
8134 }
8135 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008136 case 'p':
8137 Type = Context.getProcessIDType();
8138 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008139 }
Mike Stump11289f42009-09-09 15:08:12 +00008140
Chris Lattnerdc226c22010-10-01 22:42:38 +00008141 // If there are modifiers and if we're allowed to parse them, go for it.
8142 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008143 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008144 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008145 default: Done = true; --Str; break;
8146 case '*':
8147 case '&': {
8148 // Both pointers and references can have their pointee types
8149 // qualified with an address space.
8150 char *End;
8151 unsigned AddrSpace = strtoul(Str, &End, 10);
8152 if (End != Str && AddrSpace != 0) {
8153 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8154 Str = End;
8155 }
8156 if (c == '*')
8157 Type = Context.getPointerType(Type);
8158 else
8159 Type = Context.getLValueReferenceType(Type);
8160 break;
8161 }
8162 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8163 case 'C':
8164 Type = Type.withConst();
8165 break;
8166 case 'D':
8167 Type = Context.getVolatileType(Type);
8168 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008169 case 'R':
8170 Type = Type.withRestrict();
8171 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008172 }
8173 }
Chris Lattner84733392010-10-01 07:13:18 +00008174
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008175 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008176 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008177
Chris Lattnerecd79c62009-06-14 00:45:47 +00008178 return Type;
8179}
8180
8181/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008182QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008183 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008184 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008185 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008186
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008187 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008188
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008189 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008190 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008191 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8192 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008193 if (Error != GE_None)
8194 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008195
8196 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8197
Chris Lattnerecd79c62009-06-14 00:45:47 +00008198 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008199 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008200 if (Error != GE_None)
8201 return QualType();
8202
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008203 // If this argument is required to be an IntegerConstantExpression and the
8204 // caller cares, fill in the bitmask we return.
8205 if (RequiresICE && IntegerConstantArgs)
8206 *IntegerConstantArgs |= 1 << ArgTypes.size();
8207
Chris Lattnerecd79c62009-06-14 00:45:47 +00008208 // Do array -> pointer decay. The builtin should use the decayed type.
8209 if (Ty->isArrayType())
8210 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008211
Chris Lattnerecd79c62009-06-14 00:45:47 +00008212 ArgTypes.push_back(Ty);
8213 }
8214
David Majnemerba3e5ec2015-03-13 18:26:17 +00008215 if (Id == Builtin::BI__GetExceptionInfo)
8216 return QualType();
8217
Chris Lattnerecd79c62009-06-14 00:45:47 +00008218 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8219 "'.' should only occur at end of builtin type list!");
8220
Reid Kleckner78af0702013-08-27 23:08:25 +00008221 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008222 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8223
8224 bool Variadic = (TypeStr[0] == '.');
8225
8226 // We really shouldn't be making a no-proto type here, especially in C++.
8227 if (ArgTypes.empty() && Variadic)
8228 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008229
John McCalldb40c7f2010-12-14 08:05:40 +00008230 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008231 EPI.ExtInfo = EI;
8232 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008233
Jordan Rose5c382722013-03-08 21:51:21 +00008234 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008235}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008236
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008237static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8238 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008239 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008240 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008241
Rafael Espindola3ae00052013-05-13 00:12:11 +00008242 GVALinkage External = GVA_StrongExternal;
8243 switch (FD->getTemplateSpecializationKind()) {
8244 case TSK_Undeclared:
8245 case TSK_ExplicitSpecialization:
8246 External = GVA_StrongExternal;
8247 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008248
Rafael Espindola3ae00052013-05-13 00:12:11 +00008249 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008250 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008251
David Majnemerc3d07332014-05-15 06:25:57 +00008252 // C++11 [temp.explicit]p10:
8253 // [ Note: The intent is that an inline function that is the subject of
8254 // an explicit instantiation declaration will still be implicitly
8255 // instantiated when used so that the body can be considered for
8256 // inlining, but that no out-of-line copy of the inline function would be
8257 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008258 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008259 return GVA_AvailableExternally;
8260
Rafael Espindola3ae00052013-05-13 00:12:11 +00008261 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008262 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008263 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008264 }
8265
8266 if (!FD->isInlined())
8267 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008268
David Majnemer3f021502015-10-08 04:53:31 +00008269 if ((!Context.getLangOpts().CPlusPlus &&
8270 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008271 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008272 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008273 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8274
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008275 // GNU or C99 inline semantics. Determine whether this symbol should be
8276 // externally visible.
8277 if (FD->isInlineDefinitionExternallyVisible())
8278 return External;
8279
8280 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008281 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008282 }
8283
David Majnemer54e3ba52014-04-02 23:17:29 +00008284 // Functions specified with extern and inline in -fms-compatibility mode
8285 // forcibly get emitted. While the body of the function cannot be later
8286 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008287 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008288 return GVA_StrongODR;
8289
David Majnemer27d69db2014-04-28 22:17:59 +00008290 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008291}
8292
Artem Belevich7b41f702015-09-23 17:44:53 +00008293static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008294 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8295 // dllexport/dllimport on inline functions.
8296 if (D->hasAttr<DLLImportAttr>()) {
8297 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8298 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008299 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008300 if (L == GVA_DiscardableODR)
8301 return GVA_StrongODR;
8302 }
8303 return L;
8304}
8305
8306GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008307 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8308 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008309}
8310
8311static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8312 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008313 if (!VD->isExternallyVisible())
8314 return GVA_Internal;
8315
David Majnemer27d69db2014-04-28 22:17:59 +00008316 if (VD->isStaticLocal()) {
8317 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8318 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8319 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8320 LexicalContext = LexicalContext->getLexicalParent();
8321
Richard Smith9e2341d2015-03-23 03:25:59 +00008322 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008323 // enclosing function.
8324 if (LexicalContext)
8325 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008326 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008327
8328 // GVA_StrongODR function linkage is stronger than what we need,
8329 // downgrade to GVA_DiscardableODR.
8330 // This allows us to discard the variable if we never end up needing it.
8331 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8332 : StaticLocalLinkage;
8333 }
8334
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008335 // MSVC treats in-class initialized static data members as definitions.
8336 // By giving them non-strong linkage, out-of-line definitions won't
8337 // cause link errors.
8338 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8339 return GVA_DiscardableODR;
8340
Richard Smith8809a0c2013-09-27 20:14:12 +00008341 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008342 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008343 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008344
David Majnemer6d1780c2015-07-17 23:36:49 +00008345 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008346 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8347 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008348 ? GVA_StrongODR
8349 : GVA_StrongExternal;
8350
Rafael Espindola3ae00052013-05-13 00:12:11 +00008351 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008352 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008353
David Majnemer27d69db2014-04-28 22:17:59 +00008354 case TSK_ExplicitInstantiationDeclaration:
8355 return GVA_AvailableExternally;
8356
Rafael Espindola3ae00052013-05-13 00:12:11 +00008357 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008358 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008359 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008360
8361 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008362}
8363
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008364GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008365 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8366 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008367}
8368
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008369bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008370 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8371 if (!VD->isFileVarDecl())
8372 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008373 // Global named register variables (GNU extension) are never emitted.
8374 if (VD->getStorageClass() == SC_Register)
8375 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008376 if (VD->getDescribedVarTemplate() ||
8377 isa<VarTemplatePartialSpecializationDecl>(VD))
8378 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008379 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8380 // We never need to emit an uninstantiated function template.
8381 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8382 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008383 } else if (isa<OMPThreadPrivateDecl>(D))
8384 return true;
8385 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008386 return false;
8387
8388 // If this is a member of a class template, we do not need to emit it.
8389 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008390 return false;
8391
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008392 // Weak references don't produce any output by themselves.
8393 if (D->hasAttr<WeakRefAttr>())
8394 return false;
8395
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008396 // Aliases and used decls are required.
8397 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8398 return true;
8399
8400 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8401 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008402 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008403 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008404
8405 // Constructors and destructors are required.
8406 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8407 return true;
8408
John McCall6bd2a892013-01-25 22:31:03 +00008409 // The key function for a class is required. This rule only comes
8410 // into play when inline functions can be key functions, though.
8411 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8412 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8413 const CXXRecordDecl *RD = MD->getParent();
8414 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8415 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8416 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8417 return true;
8418 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008419 }
8420 }
8421
8422 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8423
8424 // static, static inline, always_inline, and extern inline functions can
8425 // always be deferred. Normal inline functions can be deferred in C99/C++.
8426 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008427 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8428 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008429 return false;
8430 return true;
8431 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008432
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008433 const VarDecl *VD = cast<VarDecl>(D);
8434 assert(VD->isFileVarDecl() && "Expected file scoped var");
8435
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008436 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8437 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008438 return false;
8439
Richard Smitha0e5e542012-11-12 21:38:00 +00008440 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008441 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008442 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8443 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008444 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008445
Richard Smitha0e5e542012-11-12 21:38:00 +00008446 // Variables that have destruction with side-effects are required.
8447 if (VD->getType().isDestructedType())
8448 return true;
8449
8450 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008451 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8452 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008453 return true;
8454
8455 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008456}
Charles Davis53c59df2010-08-16 03:33:14 +00008457
Reid Kleckner78af0702013-08-27 23:08:25 +00008458CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8459 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008460 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008461 if (IsCXXMethod)
8462 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008463
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008464 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8465
8466 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008467}
8468
Jay Foad39c79802011-01-12 09:06:06 +00008469bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008470 // Pass through to the C++ ABI object
8471 return ABI->isNearlyEmpty(RD);
8472}
8473
Reid Kleckner96f8f932014-02-05 17:27:08 +00008474VTableContextBase *ASTContext::getVTableContext() {
8475 if (!VTContext.get()) {
8476 if (Target->getCXXABI().isMicrosoft())
8477 VTContext.reset(new MicrosoftVTableContext(*this));
8478 else
8479 VTContext.reset(new ItaniumVTableContext(*this));
8480 }
8481 return VTContext.get();
8482}
8483
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008484MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008485 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008486 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008487 case TargetCXXABI::GenericItanium:
8488 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008489 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008490 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008491 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008492 case TargetCXXABI::WebAssembly:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008493 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008494 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008495 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008496 }
David Blaikie83d382b2011-09-23 05:06:16 +00008497 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008498}
8499
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008500CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008501
8502size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008503 return ASTRecordLayouts.getMemorySize() +
8504 llvm::capacity_in_bytes(ObjCLayouts) +
8505 llvm::capacity_in_bytes(KeyFunctions) +
8506 llvm::capacity_in_bytes(ObjCImpls) +
8507 llvm::capacity_in_bytes(BlockVarCopyInits) +
8508 llvm::capacity_in_bytes(DeclAttrs) +
8509 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8510 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8511 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8512 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8513 llvm::capacity_in_bytes(OverriddenMethods) +
8514 llvm::capacity_in_bytes(Types) +
8515 llvm::capacity_in_bytes(VariableArrayTypes) +
8516 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008517}
Ted Kremenek540017e2011-10-06 05:00:56 +00008518
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008519/// getIntTypeForBitwidth -
8520/// sets integer QualTy according to specified details:
8521/// bitwidth, signed/unsigned.
8522/// Returns empty type if there is no appropriate target types.
8523QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8524 unsigned Signed) const {
8525 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8526 CanQualType QualTy = getFromTargetType(Ty);
8527 if (!QualTy && DestWidth == 128)
8528 return Signed ? Int128Ty : UnsignedInt128Ty;
8529 return QualTy;
8530}
8531
8532/// getRealTypeForBitwidth -
8533/// sets floating point QualTy according to specified bitwidth.
8534/// Returns empty type if there is no appropriate target types.
8535QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8536 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8537 switch (Ty) {
8538 case TargetInfo::Float:
8539 return FloatTy;
8540 case TargetInfo::Double:
8541 return DoubleTy;
8542 case TargetInfo::LongDouble:
8543 return LongDoubleTy;
8544 case TargetInfo::NoFloat:
8545 return QualType();
8546 }
8547
8548 llvm_unreachable("Unhandled TargetInfo::RealType value");
8549}
8550
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008551void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8552 if (Number > 1)
8553 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008554}
8555
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008556unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8557 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8558 MangleNumbers.find(ND);
8559 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008560}
8561
David Majnemer2206bf52014-03-05 08:57:59 +00008562void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8563 if (Number > 1)
8564 StaticLocalNumbers[VD] = Number;
8565}
8566
8567unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8568 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8569 StaticLocalNumbers.find(VD);
8570 return I != StaticLocalNumbers.end() ? I->second : 1;
8571}
8572
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008573MangleNumberingContext &
8574ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008575 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8576 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8577 if (!MCtx)
8578 MCtx = createMangleNumberingContext();
8579 return *MCtx;
8580}
8581
8582MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8583 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008584}
8585
David Majnemere7a818f2015-03-06 18:53:55 +00008586const CXXConstructorDecl *
8587ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8588 return ABI->getCopyConstructorForExceptionObject(
8589 cast<CXXRecordDecl>(RD->getFirstDecl()));
8590}
8591
8592void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8593 CXXConstructorDecl *CD) {
8594 return ABI->addCopyConstructorForExceptionObject(
8595 cast<CXXRecordDecl>(RD->getFirstDecl()),
8596 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8597}
8598
David Majnemerdfa6d202015-03-11 18:36:39 +00008599void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8600 unsigned ParmIdx, Expr *DAE) {
8601 ABI->addDefaultArgExprForConstructor(
8602 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8603}
8604
8605Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8606 unsigned ParmIdx) {
8607 return ABI->getDefaultArgExprForConstructor(
8608 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8609}
8610
David Majnemer00350522015-08-31 18:48:39 +00008611void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8612 TypedefNameDecl *DD) {
8613 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8614}
8615
8616TypedefNameDecl *
8617ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8618 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8619}
8620
8621void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8622 DeclaratorDecl *DD) {
8623 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8624}
8625
8626DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8627 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8628}
8629
Ted Kremenek540017e2011-10-06 05:00:56 +00008630void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8631 ParamIndices[D] = index;
8632}
8633
8634unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8635 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8636 assert(I != ParamIndices.end() &&
8637 "ParmIndices lacks entry set by ParmVarDecl");
8638 return I->second;
8639}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008640
Richard Smithe6c01442013-06-05 00:46:14 +00008641APValue *
8642ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8643 bool MayCreate) {
8644 assert(E && E->getStorageDuration() == SD_Static &&
8645 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008646 if (MayCreate) {
8647 APValue *&MTVI = MaterializedTemporaryValues[E];
8648 if (!MTVI)
8649 MTVI = new (*this) APValue;
8650 return MTVI;
8651 }
Richard Smithe6c01442013-06-05 00:46:14 +00008652
David Majnemer2dcef9e2015-08-13 23:50:15 +00008653 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008654}
8655
Fariborz Jahanian615de762013-05-28 17:37:39 +00008656bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8657 const llvm::Triple &T = getTargetInfo().getTriple();
8658 if (!T.isOSDarwin())
8659 return false;
8660
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008661 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8662 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8663 return false;
8664
Fariborz Jahanian615de762013-05-28 17:37:39 +00008665 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8666 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8667 uint64_t Size = sizeChars.getQuantity();
8668 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8669 unsigned Align = alignChars.getQuantity();
8670 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8671 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8672}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008673
8674namespace {
8675
8676 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8677 /// parents as defined by the \c RecursiveASTVisitor.
8678 ///
8679 /// Note that the relationship described here is purely in terms of AST
8680 /// traversal - there are other relationships (for example declaration context)
8681 /// in the AST that are better modeled by special matchers.
8682 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008683 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008684 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8685
8686 public:
8687 /// \brief Builds and returns the translation unit's parent map.
8688 ///
8689 /// The caller takes ownership of the returned \c ParentMap.
8690 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8691 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8692 Visitor.TraverseDecl(&TU);
8693 return Visitor.Parents;
8694 }
8695
8696 private:
8697 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8698
8699 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8700 }
8701
8702 bool shouldVisitTemplateInstantiations() const {
8703 return true;
8704 }
8705 bool shouldVisitImplicitCode() const {
8706 return true;
8707 }
8708 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8709 // are not triggered during data recursion.
8710 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8711 return false;
8712 }
8713
8714 template <typename T>
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008715 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008716 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008717 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008718 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008719 // FIXME: Currently we add the same parent multiple times, but only
8720 // when no memoization data is available for the type.
8721 // For example when we visit all subexpressions of template
8722 // instantiations; this is suboptimal, but benign: the only way to
8723 // visit those is with hasAncestor / hasParent, and those do not create
8724 // new matches.
8725 // The plan is to enable DynTypedNode to be storable in a map or hash
8726 // map. The main problem there is to implement hash functions /
8727 // comparison operators for all types that DynTypedNode supports that
8728 // do not have pointer identity.
8729 auto &NodeOrVector = (*Parents)[Node];
Manuel Klimek95403e62014-05-21 13:28:59 +00008730 if (NodeOrVector.isNull()) {
8731 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008732 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008733 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8734 auto *Node =
8735 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8736 auto *Vector = new ASTContext::ParentVector(1, *Node);
8737 NodeOrVector = Vector;
8738 delete Node;
8739 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008740 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008741
8742 auto *Vector =
8743 NodeOrVector.template get<ASTContext::ParentVector *>();
8744 // Skip duplicates for types that have memoization data.
8745 // We must check that the type has memoization data before calling
8746 // std::find() because DynTypedNode::operator== can't compare all
8747 // types.
8748 bool Found = ParentStack.back().getMemoizationData() &&
8749 std::find(Vector->begin(), Vector->end(),
8750 ParentStack.back()) != Vector->end();
8751 if (!Found)
8752 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008753 }
8754 }
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008755 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008756 bool Result = (this ->* traverse) (Node);
8757 ParentStack.pop_back();
8758 return Result;
8759 }
8760
8761 bool TraverseDecl(Decl *DeclNode) {
8762 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8763 }
8764
8765 bool TraverseStmt(Stmt *StmtNode) {
8766 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8767 }
8768
8769 ASTContext::ParentMap *Parents;
8770 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8771
8772 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8773 };
8774
8775} // end namespace
8776
Benjamin Kramer07935292014-10-04 17:01:26 +00008777ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008778ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008779 assert(Node.getMemoizationData() &&
8780 "Invariant broken: only nodes that support memoization may be "
8781 "used in the parent map.");
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008782 if (!AllParents) {
8783 // We always need to run over the whole translation unit, as
8784 // hasAncestor can escape any subtree.
8785 AllParents.reset(
8786 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8787 }
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008788 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008789 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008790 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008791 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008792 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8793 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008794 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008795 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008796}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008797
8798bool
8799ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8800 const ObjCMethodDecl *MethodImpl) {
8801 // No point trying to match an unavailable/deprecated mothod.
8802 if (MethodDecl->hasAttr<UnavailableAttr>()
8803 || MethodDecl->hasAttr<DeprecatedAttr>())
8804 return false;
8805 if (MethodDecl->getObjCDeclQualifier() !=
8806 MethodImpl->getObjCDeclQualifier())
8807 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008808 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008809 return false;
8810
8811 if (MethodDecl->param_size() != MethodImpl->param_size())
8812 return false;
8813
8814 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8815 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8816 EF = MethodDecl->param_end();
8817 IM != EM && IF != EF; ++IM, ++IF) {
8818 const ParmVarDecl *DeclVar = (*IF);
8819 const ParmVarDecl *ImplVar = (*IM);
8820 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8821 return false;
8822 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8823 return false;
8824 }
8825 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8826
8827}
Richard Smith053f6c62014-05-16 23:01:30 +00008828
8829// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8830// doesn't include ASTContext.h
8831template
8832clang::LazyGenerationalUpdatePtr<
8833 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8834clang::LazyGenerationalUpdatePtr<
8835 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8836 const clang::ASTContext &Ctx, Decl *Value);