blob: b07a21301eee4302f739595234408995948651c1 [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),
736 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
737 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
738 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
739 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
740 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
741 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000742 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
743 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000744 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000745 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
746 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
747 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
748 Comments(SM), CommentsLoaded(false),
749 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000750 TUDecl = TranslationUnitDecl::Create(*this);
751}
752
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000753ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000754 ReleaseParentMapEntries();
755
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000756 // Release the DenseMaps associated with DeclContext objects.
757 // FIXME: Is this the ideal solution?
758 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000759
Manuel Klimeka7328992013-06-03 13:51:33 +0000760 // Call all of the deallocation functions on all of their targets.
761 for (DeallocationMap::const_iterator I = Deallocations.begin(),
762 E = Deallocations.end(); I != E; ++I)
763 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
764 (I->first)((I->second)[J]);
765
Ted Kremenek076baeb2010-06-08 23:00:58 +0000766 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000767 // because they can contain DenseMaps.
768 for (llvm::DenseMap<const ObjCContainerDecl*,
769 const ASTRecordLayout*>::iterator
770 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
771 // Increment in loop to prevent using deallocated memory.
772 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
773 R->Destroy(*this);
774
Ted Kremenek076baeb2010-06-08 23:00:58 +0000775 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
776 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
777 // Increment in loop to prevent using deallocated memory.
778 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
779 R->Destroy(*this);
780 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000781
782 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
783 AEnd = DeclAttrs.end();
784 A != AEnd; ++A)
785 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000786
David Majnemere694f3e2015-08-14 14:43:50 +0000787 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
788 MaterializedTemporaryValues)
789 MTVPair.second->~APValue();
790
Reid Kleckner588c9372014-02-19 23:44:52 +0000791 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000792}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000793
Manuel Klimek95403e62014-05-21 13:28:59 +0000794void ASTContext::ReleaseParentMapEntries() {
795 if (!AllParents) return;
796 for (const auto &Entry : *AllParents) {
797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
799 } else {
800 assert(Entry.second.is<ParentVector *>());
801 delete Entry.second.get<ParentVector *>();
802 }
803 }
804}
805
Douglas Gregor1a809332010-05-23 18:26:36 +0000806void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000807 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000808}
809
Mike Stump11289f42009-09-09 15:08:12 +0000810void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000811ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
812 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000813}
814
Chris Lattner4eb445d2007-01-26 01:27:23 +0000815void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000816 llvm::errs() << "\n*** AST Context Stats:\n";
817 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000818
Douglas Gregora30d0462009-05-26 14:40:08 +0000819 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000820#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000821#define ABSTRACT_TYPE(Name, Parent)
822#include "clang/AST/TypeNodes.def"
823 0 // Extra
824 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000825
Chris Lattner4eb445d2007-01-26 01:27:23 +0000826 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
827 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000828 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000829 }
830
Douglas Gregora30d0462009-05-26 14:40:08 +0000831 unsigned Idx = 0;
832 unsigned TotalBytes = 0;
833#define TYPE(Name, Parent) \
834 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000835 llvm::errs() << " " << counts[Idx] << " " << #Name \
836 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000837 TotalBytes += counts[Idx] * sizeof(Name##Type); \
838 ++Idx;
839#define ABSTRACT_TYPE(Name, Parent)
840#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000841
Chandler Carruth3c147a72011-07-04 05:32:14 +0000842 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
843
Douglas Gregor7454c562010-07-02 20:37:36 +0000844 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
846 << NumImplicitDefaultConstructors
847 << " implicit default constructors created\n";
848 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
849 << NumImplicitCopyConstructors
850 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000851 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
853 << NumImplicitMoveConstructors
854 << " implicit move constructors created\n";
855 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
856 << NumImplicitCopyAssignmentOperators
857 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000858 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000859 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
860 << NumImplicitMoveAssignmentOperators
861 << " implicit move assignment operators created\n";
862 llvm::errs() << NumImplicitDestructorsDeclared << "/"
863 << NumImplicitDestructors
864 << " implicit destructors created\n";
865
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000866 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000868 ExternalSource->PrintStats();
869 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000870
Douglas Gregor5b11d492010-07-25 17:53:33 +0000871 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000872}
873
Richard Smith42413142015-05-15 20:05:43 +0000874void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
875 bool NotifyListeners) {
876 if (NotifyListeners)
877 if (auto *Listener = getASTMutationListener())
878 Listener->RedefinedHiddenDefinition(ND, M);
879
880 if (getLangOpts().ModulesLocalVisibility)
881 MergedDefModules[ND].push_back(M);
882 else
883 ND->setHidden(false);
884}
885
886void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
887 auto It = MergedDefModules.find(ND);
888 if (It == MergedDefModules.end())
889 return;
890
891 auto &Merged = It->second;
892 llvm::DenseSet<Module*> Found;
893 for (Module *&M : Merged)
894 if (!Found.insert(M).second)
895 M = nullptr;
896 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
897}
898
Richard Smithf19e1272015-03-07 00:04:49 +0000899ExternCContextDecl *ASTContext::getExternCContextDecl() const {
900 if (!ExternCContext)
901 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
902
903 return ExternCContext;
904}
905
Alp Toker2dea15b2013-12-17 01:22:38 +0000906RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
907 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000908 SourceLocation Loc;
909 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000910 if (getLangOpts().CPlusPlus)
911 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
912 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000913 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000914 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
915 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000916 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000917 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
918 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000919 return NewDecl;
920}
921
922TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
923 StringRef Name) const {
924 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
925 TypedefDecl *NewDecl = TypedefDecl::Create(
926 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
927 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
928 NewDecl->setImplicit();
929 return NewDecl;
930}
931
Douglas Gregor801c99d2011-08-12 06:49:56 +0000932TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000933 if (!Int128Decl)
934 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000935 return Int128Decl;
936}
937
938TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000939 if (!UInt128Decl)
940 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000941 return UInt128Decl;
942}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000943
Nico Webere1687c52013-06-20 21:44:55 +0000944TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000945 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000946 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000947 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000948
Nico Webere1687c52013-06-20 21:44:55 +0000949 return Float128StubDecl;
950}
951
John McCall48f2d582009-10-23 23:03:21 +0000952void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000953 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000954 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000955 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000956}
957
Douglas Gregore8bbc122011-09-02 00:18:52 +0000958void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
959 assert((!this->Target || this->Target == &Target) &&
960 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000961 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000962
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963 this->Target = &Target;
964
965 ABI.reset(createCXXABI(Target));
966 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000967 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000968
Chris Lattner970e54e2006-11-12 00:37:36 +0000969 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000970 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattner970e54e2006-11-12 00:37:36 +0000972 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000973 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000974 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000975 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000976 InitBuiltinType(CharTy, BuiltinType::Char_S);
977 else
978 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000979 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000980 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
981 InitBuiltinType(ShortTy, BuiltinType::Short);
982 InitBuiltinType(IntTy, BuiltinType::Int);
983 InitBuiltinType(LongTy, BuiltinType::Long);
984 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattner970e54e2006-11-12 00:37:36 +0000986 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000987 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
988 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
989 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
990 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
991 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000992
Chris Lattner970e54e2006-11-12 00:37:36 +0000993 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000994 InitBuiltinType(FloatTy, BuiltinType::Float);
995 InitBuiltinType(DoubleTy, BuiltinType::Double);
996 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000997
Chris Lattnerf122cef2009-04-30 02:43:43 +0000998 // GNU extension, 128-bit integers.
999 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1000 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1001
Hans Wennborg0d81e012013-05-10 10:08:40 +00001002 // C++ 3.9.1p5
1003 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1004 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1005 else // -fshort-wchar makes wchar_t be unsigned.
1006 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1007 if (LangOpts.CPlusPlus && LangOpts.WChar)
1008 WideCharTy = WCharTy;
1009 else {
1010 // C99 (or C++ using -fno-wchar).
1011 WideCharTy = getFromTargetType(Target.getWCharType());
1012 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001013
James Molloy36365542012-05-04 10:55:22 +00001014 WIntTy = getFromTargetType(Target.getWIntType());
1015
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001016 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1017 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1018 else // C99
1019 Char16Ty = getFromTargetType(Target.getChar16Type());
1020
1021 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1022 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1023 else // C99
1024 Char32Ty = getFromTargetType(Target.getChar32Type());
1025
Douglas Gregor4619e432008-12-05 23:32:09 +00001026 // Placeholder type for type-dependent expressions whose type is
1027 // completely unknown. No code should ever check a type against
1028 // DependentTy and users should never see it; however, it is here to
1029 // help diagnose failures to properly check for type-dependent
1030 // expressions.
1031 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032
John McCall36e7fe32010-10-12 00:20:44 +00001033 // Placeholder type for functions.
1034 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1035
John McCall0009fcc2011-04-26 20:42:42 +00001036 // Placeholder type for bound members.
1037 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1038
John McCall526ab472011-10-25 17:37:35 +00001039 // Placeholder type for pseudo-objects.
1040 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1041
John McCall31996342011-04-07 08:22:57 +00001042 // "any" type; useful for debugger-like clients.
1043 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1044
John McCall8a6b59a2011-10-17 18:09:15 +00001045 // Placeholder type for unbridged ARC casts.
1046 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1047
Eli Friedman34866c72012-08-31 00:14:07 +00001048 // Placeholder type for builtin functions.
1049 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1050
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001051 // Placeholder type for OMP array sections.
1052 if (LangOpts.OpenMP)
1053 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1054
Chris Lattner970e54e2006-11-12 00:37:36 +00001055 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001056 FloatComplexTy = getComplexType(FloatTy);
1057 DoubleComplexTy = getComplexType(DoubleTy);
1058 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001060 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001061 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1062 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001063 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001064
1065 if (LangOpts.OpenCL) {
1066 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1067 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1068 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1069 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1070 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1071 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001072
Guy Benyei61054192013-02-07 10:55:47 +00001073 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001074 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001075 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001076
1077 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001078 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1079 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001080
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001081 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001082
1083 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001084
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001085 // void * type
1086 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001087
1088 // nullptr type (C++0x 2.14.7)
1089 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001090
1091 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1092 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001093
1094 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001095 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001096}
1097
David Blaikie9c902b52011-09-25 23:23:43 +00001098DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001099 return SourceMgr.getDiagnostics();
1100}
1101
Douglas Gregor561eceb2010-08-30 16:49:28 +00001102AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1103 AttrVec *&Result = DeclAttrs[D];
1104 if (!Result) {
1105 void *Mem = Allocate(sizeof(AttrVec));
1106 Result = new (Mem) AttrVec;
1107 }
1108
1109 return *Result;
1110}
1111
1112/// \brief Erase the attributes corresponding to the given declaration.
1113void ASTContext::eraseDeclAttrs(const Decl *D) {
1114 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1115 if (Pos != DeclAttrs.end()) {
1116 Pos->second->~AttrVec();
1117 DeclAttrs.erase(Pos);
1118 }
1119}
1120
Larisse Voufo39a1e502013-08-06 01:03:05 +00001121// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001122MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001123ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001124 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001125 return getTemplateOrSpecializationInfo(Var)
1126 .dyn_cast<MemberSpecializationInfo *>();
1127}
1128
1129ASTContext::TemplateOrSpecializationInfo
1130ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1131 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1132 TemplateOrInstantiation.find(Var);
1133 if (Pos == TemplateOrInstantiation.end())
1134 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001135
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001136 return Pos->second;
1137}
1138
Mike Stump11289f42009-09-09 15:08:12 +00001139void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001140ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001141 TemplateSpecializationKind TSK,
1142 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001143 assert(Inst->isStaticDataMember() && "Not a static data member");
1144 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001145 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1146 Tmpl, TSK, PointOfInstantiation));
1147}
1148
1149void
1150ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1151 TemplateOrSpecializationInfo TSI) {
1152 assert(!TemplateOrInstantiation[Inst] &&
1153 "Already noted what the variable was instantiated from");
1154 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001155}
1156
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001157FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1158 const FunctionDecl *FD){
1159 assert(FD && "Specialization is 0");
1160 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001161 = ClassScopeSpecializationPattern.find(FD);
1162 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001163 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001164
1165 return Pos->second;
1166}
1167
1168void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1169 FunctionDecl *Pattern) {
1170 assert(FD && "Specialization is 0");
1171 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001172 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001173}
1174
John McCalle61f2ba2009-11-18 02:36:19 +00001175NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001176ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001177 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001178 = InstantiatedFromUsingDecl.find(UUD);
1179 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001180 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001181
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001182 return Pos->second;
1183}
1184
1185void
John McCallb96ec562009-12-04 22:46:56 +00001186ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1187 assert((isa<UsingDecl>(Pattern) ||
1188 isa<UnresolvedUsingValueDecl>(Pattern) ||
1189 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1190 "pattern decl is not a using decl");
1191 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1192 InstantiatedFromUsingDecl[Inst] = Pattern;
1193}
1194
1195UsingShadowDecl *
1196ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1197 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1198 = InstantiatedFromUsingShadowDecl.find(Inst);
1199 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001200 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001201
1202 return Pos->second;
1203}
1204
1205void
1206ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1207 UsingShadowDecl *Pattern) {
1208 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1209 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001210}
1211
Anders Carlsson5da84842009-09-01 04:26:58 +00001212FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1213 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1214 = InstantiatedFromUnnamedFieldDecl.find(Field);
1215 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001216 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001217
Anders Carlsson5da84842009-09-01 04:26:58 +00001218 return Pos->second;
1219}
1220
1221void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1222 FieldDecl *Tmpl) {
1223 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1224 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1225 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1226 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001227
Anders Carlsson5da84842009-09-01 04:26:58 +00001228 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1229}
1230
Douglas Gregor832940b2010-03-02 23:58:15 +00001231ASTContext::overridden_cxx_method_iterator
1232ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1233 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001234 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001235 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001236 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001237
1238 return Pos->second.begin();
1239}
1240
1241ASTContext::overridden_cxx_method_iterator
1242ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1243 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001244 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001245 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001246 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001247
1248 return Pos->second.end();
1249}
1250
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001251unsigned
1252ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1253 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001254 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001255 if (Pos == OverriddenMethods.end())
1256 return 0;
1257
1258 return Pos->second.size();
1259}
1260
Douglas Gregor832940b2010-03-02 23:58:15 +00001261void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1262 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001263 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001264 OverriddenMethods[Method].push_back(Overridden);
1265}
1266
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001267void ASTContext::getOverriddenMethods(
1268 const NamedDecl *D,
1269 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001270 assert(D);
1271
1272 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001273 Overridden.append(overridden_methods_begin(CXXMethod),
1274 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001275 return;
1276 }
1277
1278 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1279 if (!Method)
1280 return;
1281
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001282 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1283 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001284 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001285}
1286
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001287void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1288 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1289 assert(!Import->isFromASTFile() && "Non-local import declaration");
1290 if (!FirstLocalImport) {
1291 FirstLocalImport = Import;
1292 LastLocalImport = Import;
1293 return;
1294 }
1295
1296 LastLocalImport->NextLocalImport = Import;
1297 LastLocalImport = Import;
1298}
1299
Chris Lattner53cfe802007-07-18 17:52:12 +00001300//===----------------------------------------------------------------------===//
1301// Type Sizing and Analysis
1302//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001303
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001304/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1305/// scalar floating point type.
1306const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001307 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001308 assert(BT && "Not a floating point type!");
1309 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001310 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001311 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001312 case BuiltinType::Float: return Target->getFloatFormat();
1313 case BuiltinType::Double: return Target->getDoubleFormat();
1314 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001315 }
1316}
1317
Rafael Espindola71eccb32013-08-08 19:53:46 +00001318CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001319 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001320
John McCall94268702010-10-08 18:24:19 +00001321 bool UseAlignAttrOnly = false;
1322 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1323 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001324
John McCall94268702010-10-08 18:24:19 +00001325 // __attribute__((aligned)) can increase or decrease alignment
1326 // *except* on a struct or struct member, where it only increases
1327 // alignment unless 'packed' is also specified.
1328 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001329 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001330 // ignore that possibility; Sema should diagnose it.
1331 if (isa<FieldDecl>(D)) {
1332 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1333 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1334 } else {
1335 UseAlignAttrOnly = true;
1336 }
1337 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001338 else if (isa<FieldDecl>(D))
1339 UseAlignAttrOnly =
1340 D->hasAttr<PackedAttr>() ||
1341 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001342
John McCall4e819612011-01-20 07:57:12 +00001343 // If we're using the align attribute only, just ignore everything
1344 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001345 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001346 // do nothing
1347
John McCall94268702010-10-08 18:24:19 +00001348 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001349 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001350 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001351 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001352 T = RT->getPointeeType();
1353 else
1354 T = getPointerType(RT->getPointeeType());
1355 }
Richard Smithf6d70302014-06-10 23:34:28 +00001356 QualType BaseT = getBaseElementType(T);
1357 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001358 // Adjust alignments of declarations with array type by the
1359 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001360 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001361 unsigned MinWidth = Target->getLargeArrayMinWidth();
1362 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001363 if (isa<VariableArrayType>(arrayType))
1364 Align = std::max(Align, Target->getLargeArrayAlign());
1365 else if (isa<ConstantArrayType>(arrayType) &&
1366 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1367 Align = std::max(Align, Target->getLargeArrayAlign());
1368 }
John McCall33ddac02011-01-19 10:06:00 +00001369 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001370 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001371 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001372 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001373 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1374 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001375 }
John McCall4e819612011-01-20 07:57:12 +00001376
1377 // Fields can be subject to extra alignment constraints, like if
1378 // the field is packed, the struct is packed, or the struct has a
1379 // a max-field-alignment constraint (#pragma pack). So calculate
1380 // the actual alignment of the field within the struct, and then
1381 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001382 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1383 const RecordDecl *Parent = Field->getParent();
1384 // We can only produce a sensible answer if the record is valid.
1385 if (!Parent->isInvalidDecl()) {
1386 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001387
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001388 // Start with the record's overall alignment.
1389 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001390
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001391 // Use the GCD of that and the offset within the record.
1392 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1393 if (Offset > 0) {
1394 // Alignment is always a power of 2, so the GCD will be a power of 2,
1395 // which means we get to do this crazy thing instead of Euclid's.
1396 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1397 if (LowBitOfOffset < FieldAlign)
1398 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1399 }
1400
1401 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001402 }
Charles Davis3fc51072010-02-23 04:52:00 +00001403 }
Chris Lattner68061312009-01-24 21:53:27 +00001404 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001405
Ken Dyckcc56c542011-01-15 18:38:59 +00001406 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001407}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001408
John McCallf1249922012-08-21 04:10:00 +00001409// getTypeInfoDataSizeInChars - Return the size of a type, in
1410// chars. If the type is a record, its data size is returned. This is
1411// the size of the memcpy that's performed when assigning this type
1412// using a trivial copy/move assignment operator.
1413std::pair<CharUnits, CharUnits>
1414ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1415 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1416
1417 // In C++, objects can sometimes be allocated into the tail padding
1418 // of a base-class subobject. We decide whether that's possible
1419 // during class layout, so here we can just trust the layout results.
1420 if (getLangOpts().CPlusPlus) {
1421 if (const RecordType *RT = T->getAs<RecordType>()) {
1422 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1423 sizeAndAlign.first = layout.getDataSize();
1424 }
1425 }
1426
1427 return sizeAndAlign;
1428}
1429
Richard Trieu04d2d942013-05-14 21:59:17 +00001430/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1431/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1432std::pair<CharUnits, CharUnits>
1433static getConstantArrayInfoInChars(const ASTContext &Context,
1434 const ConstantArrayType *CAT) {
1435 std::pair<CharUnits, CharUnits> EltInfo =
1436 Context.getTypeInfoInChars(CAT->getElementType());
1437 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001438 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1439 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001440 "Overflow in array type char size evaluation");
1441 uint64_t Width = EltInfo.first.getQuantity() * Size;
1442 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001443 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1444 Context.getTargetInfo().getPointerWidth(0) == 64)
1445 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001446 return std::make_pair(CharUnits::fromQuantity(Width),
1447 CharUnits::fromQuantity(Align));
1448}
1449
John McCall87fe5d52010-05-20 01:18:31 +00001450std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001451ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001452 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1453 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001454 TypeInfo Info = getTypeInfo(T);
1455 return std::make_pair(toCharUnitsFromBits(Info.Width),
1456 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001457}
1458
1459std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001460ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001461 return getTypeInfoInChars(T.getTypePtr());
1462}
1463
David Majnemer34b57492014-07-30 01:30:47 +00001464bool ASTContext::isAlignmentRequired(const Type *T) const {
1465 return getTypeInfo(T).AlignIsRequired;
1466}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001467
David Majnemer34b57492014-07-30 01:30:47 +00001468bool ASTContext::isAlignmentRequired(QualType T) const {
1469 return isAlignmentRequired(T.getTypePtr());
1470}
1471
1472TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001473 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1474 if (I != MemoizedTypeInfo.end())
1475 return I->second;
1476
1477 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1478 TypeInfo TI = getTypeInfoImpl(T);
1479 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001480 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001481}
1482
1483/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1484/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001485///
1486/// FIXME: Pointers into different addr spaces could have different sizes and
1487/// alignment requirements: getPointerInfo should take an AddrSpace, this
1488/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001489TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1490 uint64_t Width = 0;
1491 unsigned Align = 8;
1492 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001493 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001494#define TYPE(Class, Base)
1495#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001496#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001497#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001498#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1499 case Type::Class: \
1500 assert(!T->isDependentType() && "should not see dependent types here"); \
1501 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001502#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001503 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001504
Chris Lattner355332d2007-07-13 22:27:08 +00001505 case Type::FunctionNoProto:
1506 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001507 // GCC extension: alignof(function) = 32 bits
1508 Width = 0;
1509 Align = 32;
1510 break;
1511
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001512 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001513 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001514 Width = 0;
1515 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1516 break;
1517
Steve Naroff5c131802007-08-30 01:06:46 +00001518 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001519 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001520
David Majnemer34b57492014-07-30 01:30:47 +00001521 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001522 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001523 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001524 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001525 Width = EltInfo.Width * Size;
1526 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001527 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1528 getTargetInfo().getPointerWidth(0) == 64)
1529 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001530 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001531 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001532 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001533 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001534 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001535 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1536 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001537 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001538 // If the alignment is not a power of 2, round up to the next power of 2.
1539 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001540 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001541 Align = llvm::NextPowerOf2(Align);
1542 Width = llvm::RoundUpToAlignment(Width, Align);
1543 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001544 // Adjust the alignment based on the target max.
1545 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1546 if (TargetVectorAlign && TargetVectorAlign < Align)
1547 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001548 break;
1549 }
Chris Lattner647fb222007-07-18 18:26:58 +00001550
Chris Lattner7570e9c2008-03-08 08:52:55 +00001551 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001552 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001553 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001554 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001555 // GCC extension: alignof(void) = 8 bits.
1556 Width = 0;
1557 Align = 8;
1558 break;
1559
Chris Lattner6a4f7452007-12-19 19:23:28 +00001560 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001561 Width = Target->getBoolWidth();
1562 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001563 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001564 case BuiltinType::Char_S:
1565 case BuiltinType::Char_U:
1566 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001567 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001568 Width = Target->getCharWidth();
1569 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001570 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001571 case BuiltinType::WChar_S:
1572 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001573 Width = Target->getWCharWidth();
1574 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001575 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001576 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001577 Width = Target->getChar16Width();
1578 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001579 break;
1580 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001581 Width = Target->getChar32Width();
1582 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001583 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001584 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001585 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001586 Width = Target->getShortWidth();
1587 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001588 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001589 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001590 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001591 Width = Target->getIntWidth();
1592 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001593 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001594 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001595 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001596 Width = Target->getLongWidth();
1597 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001598 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001599 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001600 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001601 Width = Target->getLongLongWidth();
1602 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001603 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001604 case BuiltinType::Int128:
1605 case BuiltinType::UInt128:
1606 Width = 128;
1607 Align = 128; // int128_t is 128-bit aligned on all targets.
1608 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001609 case BuiltinType::Half:
1610 Width = Target->getHalfWidth();
1611 Align = Target->getHalfAlign();
1612 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001613 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 Width = Target->getFloatWidth();
1615 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001616 break;
1617 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001618 Width = Target->getDoubleWidth();
1619 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001620 break;
1621 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001622 Width = Target->getLongDoubleWidth();
1623 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001624 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001625 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001626 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1627 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001628 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001629 case BuiltinType::ObjCId:
1630 case BuiltinType::ObjCClass:
1631 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001632 Width = Target->getPointerWidth(0);
1633 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001634 break;
Guy Benyei61054192013-02-07 10:55:47 +00001635 case BuiltinType::OCLSampler:
1636 // Samplers are modeled as integers.
1637 Width = Target->getIntWidth();
1638 Align = Target->getIntAlign();
1639 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001640 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001641 case BuiltinType::OCLImage1d:
1642 case BuiltinType::OCLImage1dArray:
1643 case BuiltinType::OCLImage1dBuffer:
1644 case BuiltinType::OCLImage2d:
1645 case BuiltinType::OCLImage2dArray:
1646 case BuiltinType::OCLImage3d:
1647 // Currently these types are pointers to opaque types.
1648 Width = Target->getPointerWidth(0);
1649 Align = Target->getPointerAlign(0);
1650 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001651 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001652 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001653 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001654 Width = Target->getPointerWidth(0);
1655 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001656 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001657 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001658 unsigned AS = getTargetAddressSpace(
1659 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001660 Width = Target->getPointerWidth(AS);
1661 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001662 break;
1663 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001664 case Type::LValueReference:
1665 case Type::RValueReference: {
1666 // alignof and sizeof should never enter this code path here, so we go
1667 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001668 unsigned AS = getTargetAddressSpace(
1669 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001670 Width = Target->getPointerWidth(AS);
1671 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001672 break;
1673 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001674 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001675 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001676 Width = Target->getPointerWidth(AS);
1677 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001678 break;
1679 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001680 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001681 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001682 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001683 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001684 }
Chris Lattner647fb222007-07-18 18:26:58 +00001685 case Type::Complex: {
1686 // Complex types have the same alignment as their elements, but twice the
1687 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001688 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1689 Width = EltInfo.Width * 2;
1690 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001691 break;
1692 }
John McCall8b07ec22010-05-15 11:32:37 +00001693 case Type::ObjCObject:
1694 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001695 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001696 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001697 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001698 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001699 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001700 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001701 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001702 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001703 break;
1704 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001705 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001706 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001707 const TagType *TT = cast<TagType>(T);
1708
1709 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001710 Width = 8;
1711 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001712 break;
1713 }
Mike Stump11289f42009-09-09 15:08:12 +00001714
David Majnemer475b25e2015-01-21 10:54:38 +00001715 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1716 const EnumDecl *ED = ET->getDecl();
1717 TypeInfo Info =
1718 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1719 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1720 Info.Align = AttrAlign;
1721 Info.AlignIsRequired = true;
1722 }
1723 return Info;
1724 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001725
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001726 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001727 const RecordDecl *RD = RT->getDecl();
1728 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001729 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001730 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001731 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001732 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001733 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001734
Chris Lattner63d2b362009-10-22 05:17:15 +00001735 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001736 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1737 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001738
Richard Smith30482bc2011-02-20 03:19:35 +00001739 case Type::Auto: {
1740 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001741 assert(!A->getDeducedType().isNull() &&
1742 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001743 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001744 }
1745
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001746 case Type::Paren:
1747 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1748
Douglas Gregoref462e62009-04-30 17:32:17 +00001749 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001750 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001751 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001752 // If the typedef has an aligned attribute on it, it overrides any computed
1753 // alignment we have. This violates the GCC documentation (which says that
1754 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001755 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001756 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001757 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001758 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001759 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001760 AlignIsRequired = Info.AlignIsRequired;
1761 }
David Majnemer34b57492014-07-30 01:30:47 +00001762 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001763 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001764 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001765
Abramo Bagnara6150c882010-05-11 21:36:43 +00001766 case Type::Elaborated:
1767 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001768
John McCall81904512011-01-06 01:58:22 +00001769 case Type::Attributed:
1770 return getTypeInfo(
1771 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1772
Eli Friedman0dfb8892011-10-06 23:00:33 +00001773 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001774 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001775 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1776 Width = Info.Width;
1777 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001778
1779 // If the size of the type doesn't exceed the platform's max
1780 // atomic promotion width, make the size and alignment more
1781 // favorable to atomic operations:
1782 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1783 // Round the size up to a power of 2.
1784 if (!llvm::isPowerOf2_64(Width))
1785 Width = llvm::NextPowerOf2(Width);
1786
1787 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001788 Align = static_cast<unsigned>(Width);
1789 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001790 }
1791
Douglas Gregoref462e62009-04-30 17:32:17 +00001792 }
Mike Stump11289f42009-09-09 15:08:12 +00001793
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001794 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001795 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001796}
1797
Alexey Bataev00396512015-07-02 03:40:19 +00001798unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1799 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1800 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1801 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1802 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1803 getTargetInfo().getABI() == "elfv1-qpx" &&
1804 T->isSpecificBuiltinType(BuiltinType::Double))
1805 SimdAlign = 256;
1806 return SimdAlign;
1807}
1808
Ken Dyckcc56c542011-01-15 18:38:59 +00001809/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1810CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1811 return CharUnits::fromQuantity(BitSize / getCharWidth());
1812}
1813
Ken Dyckb0fcc592011-02-11 01:54:29 +00001814/// toBits - Convert a size in characters to a size in characters.
1815int64_t ASTContext::toBits(CharUnits CharSize) const {
1816 return CharSize.getQuantity() * getCharWidth();
1817}
1818
Ken Dyck8c89d592009-12-22 14:23:30 +00001819/// getTypeSizeInChars - Return the size of the specified type, in characters.
1820/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001821CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001822 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001823}
Jay Foad39c79802011-01-12 09:06:06 +00001824CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001825 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001826}
1827
Ken Dycka6046ab2010-01-26 17:25:18 +00001828/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001829/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001830CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001831 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001832}
Jay Foad39c79802011-01-12 09:06:06 +00001833CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001834 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001835}
1836
Chris Lattnera3402cd2009-01-27 18:08:34 +00001837/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1838/// type for the current target in bits. This can be different than the ABI
1839/// alignment in cases where it is beneficial for performance to overalign
1840/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001841unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001842 TypeInfo TI = getTypeInfo(T);
1843 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001844
David Majnemere1544562015-04-24 01:25:05 +00001845 T = T->getBaseElementTypeUnsafe();
1846
1847 // The preferred alignment of member pointers is that of a pointer.
1848 if (T->isMemberPointerType())
1849 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1850
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001851 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1852 return ABIAlign; // Never overalign on XCore.
1853
Eli Friedman7ab09572009-05-25 21:27:19 +00001854 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001855 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001856 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001857 if (const EnumType *ET = T->getAs<EnumType>())
1858 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001859 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001860 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1861 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001862 // Don't increase the alignment if an alignment attribute was specified on a
1863 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001864 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001865 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001866
Chris Lattnera3402cd2009-01-27 18:08:34 +00001867 return ABIAlign;
1868}
1869
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001870/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1871/// for __attribute__((aligned)) on this target, to be used if no alignment
1872/// value is specified.
1873unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1874 return getTargetInfo().getDefaultAlignForAttributeAligned();
1875}
1876
Ulrich Weigandfa806422013-05-06 16:23:57 +00001877/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1878/// to a global variable of the specified type.
1879unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1880 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1881}
1882
1883/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1884/// should be given to a global variable of the specified type.
1885CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1886 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1887}
1888
David Majnemer08ef2ba2015-06-23 20:34:18 +00001889CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1890 CharUnits Offset = CharUnits::Zero();
1891 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1892 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1893 Offset += Layout->getBaseClassOffset(Base);
1894 Layout = &getASTRecordLayout(Base);
1895 }
1896 return Offset;
1897}
1898
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001899/// DeepCollectObjCIvars -
1900/// This routine first collects all declared, but not synthesized, ivars in
1901/// super class and then collects all ivars, including those synthesized for
1902/// current class. This routine is used for implementation of current class
1903/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001904///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001905void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1906 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001907 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001908 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1909 DeepCollectObjCIvars(SuperClass, false, Ivars);
1910 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001911 for (const auto *I : OI->ivars())
1912 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001913 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001914 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001915 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001916 Iv= Iv->getNextIvar())
1917 Ivars.push_back(Iv);
1918 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001919}
1920
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001921/// CollectInheritedProtocols - Collect all protocols in current class and
1922/// those inherited by it.
1923void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001924 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001925 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001926 // We can use protocol_iterator here instead of
1927 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001928 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001929 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001930 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001931
1932 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001933 for (const auto *Cat : OI->visible_categories())
1934 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001935
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001936 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1937 while (SD) {
1938 CollectInheritedProtocols(SD, Protocols);
1939 SD = SD->getSuperClass();
1940 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001941 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001942 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001943 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001944 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001945 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001946 // Insert the protocol.
1947 if (!Protocols.insert(
1948 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1949 return;
1950
1951 for (auto *Proto : OP->protocols())
1952 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001953 }
1954}
1955
Jay Foad39c79802011-01-12 09:06:06 +00001956unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001957 unsigned count = 0;
1958 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001959 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001960 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001961
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001962 // Count ivar defined in this class's implementation. This
1963 // includes synthesized ivars.
1964 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001965 count += ImplDecl->ivar_size();
1966
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001967 return count;
1968}
1969
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001970bool ASTContext::isSentinelNullExpr(const Expr *E) {
1971 if (!E)
1972 return false;
1973
1974 // nullptr_t is always treated as null.
1975 if (E->getType()->isNullPtrType()) return true;
1976
1977 if (E->getType()->isAnyPointerType() &&
1978 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1979 Expr::NPC_ValueDependentIsNull))
1980 return true;
1981
1982 // Unfortunately, __null has type 'int'.
1983 if (isa<GNUNullExpr>(E)) return true;
1984
1985 return false;
1986}
1987
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001988/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1989ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1990 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1991 I = ObjCImpls.find(D);
1992 if (I != ObjCImpls.end())
1993 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001994 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001995}
1996/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1997ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1998 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1999 I = ObjCImpls.find(D);
2000 if (I != ObjCImpls.end())
2001 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002002 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002003}
2004
2005/// \brief Set the implementation of ObjCInterfaceDecl.
2006void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2007 ObjCImplementationDecl *ImplD) {
2008 assert(IFaceD && ImplD && "Passed null params");
2009 ObjCImpls[IFaceD] = ImplD;
2010}
2011/// \brief Set the implementation of ObjCCategoryDecl.
2012void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2013 ObjCCategoryImplDecl *ImplD) {
2014 assert(CatD && ImplD && "Passed null params");
2015 ObjCImpls[CatD] = ImplD;
2016}
2017
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002018const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2019 const NamedDecl *ND) const {
2020 if (const ObjCInterfaceDecl *ID =
2021 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002022 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002023 if (const ObjCCategoryDecl *CD =
2024 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002025 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002026 if (const ObjCImplDecl *IMD =
2027 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002028 return IMD->getClassInterface();
2029
Craig Topper36250ad2014-05-12 05:36:57 +00002030 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002031}
2032
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002033/// \brief Get the copy initialization expression of VarDecl,or NULL if
2034/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002035Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002036 assert(VD && "Passed null params");
2037 assert(VD->hasAttr<BlocksAttr>() &&
2038 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002039 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002040 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002041 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002042}
2043
2044/// \brief Set the copy inialization expression of a block var decl.
2045void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2046 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002047 assert(VD->hasAttr<BlocksAttr>() &&
2048 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002049 BlockVarCopyInits[VD] = Init;
2050}
2051
John McCallbcd03502009-12-07 02:54:59 +00002052TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002053 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002054 if (!DataSize)
2055 DataSize = TypeLoc::getFullDataSizeForType(T);
2056 else
2057 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002058 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002059
John McCallbcd03502009-12-07 02:54:59 +00002060 TypeSourceInfo *TInfo =
2061 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2062 new (TInfo) TypeSourceInfo(T);
2063 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002064}
2065
John McCallbcd03502009-12-07 02:54:59 +00002066TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002067 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002068 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002069 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002070 return DI;
2071}
2072
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002073const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002074ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002075 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002076}
2077
2078const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002079ASTContext::getASTObjCImplementationLayout(
2080 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002081 return getObjCLayout(D->getClassInterface(), D);
2082}
2083
Chris Lattner983a8bb2007-07-13 22:13:22 +00002084//===----------------------------------------------------------------------===//
2085// Type creation/memoization methods
2086//===----------------------------------------------------------------------===//
2087
Jay Foad39c79802011-01-12 09:06:06 +00002088QualType
John McCall33ddac02011-01-19 10:06:00 +00002089ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2090 unsigned fastQuals = quals.getFastQualifiers();
2091 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002092
2093 // Check if we've already instantiated this type.
2094 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002095 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002096 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002097 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2098 assert(eq->getQualifiers() == quals);
2099 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002100 }
2101
John McCall33ddac02011-01-19 10:06:00 +00002102 // If the base type is not canonical, make the appropriate canonical type.
2103 QualType canon;
2104 if (!baseType->isCanonicalUnqualified()) {
2105 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002106 canonSplit.Quals.addConsistentQualifiers(quals);
2107 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002108
2109 // Re-find the insert position.
2110 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2111 }
2112
2113 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2114 ExtQualNodes.InsertNode(eq, insertPos);
2115 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002116}
2117
Jay Foad39c79802011-01-12 09:06:06 +00002118QualType
2119ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002120 QualType CanT = getCanonicalType(T);
2121 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002122 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002123
John McCall8ccfcb52009-09-24 19:53:00 +00002124 // If we are composing extended qualifiers together, merge together
2125 // into one ExtQuals node.
2126 QualifierCollector Quals;
2127 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002128
John McCall8ccfcb52009-09-24 19:53:00 +00002129 // If this type already has an address space specified, it cannot get
2130 // another one.
2131 assert(!Quals.hasAddressSpace() &&
2132 "Type cannot be in multiple addr spaces!");
2133 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002134
John McCall8ccfcb52009-09-24 19:53:00 +00002135 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002136}
2137
Chris Lattnerd60183d2009-02-18 22:53:11 +00002138QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002139 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002140 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002141 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002142 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002143
John McCall53fa7142010-12-24 02:08:15 +00002144 if (const PointerType *ptr = T->getAs<PointerType>()) {
2145 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002146 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002147 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2148 return getPointerType(ResultType);
2149 }
2150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
John McCall8ccfcb52009-09-24 19:53:00 +00002152 // If we are composing extended qualifiers together, merge together
2153 // into one ExtQuals node.
2154 QualifierCollector Quals;
2155 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002156
John McCall8ccfcb52009-09-24 19:53:00 +00002157 // If this type already has an ObjCGC specified, it cannot get
2158 // another one.
2159 assert(!Quals.hasObjCGCAttr() &&
2160 "Type cannot have multiple ObjCGCs!");
2161 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002162
John McCall8ccfcb52009-09-24 19:53:00 +00002163 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002164}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002165
John McCall4f5019e2010-12-19 02:44:49 +00002166const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2167 FunctionType::ExtInfo Info) {
2168 if (T->getExtInfo() == Info)
2169 return T;
2170
2171 QualType Result;
2172 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002173 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002174 } else {
2175 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2176 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2177 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002178 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002179 }
2180
2181 return cast<FunctionType>(Result.getTypePtr());
2182}
2183
Richard Smith2a7d4812013-05-04 07:00:32 +00002184void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2185 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002186 FD = FD->getMostRecentDecl();
2187 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002188 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2189 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002190 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002191 if (FunctionDecl *Next = FD->getPreviousDecl())
2192 FD = Next;
2193 else
2194 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002195 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002196 if (ASTMutationListener *L = getASTMutationListener())
2197 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002198}
2199
Richard Smith0b3a4622014-11-13 20:01:57 +00002200/// Get a function type and produce the equivalent function type with the
2201/// specified exception specification. Type sugar that can be present on a
2202/// declaration of a function with an exception specification is permitted
2203/// and preserved. Other type sugar (for instance, typedefs) is not.
2204static QualType getFunctionTypeWithExceptionSpec(
2205 ASTContext &Context, QualType Orig,
2206 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2207 // Might have some parens.
2208 if (auto *PT = dyn_cast<ParenType>(Orig))
2209 return Context.getParenType(
2210 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2211
2212 // Might have a calling-convention attribute.
2213 if (auto *AT = dyn_cast<AttributedType>(Orig))
2214 return Context.getAttributedType(
2215 AT->getAttrKind(),
2216 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2217 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2218 ESI));
2219
2220 // Anything else must be a function type. Rebuild it with the new exception
2221 // specification.
2222 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2223 return Context.getFunctionType(
2224 Proto->getReturnType(), Proto->getParamTypes(),
2225 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2226}
2227
2228void ASTContext::adjustExceptionSpec(
2229 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2230 bool AsWritten) {
2231 // Update the type.
2232 QualType Updated =
2233 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2234 FD->setType(Updated);
2235
2236 if (!AsWritten)
2237 return;
2238
2239 // Update the type in the type source information too.
2240 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2241 // If the type and the type-as-written differ, we may need to update
2242 // the type-as-written too.
2243 if (TSInfo->getType() != FD->getType())
2244 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2245
2246 // FIXME: When we get proper type location information for exceptions,
2247 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2248 // up the TypeSourceInfo;
2249 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2250 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2251 "TypeLoc size mismatch from updating exception specification");
2252 TSInfo->overrideType(Updated);
2253 }
2254}
2255
Chris Lattnerc6395932007-06-22 20:56:16 +00002256/// getComplexType - Return the uniqued reference to the type for a complex
2257/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002258QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002259 // Unique pointers, to guarantee there is only one pointer of a particular
2260 // structure.
2261 llvm::FoldingSetNodeID ID;
2262 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002263
Craig Topper36250ad2014-05-12 05:36:57 +00002264 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002265 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2266 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002267
Chris Lattnerc6395932007-06-22 20:56:16 +00002268 // If the pointee type isn't canonical, this won't be a canonical type either,
2269 // so fill in the canonical type field.
2270 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002271 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002272 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002273
Chris Lattnerc6395932007-06-22 20:56:16 +00002274 // Get the new insert position for the node we care about.
2275 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002276 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002277 }
John McCall90d1c2d2009-09-24 23:30:46 +00002278 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002279 Types.push_back(New);
2280 ComplexTypes.InsertNode(New, InsertPos);
2281 return QualType(New, 0);
2282}
2283
Chris Lattner970e54e2006-11-12 00:37:36 +00002284/// getPointerType - Return the uniqued reference to the type for a pointer to
2285/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002286QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002287 // Unique pointers, to guarantee there is only one pointer of a particular
2288 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002289 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002290 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002291
Craig Topper36250ad2014-05-12 05:36:57 +00002292 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002293 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002294 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattner7ccecb92006-11-12 08:50:50 +00002296 // If the pointee type isn't canonical, this won't be a canonical type either,
2297 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002298 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002299 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002300 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002301
Bob Wilsonc8541f22013-03-15 17:12:43 +00002302 // Get the new insert position for the node we care about.
2303 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002304 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002305 }
John McCall90d1c2d2009-09-24 23:30:46 +00002306 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002307 Types.push_back(New);
2308 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002309 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002310}
2311
Reid Kleckner0503a872013-12-05 01:23:43 +00002312QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2313 llvm::FoldingSetNodeID ID;
2314 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002315 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002316 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2317 if (AT)
2318 return QualType(AT, 0);
2319
2320 QualType Canonical = getCanonicalType(New);
2321
2322 // Get the new insert position for the node we care about.
2323 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002324 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002325
2326 AT = new (*this, TypeAlignment)
2327 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2328 Types.push_back(AT);
2329 AdjustedTypes.InsertNode(AT, InsertPos);
2330 return QualType(AT, 0);
2331}
2332
Reid Kleckner8a365022013-06-24 17:51:48 +00002333QualType ASTContext::getDecayedType(QualType T) const {
2334 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2335
Reid Kleckner8a365022013-06-24 17:51:48 +00002336 QualType Decayed;
2337
2338 // C99 6.7.5.3p7:
2339 // A declaration of a parameter as "array of type" shall be
2340 // adjusted to "qualified pointer to type", where the type
2341 // qualifiers (if any) are those specified within the [ and ] of
2342 // the array type derivation.
2343 if (T->isArrayType())
2344 Decayed = getArrayDecayedType(T);
2345
2346 // C99 6.7.5.3p8:
2347 // A declaration of a parameter as "function returning type"
2348 // shall be adjusted to "pointer to function returning type", as
2349 // in 6.3.2.1.
2350 if (T->isFunctionType())
2351 Decayed = getPointerType(T);
2352
Reid Kleckner0503a872013-12-05 01:23:43 +00002353 llvm::FoldingSetNodeID ID;
2354 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002355 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002356 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2357 if (AT)
2358 return QualType(AT, 0);
2359
Reid Kleckner8a365022013-06-24 17:51:48 +00002360 QualType Canonical = getCanonicalType(Decayed);
2361
2362 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002363 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002364 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002365
Reid Kleckner0503a872013-12-05 01:23:43 +00002366 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2367 Types.push_back(AT);
2368 AdjustedTypes.InsertNode(AT, InsertPos);
2369 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002370}
2371
Mike Stump11289f42009-09-09 15:08:12 +00002372/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002373/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002374QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002375 assert(T->isFunctionType() && "block of function types only");
2376 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002377 // structure.
2378 llvm::FoldingSetNodeID ID;
2379 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002380
Craig Topper36250ad2014-05-12 05:36:57 +00002381 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002382 if (BlockPointerType *PT =
2383 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2384 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002385
2386 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002387 // type either so fill in the canonical type field.
2388 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002389 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002390 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002391
Steve Naroffec33ed92008-08-27 16:04:49 +00002392 // Get the new insert position for the node we care about.
2393 BlockPointerType *NewIP =
2394 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002395 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002396 }
John McCall90d1c2d2009-09-24 23:30:46 +00002397 BlockPointerType *New
2398 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002399 Types.push_back(New);
2400 BlockPointerTypes.InsertNode(New, InsertPos);
2401 return QualType(New, 0);
2402}
2403
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002404/// getLValueReferenceType - Return the uniqued reference to the type for an
2405/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002406QualType
2407ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002408 assert(getCanonicalType(T) != OverloadTy &&
2409 "Unresolved overloaded function type");
2410
Bill Wendling3708c182007-05-27 10:15:43 +00002411 // Unique pointers, to guarantee there is only one pointer of a particular
2412 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002413 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002414 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002415
Craig Topper36250ad2014-05-12 05:36:57 +00002416 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002417 if (LValueReferenceType *RT =
2418 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002419 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002420
John McCallfc93cf92009-10-22 22:37:11 +00002421 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2422
Bill Wendling3708c182007-05-27 10:15:43 +00002423 // If the referencee type isn't canonical, this won't be a canonical type
2424 // either, so fill in the canonical type field.
2425 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002426 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2427 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2428 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002429
Bill Wendling3708c182007-05-27 10:15:43 +00002430 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002431 LValueReferenceType *NewIP =
2432 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002433 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002434 }
2435
John McCall90d1c2d2009-09-24 23:30:46 +00002436 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002437 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2438 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002439 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002440 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002441
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002442 return QualType(New, 0);
2443}
2444
2445/// getRValueReferenceType - Return the uniqued reference to the type for an
2446/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002447QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002448 // Unique pointers, to guarantee there is only one pointer of a particular
2449 // structure.
2450 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002451 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002452
Craig Topper36250ad2014-05-12 05:36:57 +00002453 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002454 if (RValueReferenceType *RT =
2455 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2456 return QualType(RT, 0);
2457
John McCallfc93cf92009-10-22 22:37:11 +00002458 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2459
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002460 // If the referencee type isn't canonical, this won't be a canonical type
2461 // either, so fill in the canonical type field.
2462 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002463 if (InnerRef || !T.isCanonical()) {
2464 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2465 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002466
2467 // Get the new insert position for the node we care about.
2468 RValueReferenceType *NewIP =
2469 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002470 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002471 }
2472
John McCall90d1c2d2009-09-24 23:30:46 +00002473 RValueReferenceType *New
2474 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002475 Types.push_back(New);
2476 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002477 return QualType(New, 0);
2478}
2479
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002480/// getMemberPointerType - Return the uniqued reference to the type for a
2481/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002482QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002483 // Unique pointers, to guarantee there is only one pointer of a particular
2484 // structure.
2485 llvm::FoldingSetNodeID ID;
2486 MemberPointerType::Profile(ID, T, Cls);
2487
Craig Topper36250ad2014-05-12 05:36:57 +00002488 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002489 if (MemberPointerType *PT =
2490 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2491 return QualType(PT, 0);
2492
2493 // If the pointee or class type isn't canonical, this won't be a canonical
2494 // type either, so fill in the canonical type field.
2495 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002496 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002497 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2498
2499 // Get the new insert position for the node we care about.
2500 MemberPointerType *NewIP =
2501 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002502 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002503 }
John McCall90d1c2d2009-09-24 23:30:46 +00002504 MemberPointerType *New
2505 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002506 Types.push_back(New);
2507 MemberPointerTypes.InsertNode(New, InsertPos);
2508 return QualType(New, 0);
2509}
2510
Mike Stump11289f42009-09-09 15:08:12 +00002511/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002512/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002513QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002514 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002515 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002516 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002517 assert((EltTy->isDependentType() ||
2518 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002519 "Constant array of VLAs is illegal!");
2520
Chris Lattnere2df3f92009-05-13 04:12:56 +00002521 // Convert the array size into a canonical width matching the pointer size for
2522 // the target.
2523 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002524 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002525 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002526
Chris Lattner23b7eb62007-06-15 23:05:46 +00002527 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002528 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002529
Craig Topper36250ad2014-05-12 05:36:57 +00002530 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002531 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002532 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002533 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002534
John McCall33ddac02011-01-19 10:06:00 +00002535 // If the element type isn't canonical or has qualifiers, this won't
2536 // be a canonical type either, so fill in the canonical type field.
2537 QualType Canon;
2538 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2539 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002540 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002541 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002542 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002543
Chris Lattner36f8e652007-01-27 08:31:04 +00002544 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002545 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002546 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002547 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002548 }
Mike Stump11289f42009-09-09 15:08:12 +00002549
John McCall90d1c2d2009-09-24 23:30:46 +00002550 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002551 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002552 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002553 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002554 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002555}
2556
John McCall06549462011-01-18 08:40:38 +00002557/// getVariableArrayDecayedType - Turns the given type, which may be
2558/// variably-modified, into the corresponding type with all the known
2559/// sizes replaced with [*].
2560QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2561 // Vastly most common case.
2562 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002563
John McCall06549462011-01-18 08:40:38 +00002564 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002565
John McCall06549462011-01-18 08:40:38 +00002566 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002567 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002568 switch (ty->getTypeClass()) {
2569#define TYPE(Class, Base)
2570#define ABSTRACT_TYPE(Class, Base)
2571#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2572#include "clang/AST/TypeNodes.def"
2573 llvm_unreachable("didn't desugar past all non-canonical types?");
2574
2575 // These types should never be variably-modified.
2576 case Type::Builtin:
2577 case Type::Complex:
2578 case Type::Vector:
2579 case Type::ExtVector:
2580 case Type::DependentSizedExtVector:
2581 case Type::ObjCObject:
2582 case Type::ObjCInterface:
2583 case Type::ObjCObjectPointer:
2584 case Type::Record:
2585 case Type::Enum:
2586 case Type::UnresolvedUsing:
2587 case Type::TypeOfExpr:
2588 case Type::TypeOf:
2589 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002590 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002591 case Type::DependentName:
2592 case Type::InjectedClassName:
2593 case Type::TemplateSpecialization:
2594 case Type::DependentTemplateSpecialization:
2595 case Type::TemplateTypeParm:
2596 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002597 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002598 case Type::PackExpansion:
2599 llvm_unreachable("type should never be variably-modified");
2600
2601 // These types can be variably-modified but should never need to
2602 // further decay.
2603 case Type::FunctionNoProto:
2604 case Type::FunctionProto:
2605 case Type::BlockPointer:
2606 case Type::MemberPointer:
2607 return type;
2608
2609 // These types can be variably-modified. All these modifications
2610 // preserve structure except as noted by comments.
2611 // TODO: if we ever care about optimizing VLAs, there are no-op
2612 // optimizations available here.
2613 case Type::Pointer:
2614 result = getPointerType(getVariableArrayDecayedType(
2615 cast<PointerType>(ty)->getPointeeType()));
2616 break;
2617
2618 case Type::LValueReference: {
2619 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2620 result = getLValueReferenceType(
2621 getVariableArrayDecayedType(lv->getPointeeType()),
2622 lv->isSpelledAsLValue());
2623 break;
2624 }
2625
2626 case Type::RValueReference: {
2627 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2628 result = getRValueReferenceType(
2629 getVariableArrayDecayedType(lv->getPointeeType()));
2630 break;
2631 }
2632
Eli Friedman0dfb8892011-10-06 23:00:33 +00002633 case Type::Atomic: {
2634 const AtomicType *at = cast<AtomicType>(ty);
2635 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2636 break;
2637 }
2638
John McCall06549462011-01-18 08:40:38 +00002639 case Type::ConstantArray: {
2640 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2641 result = getConstantArrayType(
2642 getVariableArrayDecayedType(cat->getElementType()),
2643 cat->getSize(),
2644 cat->getSizeModifier(),
2645 cat->getIndexTypeCVRQualifiers());
2646 break;
2647 }
2648
2649 case Type::DependentSizedArray: {
2650 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2651 result = getDependentSizedArrayType(
2652 getVariableArrayDecayedType(dat->getElementType()),
2653 dat->getSizeExpr(),
2654 dat->getSizeModifier(),
2655 dat->getIndexTypeCVRQualifiers(),
2656 dat->getBracketsRange());
2657 break;
2658 }
2659
2660 // Turn incomplete types into [*] types.
2661 case Type::IncompleteArray: {
2662 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2663 result = getVariableArrayType(
2664 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002665 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002666 ArrayType::Normal,
2667 iat->getIndexTypeCVRQualifiers(),
2668 SourceRange());
2669 break;
2670 }
2671
2672 // Turn VLA types into [*] types.
2673 case Type::VariableArray: {
2674 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2675 result = getVariableArrayType(
2676 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002677 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002678 ArrayType::Star,
2679 vat->getIndexTypeCVRQualifiers(),
2680 vat->getBracketsRange());
2681 break;
2682 }
2683 }
2684
2685 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002686 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002687}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002688
Steve Naroffcadebd02007-08-30 18:14:25 +00002689/// getVariableArrayType - Returns a non-unique reference to the type for a
2690/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002691QualType ASTContext::getVariableArrayType(QualType EltTy,
2692 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002693 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002694 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002695 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002696 // Since we don't unique expressions, it isn't possible to unique VLA's
2697 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002698 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002699
John McCall33ddac02011-01-19 10:06:00 +00002700 // Be sure to pull qualifiers off the element type.
2701 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2702 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002703 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002704 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002705 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002706 }
2707
John McCall90d1c2d2009-09-24 23:30:46 +00002708 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002709 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002710
2711 VariableArrayTypes.push_back(New);
2712 Types.push_back(New);
2713 return QualType(New, 0);
2714}
2715
Douglas Gregor4619e432008-12-05 23:32:09 +00002716/// getDependentSizedArrayType - Returns a non-unique reference to
2717/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002718/// type.
John McCall33ddac02011-01-19 10:06:00 +00002719QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2720 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002721 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002722 unsigned elementTypeQuals,
2723 SourceRange brackets) const {
2724 assert((!numElements || numElements->isTypeDependent() ||
2725 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002726 "Size must be type- or value-dependent!");
2727
John McCall33ddac02011-01-19 10:06:00 +00002728 // Dependently-sized array types that do not have a specified number
2729 // of elements will have their sizes deduced from a dependent
2730 // initializer. We do no canonicalization here at all, which is okay
2731 // because they can't be used in most locations.
2732 if (!numElements) {
2733 DependentSizedArrayType *newType
2734 = new (*this, TypeAlignment)
2735 DependentSizedArrayType(*this, elementType, QualType(),
2736 numElements, ASM, elementTypeQuals,
2737 brackets);
2738 Types.push_back(newType);
2739 return QualType(newType, 0);
2740 }
2741
2742 // Otherwise, we actually build a new type every time, but we
2743 // also build a canonical type.
2744
2745 SplitQualType canonElementType = getCanonicalType(elementType).split();
2746
Craig Topper36250ad2014-05-12 05:36:57 +00002747 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002748 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002749 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002750 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002751 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002752
John McCall33ddac02011-01-19 10:06:00 +00002753 // Look for an existing type with these properties.
2754 DependentSizedArrayType *canonTy =
2755 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002756
John McCall33ddac02011-01-19 10:06:00 +00002757 // If we don't have one, build one.
2758 if (!canonTy) {
2759 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002760 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002761 QualType(), numElements, ASM, elementTypeQuals,
2762 brackets);
2763 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2764 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002765 }
2766
John McCall33ddac02011-01-19 10:06:00 +00002767 // Apply qualifiers from the element type to the array.
2768 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002769 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002770
David Majnemer16a74702015-07-24 05:54:19 +00002771 // If we didn't need extra canonicalization for the element type or the size
2772 // expression, then just use that as our result.
2773 if (QualType(canonElementType.Ty, 0) == elementType &&
2774 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002775 return canon;
2776
2777 // Otherwise, we need to build a type which follows the spelling
2778 // of the element type.
2779 DependentSizedArrayType *sugaredType
2780 = new (*this, TypeAlignment)
2781 DependentSizedArrayType(*this, elementType, canon, numElements,
2782 ASM, elementTypeQuals, brackets);
2783 Types.push_back(sugaredType);
2784 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002785}
2786
John McCall33ddac02011-01-19 10:06:00 +00002787QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002788 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002789 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002790 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002791 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002792
Craig Topper36250ad2014-05-12 05:36:57 +00002793 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002794 if (IncompleteArrayType *iat =
2795 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2796 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002797
2798 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002799 // either, so fill in the canonical type field. We also have to pull
2800 // qualifiers off the element type.
2801 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002802
John McCall33ddac02011-01-19 10:06:00 +00002803 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2804 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002805 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002806 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002807 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002808
2809 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002810 IncompleteArrayType *existing =
2811 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2812 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002813 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002814
John McCall33ddac02011-01-19 10:06:00 +00002815 IncompleteArrayType *newType = new (*this, TypeAlignment)
2816 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002817
John McCall33ddac02011-01-19 10:06:00 +00002818 IncompleteArrayTypes.InsertNode(newType, insertPos);
2819 Types.push_back(newType);
2820 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002821}
2822
Steve Naroff91fcddb2007-07-18 18:00:27 +00002823/// getVectorType - Return the unique reference to a vector type of
2824/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002825QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002826 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002827 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002828
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002829 // Check if we've already instantiated a vector of this type.
2830 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002831 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002832
Craig Topper36250ad2014-05-12 05:36:57 +00002833 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002834 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2835 return QualType(VTP, 0);
2836
2837 // If the element type isn't canonical, this won't be a canonical type either,
2838 // so fill in the canonical type field.
2839 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002840 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002841 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002842
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002843 // Get the new insert position for the node we care about.
2844 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002845 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002846 }
John McCall90d1c2d2009-09-24 23:30:46 +00002847 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002848 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002849 VectorTypes.InsertNode(New, InsertPos);
2850 Types.push_back(New);
2851 return QualType(New, 0);
2852}
2853
Nate Begemance4d7fc2008-04-18 23:10:10 +00002854/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002855/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002856QualType
2857ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002858 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002859
Steve Naroff91fcddb2007-07-18 18:00:27 +00002860 // Check if we've already instantiated a vector of this type.
2861 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002862 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002863 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002864 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002865 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2866 return QualType(VTP, 0);
2867
2868 // If the element type isn't canonical, this won't be a canonical type either,
2869 // so fill in the canonical type field.
2870 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002871 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002872 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002873
Steve Naroff91fcddb2007-07-18 18:00:27 +00002874 // Get the new insert position for the node we care about.
2875 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002876 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002877 }
John McCall90d1c2d2009-09-24 23:30:46 +00002878 ExtVectorType *New = new (*this, TypeAlignment)
2879 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002880 VectorTypes.InsertNode(New, InsertPos);
2881 Types.push_back(New);
2882 return QualType(New, 0);
2883}
2884
Jay Foad39c79802011-01-12 09:06:06 +00002885QualType
2886ASTContext::getDependentSizedExtVectorType(QualType vecType,
2887 Expr *SizeExpr,
2888 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002889 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002890 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002891 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Craig Topper36250ad2014-05-12 05:36:57 +00002893 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002894 DependentSizedExtVectorType *Canon
2895 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2896 DependentSizedExtVectorType *New;
2897 if (Canon) {
2898 // We already have a canonical version of this array type; use it as
2899 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002900 New = new (*this, TypeAlignment)
2901 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2902 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002903 } else {
2904 QualType CanonVecTy = getCanonicalType(vecType);
2905 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002906 New = new (*this, TypeAlignment)
2907 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2908 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002909
2910 DependentSizedExtVectorType *CanonCheck
2911 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2912 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2913 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002914 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2915 } else {
2916 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2917 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002918 New = new (*this, TypeAlignment)
2919 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002920 }
2921 }
Mike Stump11289f42009-09-09 15:08:12 +00002922
Douglas Gregor758a8692009-06-17 21:51:59 +00002923 Types.push_back(New);
2924 return QualType(New, 0);
2925}
2926
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002927/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002928///
Jay Foad39c79802011-01-12 09:06:06 +00002929QualType
2930ASTContext::getFunctionNoProtoType(QualType ResultTy,
2931 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002932 const CallingConv CallConv = Info.getCC();
2933
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002934 // Unique functions, to guarantee there is only one function of a particular
2935 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002936 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002937 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002938
Craig Topper36250ad2014-05-12 05:36:57 +00002939 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002940 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002941 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002942 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002943
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002944 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002945 if (!ResultTy.isCanonical()) {
2946 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002947
Chris Lattner47955de2007-01-27 08:37:20 +00002948 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002949 FunctionNoProtoType *NewIP =
2950 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002951 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002952 }
Mike Stump11289f42009-09-09 15:08:12 +00002953
Roman Divacky65b88cd2011-03-01 17:40:53 +00002954 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002955 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002956 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002957 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002958 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002959 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002960}
2961
Douglas Gregorcd780372013-01-17 23:36:45 +00002962/// \brief Determine whether \p T is canonical as the result type of a function.
2963static bool isCanonicalResultType(QualType T) {
2964 return T.isCanonical() &&
2965 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2966 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2967}
2968
Jay Foad39c79802011-01-12 09:06:06 +00002969QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002970ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002971 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002972 size_t NumArgs = ArgArray.size();
2973
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002974 // Unique functions, to guarantee there is only one function of a particular
2975 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002976 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002977 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2978 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002979
Craig Topper36250ad2014-05-12 05:36:57 +00002980 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002981 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002982 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002983 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002984
2985 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002986 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002987 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002988 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002989 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002990 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002991 isCanonical = false;
2992
2993 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002994 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002995 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002996 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002997 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002998 CanonicalArgs.reserve(NumArgs);
2999 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003000 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003001
John McCalldb40c7f2010-12-14 08:05:40 +00003002 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003003 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003004 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003005
Douglas Gregorcd780372013-01-17 23:36:45 +00003006 // Result types do not have ARC lifetime qualifiers.
3007 QualType CanResultTy = getCanonicalType(ResultTy);
3008 if (ResultTy.getQualifiers().hasObjCLifetime()) {
3009 Qualifiers Qs = CanResultTy.getQualifiers();
3010 Qs.removeObjCLifetime();
3011 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
3012 }
3013
Jordan Rose5c382722013-03-08 21:51:21 +00003014 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003015
Chris Lattnerfd4de792007-01-27 01:15:32 +00003016 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003017 FunctionProtoType *NewIP =
3018 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003019 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003020 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003021
John McCall31168b02011-06-15 23:02:42 +00003022 // FunctionProtoType objects are allocated with extra bytes after
3023 // them for three variable size arrays at the end:
3024 // - parameter types
3025 // - exception types
3026 // - consumed-arguments flags
3027 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003028 // expression, or information used to resolve the exception
3029 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003030 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003031 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003032 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3033 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3034 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003035 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003036 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003037 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003038 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003039 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003040 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003041 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003042 Size += NumArgs * sizeof(bool);
3043
John McCalldb40c7f2010-12-14 08:05:40 +00003044 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003045 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003046 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003047 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003048 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003049 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003050}
Chris Lattneref51c202006-11-10 07:17:23 +00003051
John McCalle78aac42010-03-10 03:28:59 +00003052#ifndef NDEBUG
3053static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3054 if (!isa<CXXRecordDecl>(D)) return false;
3055 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3056 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3057 return true;
3058 if (RD->getDescribedClassTemplate() &&
3059 !isa<ClassTemplateSpecializationDecl>(RD))
3060 return true;
3061 return false;
3062}
3063#endif
3064
3065/// getInjectedClassNameType - Return the unique reference to the
3066/// injected class name type for the specified templated declaration.
3067QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003068 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003069 assert(NeedsInjectedClassNameType(Decl));
3070 if (Decl->TypeForDecl) {
3071 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003072 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003073 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3074 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3075 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3076 } else {
John McCall424cec92011-01-19 06:33:43 +00003077 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003078 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003079 Decl->TypeForDecl = newType;
3080 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003081 }
3082 return QualType(Decl->TypeForDecl, 0);
3083}
3084
Douglas Gregor83a586e2008-04-13 21:07:44 +00003085/// getTypeDeclType - Return the unique reference to the type for the
3086/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003087QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003088 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003089 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003090
Richard Smithdda56e42011-04-15 14:24:37 +00003091 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003092 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003093
John McCall96f0b5f2010-03-10 06:48:02 +00003094 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3095 "Template type parameter types are always available.");
3096
John McCall81e38502010-02-16 03:57:14 +00003097 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003098 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003099 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003100 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003101 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003102 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003103 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003104 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003105 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003106 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3107 Decl->TypeForDecl = newType;
3108 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003109 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003110 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003111
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003112 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003113}
3114
Chris Lattner32d920b2007-01-26 02:01:53 +00003115/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003116/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003117QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003118ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3119 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003120 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003121
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003122 if (Canonical.isNull())
3123 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003124 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003125 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003126 Decl->TypeForDecl = newType;
3127 Types.push_back(newType);
3128 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003129}
3130
Jay Foad39c79802011-01-12 09:06:06 +00003131QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003132 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3133
Douglas Gregorec9fd132012-01-14 16:38:05 +00003134 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003135 if (PrevDecl->TypeForDecl)
3136 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3137
John McCall424cec92011-01-19 06:33:43 +00003138 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3139 Decl->TypeForDecl = newType;
3140 Types.push_back(newType);
3141 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003142}
3143
Jay Foad39c79802011-01-12 09:06:06 +00003144QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003145 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3146
Douglas Gregorec9fd132012-01-14 16:38:05 +00003147 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003148 if (PrevDecl->TypeForDecl)
3149 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3150
John McCall424cec92011-01-19 06:33:43 +00003151 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3152 Decl->TypeForDecl = newType;
3153 Types.push_back(newType);
3154 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003155}
3156
John McCall81904512011-01-06 01:58:22 +00003157QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3158 QualType modifiedType,
3159 QualType equivalentType) {
3160 llvm::FoldingSetNodeID id;
3161 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3162
Craig Topper36250ad2014-05-12 05:36:57 +00003163 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003164 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3165 if (type) return QualType(type, 0);
3166
3167 QualType canon = getCanonicalType(equivalentType);
3168 type = new (*this, TypeAlignment)
3169 AttributedType(canon, attrKind, modifiedType, equivalentType);
3170
3171 Types.push_back(type);
3172 AttributedTypes.InsertNode(type, insertPos);
3173
3174 return QualType(type, 0);
3175}
3176
3177
John McCallcebee162009-10-18 09:09:24 +00003178/// \brief Retrieve a substitution-result type.
3179QualType
3180ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003181 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003182 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003183 && "replacement types must always be canonical");
3184
3185 llvm::FoldingSetNodeID ID;
3186 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003187 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003188 SubstTemplateTypeParmType *SubstParm
3189 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3190
3191 if (!SubstParm) {
3192 SubstParm = new (*this, TypeAlignment)
3193 SubstTemplateTypeParmType(Parm, Replacement);
3194 Types.push_back(SubstParm);
3195 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3196 }
3197
3198 return QualType(SubstParm, 0);
3199}
3200
Douglas Gregorada4b792011-01-14 02:55:32 +00003201/// \brief Retrieve a
3202QualType ASTContext::getSubstTemplateTypeParmPackType(
3203 const TemplateTypeParmType *Parm,
3204 const TemplateArgument &ArgPack) {
3205#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003206 for (const auto &P : ArgPack.pack_elements()) {
3207 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3208 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003209 }
3210#endif
3211
3212 llvm::FoldingSetNodeID ID;
3213 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003214 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003215 if (SubstTemplateTypeParmPackType *SubstParm
3216 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3217 return QualType(SubstParm, 0);
3218
3219 QualType Canon;
3220 if (!Parm->isCanonicalUnqualified()) {
3221 Canon = getCanonicalType(QualType(Parm, 0));
3222 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3223 ArgPack);
3224 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3225 }
3226
3227 SubstTemplateTypeParmPackType *SubstParm
3228 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3229 ArgPack);
3230 Types.push_back(SubstParm);
3231 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3232 return QualType(SubstParm, 0);
3233}
3234
Douglas Gregoreff93e02009-02-05 23:33:38 +00003235/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003236/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003237/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003238QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003239 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003240 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003241 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003242 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003243 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003244 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003245 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3246
3247 if (TypeParm)
3248 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003249
Chandler Carruth08836322011-05-01 00:51:33 +00003250 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003251 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003252 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003253
3254 TemplateTypeParmType *TypeCheck
3255 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3256 assert(!TypeCheck && "Template type parameter canonical type broken");
3257 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003258 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003259 TypeParm = new (*this, TypeAlignment)
3260 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003261
3262 Types.push_back(TypeParm);
3263 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3264
3265 return QualType(TypeParm, 0);
3266}
3267
John McCalle78aac42010-03-10 03:28:59 +00003268TypeSourceInfo *
3269ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3270 SourceLocation NameLoc,
3271 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003272 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003273 assert(!Name.getAsDependentTemplateName() &&
3274 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003275 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003276
3277 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003278 TemplateSpecializationTypeLoc TL =
3279 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003280 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003281 TL.setTemplateNameLoc(NameLoc);
3282 TL.setLAngleLoc(Args.getLAngleLoc());
3283 TL.setRAngleLoc(Args.getRAngleLoc());
3284 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3285 TL.setArgLocInfo(i, Args[i].getLocInfo());
3286 return DI;
3287}
3288
Mike Stump11289f42009-09-09 15:08:12 +00003289QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003290ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003291 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003292 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003293 assert(!Template.getAsDependentTemplateName() &&
3294 "No dependent template names here!");
3295
John McCall6b51f282009-11-23 01:53:49 +00003296 unsigned NumArgs = Args.size();
3297
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003298 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003299 ArgVec.reserve(NumArgs);
3300 for (unsigned i = 0; i != NumArgs; ++i)
3301 ArgVec.push_back(Args[i].getArgument());
3302
John McCall2408e322010-04-27 00:57:59 +00003303 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003304 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003305}
3306
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003307#ifndef NDEBUG
3308static bool hasAnyPackExpansions(const TemplateArgument *Args,
3309 unsigned NumArgs) {
3310 for (unsigned I = 0; I != NumArgs; ++I)
3311 if (Args[I].isPackExpansion())
3312 return true;
3313
3314 return true;
3315}
3316#endif
3317
John McCall0ad16662009-10-29 08:12:44 +00003318QualType
3319ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003320 const TemplateArgument *Args,
3321 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003322 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003323 assert(!Template.getAsDependentTemplateName() &&
3324 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003325 // Look through qualified template names.
3326 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3327 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003328
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003329 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003330 Template.getAsTemplateDecl() &&
3331 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003332 QualType CanonType;
3333 if (!Underlying.isNull())
3334 CanonType = getCanonicalType(Underlying);
3335 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003336 // We can get here with an alias template when the specialization contains
3337 // a pack expansion that does not match up with a parameter pack.
3338 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3339 "Caller must compute aliased type");
3340 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003341 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3342 NumArgs);
3343 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003344
Douglas Gregora8e02e72009-07-28 23:00:59 +00003345 // Allocate the (non-canonical) template specialization type, but don't
3346 // try to unique it: these types typically have location information that
3347 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003348 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3349 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003350 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003351 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003352 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003353 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3354 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003355
Douglas Gregor8bf42052009-02-09 18:46:07 +00003356 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003357 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003358}
3359
Mike Stump11289f42009-09-09 15:08:12 +00003360QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003361ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3362 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003363 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003364 assert(!Template.getAsDependentTemplateName() &&
3365 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003366
Douglas Gregore29139c2011-03-03 17:04:51 +00003367 // Look through qualified template names.
3368 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3369 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003370
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003371 // Build the canonical template specialization type.
3372 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003373 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003374 CanonArgs.reserve(NumArgs);
3375 for (unsigned I = 0; I != NumArgs; ++I)
3376 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3377
3378 // Determine whether this canonical template specialization type already
3379 // exists.
3380 llvm::FoldingSetNodeID ID;
3381 TemplateSpecializationType::Profile(ID, CanonTemplate,
3382 CanonArgs.data(), NumArgs, *this);
3383
Craig Topper36250ad2014-05-12 05:36:57 +00003384 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003385 TemplateSpecializationType *Spec
3386 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3387
3388 if (!Spec) {
3389 // Allocate a new canonical template specialization type.
3390 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3391 sizeof(TemplateArgument) * NumArgs),
3392 TypeAlignment);
3393 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3394 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003395 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003396 Types.push_back(Spec);
3397 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3398 }
3399
3400 assert(Spec->isDependentType() &&
3401 "Non-dependent template-id type must have a canonical type");
3402 return QualType(Spec, 0);
3403}
3404
3405QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003406ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3407 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003408 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003409 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003410 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003411
Craig Topper36250ad2014-05-12 05:36:57 +00003412 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003413 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003414 if (T)
3415 return QualType(T, 0);
3416
Douglas Gregorc42075a2010-02-04 18:10:26 +00003417 QualType Canon = NamedType;
3418 if (!Canon.isCanonical()) {
3419 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003420 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3421 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003422 (void)CheckT;
3423 }
3424
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003425 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003426 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003427 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003428 return QualType(T, 0);
3429}
3430
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003431QualType
Jay Foad39c79802011-01-12 09:06:06 +00003432ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003433 llvm::FoldingSetNodeID ID;
3434 ParenType::Profile(ID, InnerType);
3435
Craig Topper36250ad2014-05-12 05:36:57 +00003436 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003437 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3438 if (T)
3439 return QualType(T, 0);
3440
3441 QualType Canon = InnerType;
3442 if (!Canon.isCanonical()) {
3443 Canon = getCanonicalType(InnerType);
3444 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3445 assert(!CheckT && "Paren canonical type broken");
3446 (void)CheckT;
3447 }
3448
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003449 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003450 Types.push_back(T);
3451 ParenTypes.InsertNode(T, InsertPos);
3452 return QualType(T, 0);
3453}
3454
Douglas Gregor02085352010-03-31 20:19:30 +00003455QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3456 NestedNameSpecifier *NNS,
3457 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003458 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003459 if (Canon.isNull()) {
3460 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003461 ElaboratedTypeKeyword CanonKeyword = Keyword;
3462 if (Keyword == ETK_None)
3463 CanonKeyword = ETK_Typename;
3464
3465 if (CanonNNS != NNS || CanonKeyword != Keyword)
3466 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003467 }
3468
3469 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003470 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003471
Craig Topper36250ad2014-05-12 05:36:57 +00003472 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003473 DependentNameType *T
3474 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003475 if (T)
3476 return QualType(T, 0);
3477
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003478 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003479 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003480 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003481 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003482}
3483
Mike Stump11289f42009-09-09 15:08:12 +00003484QualType
John McCallc392f372010-06-11 00:33:02 +00003485ASTContext::getDependentTemplateSpecializationType(
3486 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003487 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003488 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003489 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003490 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003491 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003492 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3493 ArgCopy.push_back(Args[I].getArgument());
3494 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3495 ArgCopy.size(),
3496 ArgCopy.data());
3497}
3498
3499QualType
3500ASTContext::getDependentTemplateSpecializationType(
3501 ElaboratedTypeKeyword Keyword,
3502 NestedNameSpecifier *NNS,
3503 const IdentifierInfo *Name,
3504 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003505 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003506 assert((!NNS || NNS->isDependent()) &&
3507 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003508
Douglas Gregorc42075a2010-02-04 18:10:26 +00003509 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003510 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3511 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003512
Craig Topper36250ad2014-05-12 05:36:57 +00003513 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003514 DependentTemplateSpecializationType *T
3515 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003516 if (T)
3517 return QualType(T, 0);
3518
John McCallc392f372010-06-11 00:33:02 +00003519 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003520
John McCallc392f372010-06-11 00:33:02 +00003521 ElaboratedTypeKeyword CanonKeyword = Keyword;
3522 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3523
3524 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003525 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003526 for (unsigned I = 0; I != NumArgs; ++I) {
3527 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3528 if (!CanonArgs[I].structurallyEquals(Args[I]))
3529 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003530 }
3531
John McCallc392f372010-06-11 00:33:02 +00003532 QualType Canon;
3533 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3534 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3535 Name, NumArgs,
3536 CanonArgs.data());
3537
3538 // Find the insert position again.
3539 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3540 }
3541
3542 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3543 sizeof(TemplateArgument) * NumArgs),
3544 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003545 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003546 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003547 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003548 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003549 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003550}
3551
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003552QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003553 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003554 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003555 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003556
3557 assert(Pattern->containsUnexpandedParameterPack() &&
3558 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003559 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003560 PackExpansionType *T
3561 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3562 if (T)
3563 return QualType(T, 0);
3564
3565 QualType Canon;
3566 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003567 Canon = getCanonicalType(Pattern);
3568 // The canonical type might not contain an unexpanded parameter pack, if it
3569 // contains an alias template specialization which ignores one of its
3570 // parameters.
3571 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003572 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003573
Richard Smith68eea502012-07-16 00:20:35 +00003574 // Find the insert position again, in case we inserted an element into
3575 // PackExpansionTypes and invalidated our insert position.
3576 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3577 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003578 }
3579
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003580 T = new (*this, TypeAlignment)
3581 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003582 Types.push_back(T);
3583 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003584 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003585}
3586
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003587/// CmpProtocolNames - Comparison predicate for sorting protocols
3588/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003589static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3590 ObjCProtocolDecl *const *RHS) {
3591 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003592}
3593
John McCall8b07ec22010-05-15 11:32:37 +00003594static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003595 unsigned NumProtocols) {
3596 if (NumProtocols == 0) return true;
3597
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003598 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3599 return false;
3600
John McCallfc93cf92009-10-22 22:37:11 +00003601 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003602 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003603 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003604 return false;
3605 return true;
3606}
3607
3608static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003609 unsigned &NumProtocols) {
3610 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003611
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003612 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003613 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003614
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003615 // Canonicalize.
3616 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3617 Protocols[I] = Protocols[I]->getCanonicalDecl();
3618
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003619 // Remove duplicates.
3620 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3621 NumProtocols = ProtocolsEnd-Protocols;
3622}
3623
John McCall8b07ec22010-05-15 11:32:37 +00003624QualType ASTContext::getObjCObjectType(QualType BaseType,
3625 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003626 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003627 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003628 llvm::makeArrayRef(Protocols, NumProtocols),
3629 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003630}
3631
3632QualType ASTContext::getObjCObjectType(
3633 QualType baseType,
3634 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003635 ArrayRef<ObjCProtocolDecl *> protocols,
3636 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003637 // If the base type is an interface and there aren't any protocols or
3638 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003639 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3640 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003641 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003642
3643 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003644 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003645 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003646 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003647 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3648 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003649
Douglas Gregore9d95f12015-07-07 03:57:35 +00003650 // Determine the type arguments to be used for canonicalization,
3651 // which may be explicitly specified here or written on the base
3652 // type.
3653 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3654 if (effectiveTypeArgs.empty()) {
3655 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3656 effectiveTypeArgs = baseObject->getTypeArgs();
3657 }
John McCallfc93cf92009-10-22 22:37:11 +00003658
Douglas Gregore9d95f12015-07-07 03:57:35 +00003659 // Build the canonical type, which has the canonical base type and a
3660 // sorted-and-uniqued list of protocols and the type arguments
3661 // canonicalized.
3662 QualType canonical;
3663 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3664 effectiveTypeArgs.end(),
3665 [&](QualType type) {
3666 return type.isCanonical();
3667 });
3668 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3669 protocols.size());
3670 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3671 // Determine the canonical type arguments.
3672 ArrayRef<QualType> canonTypeArgs;
3673 SmallVector<QualType, 4> canonTypeArgsVec;
3674 if (!typeArgsAreCanonical) {
3675 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3676 for (auto typeArg : effectiveTypeArgs)
3677 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3678 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003679 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003680 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003681 }
3682
Douglas Gregore9d95f12015-07-07 03:57:35 +00003683 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3684 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3685 if (!protocolsSorted) {
3686 canonProtocolsVec.insert(canonProtocolsVec.begin(),
3687 protocols.begin(),
3688 protocols.end());
3689 unsigned uniqueCount = protocols.size();
3690 SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3691 canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3692 } else {
3693 canonProtocols = protocols;
3694 }
3695
3696 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003697 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003698
John McCallfc93cf92009-10-22 22:37:11 +00003699 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003700 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3701 }
3702
Douglas Gregore9d95f12015-07-07 03:57:35 +00003703 unsigned size = sizeof(ObjCObjectTypeImpl);
3704 size += typeArgs.size() * sizeof(QualType);
3705 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3706 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003707 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003708 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3709 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003710
3711 Types.push_back(T);
3712 ObjCObjectTypes.InsertNode(T, InsertPos);
3713 return QualType(T, 0);
3714}
3715
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003716/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3717/// protocol list adopt all protocols in QT's qualified-id protocol
3718/// list.
3719bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3720 ObjCInterfaceDecl *IC) {
3721 if (!QT->isObjCQualifiedIdType())
3722 return false;
3723
3724 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3725 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003726 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003727 if (!IC->ClassImplementsProtocol(Proto, false))
3728 return false;
3729 }
3730 return true;
3731 }
3732 return false;
3733}
3734
3735/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3736/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3737/// of protocols.
3738bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3739 ObjCInterfaceDecl *IDecl) {
3740 if (!QT->isObjCQualifiedIdType())
3741 return false;
3742 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3743 if (!OPT)
3744 return false;
3745 if (!IDecl->hasDefinition())
3746 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003747 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3748 CollectInheritedProtocols(IDecl, InheritedProtocols);
3749 if (InheritedProtocols.empty())
3750 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003751 // Check that if every protocol in list of id<plist> conforms to a protcol
3752 // of IDecl's, then bridge casting is ok.
3753 bool Conforms = false;
3754 for (auto *Proto : OPT->quals()) {
3755 Conforms = false;
3756 for (auto *PI : InheritedProtocols) {
3757 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3758 Conforms = true;
3759 break;
3760 }
3761 }
3762 if (!Conforms)
3763 break;
3764 }
3765 if (Conforms)
3766 return true;
3767
Aaron Ballman83731462014-03-17 16:14:00 +00003768 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003769 // If both the right and left sides have qualifiers.
3770 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003771 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003772 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003773 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003774 break;
3775 }
3776 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003777 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003778 }
3779 return true;
3780}
3781
John McCall8b07ec22010-05-15 11:32:37 +00003782/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3783/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003784QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003785 llvm::FoldingSetNodeID ID;
3786 ObjCObjectPointerType::Profile(ID, ObjectT);
3787
Craig Topper36250ad2014-05-12 05:36:57 +00003788 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003789 if (ObjCObjectPointerType *QT =
3790 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3791 return QualType(QT, 0);
3792
3793 // Find the canonical object type.
3794 QualType Canonical;
3795 if (!ObjectT.isCanonical()) {
3796 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3797
3798 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003799 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3800 }
3801
Douglas Gregorf85bee62010-02-08 22:59:26 +00003802 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003803 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3804 ObjCObjectPointerType *QType =
3805 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003806
Steve Narofffb4330f2009-06-17 22:40:22 +00003807 Types.push_back(QType);
3808 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003809 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003810}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003811
Douglas Gregor1c283312010-08-11 12:19:30 +00003812/// getObjCInterfaceType - Return the unique reference to the type for the
3813/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003814QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3815 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003816 if (Decl->TypeForDecl)
3817 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003818
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003819 if (PrevDecl) {
3820 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3821 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3822 return QualType(PrevDecl->TypeForDecl, 0);
3823 }
3824
Douglas Gregor7671e532011-12-16 16:34:57 +00003825 // Prefer the definition, if there is one.
3826 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3827 Decl = Def;
3828
Douglas Gregor1c283312010-08-11 12:19:30 +00003829 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3830 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3831 Decl->TypeForDecl = T;
3832 Types.push_back(T);
3833 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003834}
3835
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003836/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3837/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003838/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003839/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003840/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003841QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003842 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003843 if (tofExpr->isTypeDependent()) {
3844 llvm::FoldingSetNodeID ID;
3845 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003846
Craig Topper36250ad2014-05-12 05:36:57 +00003847 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003848 DependentTypeOfExprType *Canon
3849 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3850 if (Canon) {
3851 // We already have a "canonical" version of an identical, dependent
3852 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003853 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003854 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003855 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003856 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003857 Canon
3858 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003859 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3860 toe = Canon;
3861 }
3862 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003863 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003864 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003865 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003866 Types.push_back(toe);
3867 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003868}
3869
Steve Naroffa773cd52007-08-01 18:02:17 +00003870/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003871/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003872/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003873/// an issue. This doesn't affect the type checker, since it operates
3874/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003875QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003876 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003877 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003878 Types.push_back(tot);
3879 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003880}
3881
Anders Carlssonad6bd352009-06-24 21:24:56 +00003882
Richard Smith8eb1d322014-06-05 20:13:13 +00003883/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3884/// nodes. This would never be helpful, since each such type has its own
3885/// expression, and would not give a significant memory saving, since there
3886/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003887QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003888 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003889
3890 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003891 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003892 // unique dependent type. Two such decltype-specifiers refer to the same
3893 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003894 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003895 llvm::FoldingSetNodeID ID;
3896 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003897
Craig Topper36250ad2014-05-12 05:36:57 +00003898 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003899 DependentDecltypeType *Canon
3900 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003901 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003902 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003903 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003904 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003905 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003906 dt = new (*this, TypeAlignment)
3907 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003908 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003909 dt = new (*this, TypeAlignment)
3910 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003911 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003912 Types.push_back(dt);
3913 return QualType(dt, 0);
3914}
3915
Alexis Hunte852b102011-05-24 22:41:36 +00003916/// getUnaryTransformationType - We don't unique these, since the memory
3917/// savings are minimal and these are rare.
3918QualType ASTContext::getUnaryTransformType(QualType BaseType,
3919 QualType UnderlyingType,
3920 UnaryTransformType::UTTKind Kind)
3921 const {
3922 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003923 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3924 Kind,
3925 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003926 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003927 Types.push_back(Ty);
3928 return QualType(Ty, 0);
3929}
3930
Richard Smith2a7d4812013-05-04 07:00:32 +00003931/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3932/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3933/// canonical deduced-but-dependent 'auto' type.
3934QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003935 bool IsDependent) const {
3936 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003937 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003938
Richard Smith2a7d4812013-05-04 07:00:32 +00003939 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003940 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003941 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003942 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003943 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3944 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003945
Richard Smith74aeef52013-04-26 16:15:35 +00003946 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003947 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003948 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003949 Types.push_back(AT);
3950 if (InsertPos)
3951 AutoTypes.InsertNode(AT, InsertPos);
3952 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003953}
3954
Eli Friedman0dfb8892011-10-06 23:00:33 +00003955/// getAtomicType - Return the uniqued reference to the atomic type for
3956/// the given value type.
3957QualType ASTContext::getAtomicType(QualType T) const {
3958 // Unique pointers, to guarantee there is only one pointer of a particular
3959 // structure.
3960 llvm::FoldingSetNodeID ID;
3961 AtomicType::Profile(ID, T);
3962
Craig Topper36250ad2014-05-12 05:36:57 +00003963 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003964 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3965 return QualType(AT, 0);
3966
3967 // If the atomic value type isn't canonical, this won't be a canonical type
3968 // either, so fill in the canonical type field.
3969 QualType Canonical;
3970 if (!T.isCanonical()) {
3971 Canonical = getAtomicType(getCanonicalType(T));
3972
3973 // Get the new insert position for the node we care about.
3974 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003975 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003976 }
3977 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3978 Types.push_back(New);
3979 AtomicTypes.InsertNode(New, InsertPos);
3980 return QualType(New, 0);
3981}
3982
Richard Smith02e85f32011-04-14 22:09:26 +00003983/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3984QualType ASTContext::getAutoDeductType() const {
3985 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003986 AutoDeductTy = QualType(
3987 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003988 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003989 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003990 return AutoDeductTy;
3991}
3992
3993/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3994QualType ASTContext::getAutoRRefDeductType() const {
3995 if (AutoRRefDeductTy.isNull())
3996 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3997 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3998 return AutoRRefDeductTy;
3999}
4000
Chris Lattnerfb072462007-01-23 05:45:31 +00004001/// getTagDeclType - Return the unique reference to the type for the
4002/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004003QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004004 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004005 // FIXME: What is the design on getTagDeclType when it requires casting
4006 // away const? mutable?
4007 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004008}
4009
Mike Stump11289f42009-09-09 15:08:12 +00004010/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4011/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4012/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004013CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004014 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004015}
Chris Lattnerfb072462007-01-23 05:45:31 +00004016
Hans Wennborg27541db2011-10-27 08:29:09 +00004017/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4018CanQualType ASTContext::getIntMaxType() const {
4019 return getFromTargetType(Target->getIntMaxType());
4020}
4021
4022/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4023CanQualType ASTContext::getUIntMaxType() const {
4024 return getFromTargetType(Target->getUIntMaxType());
4025}
4026
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004027/// getSignedWCharType - Return the type of "signed wchar_t".
4028/// Used when in C++, as a GCC extension.
4029QualType ASTContext::getSignedWCharType() const {
4030 // FIXME: derive from "Target" ?
4031 return WCharTy;
4032}
4033
4034/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4035/// Used when in C++, as a GCC extension.
4036QualType ASTContext::getUnsignedWCharType() const {
4037 // FIXME: derive from "Target" ?
4038 return UnsignedIntTy;
4039}
4040
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004041QualType ASTContext::getIntPtrType() const {
4042 return getFromTargetType(Target->getIntPtrType());
4043}
4044
4045QualType ASTContext::getUIntPtrType() const {
4046 return getCorrespondingUnsignedType(getIntPtrType());
4047}
4048
Hans Wennborg27541db2011-10-27 08:29:09 +00004049/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004050/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4051QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004052 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004053}
4054
Eli Friedman4e91899e2012-11-27 02:58:24 +00004055/// \brief Return the unique type for "pid_t" defined in
4056/// <sys/types.h>. We need this to compute the correct type for vfork().
4057QualType ASTContext::getProcessIDType() const {
4058 return getFromTargetType(Target->getProcessIDType());
4059}
4060
Chris Lattnera21ad802008-04-02 05:18:44 +00004061//===----------------------------------------------------------------------===//
4062// Type Operators
4063//===----------------------------------------------------------------------===//
4064
Jay Foad39c79802011-01-12 09:06:06 +00004065CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004066 // Push qualifiers into arrays, and then discard any remaining
4067 // qualifiers.
4068 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004069 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004070 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004071 QualType Result;
4072 if (isa<ArrayType>(Ty)) {
4073 Result = getArrayDecayedType(QualType(Ty,0));
4074 } else if (isa<FunctionType>(Ty)) {
4075 Result = getPointerType(QualType(Ty, 0));
4076 } else {
4077 Result = QualType(Ty, 0);
4078 }
4079
4080 return CanQualType::CreateUnsafe(Result);
4081}
4082
John McCall6c9dd522011-01-18 07:41:22 +00004083QualType ASTContext::getUnqualifiedArrayType(QualType type,
4084 Qualifiers &quals) {
4085 SplitQualType splitType = type.getSplitUnqualifiedType();
4086
4087 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4088 // the unqualified desugared type and then drops it on the floor.
4089 // We then have to strip that sugar back off with
4090 // getUnqualifiedDesugaredType(), which is silly.
4091 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004092 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004093
4094 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004095 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004096 quals = splitType.Quals;
4097 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004098 }
4099
John McCall6c9dd522011-01-18 07:41:22 +00004100 // Otherwise, recurse on the array's element type.
4101 QualType elementType = AT->getElementType();
4102 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4103
4104 // If that didn't change the element type, AT has no qualifiers, so we
4105 // can just use the results in splitType.
4106 if (elementType == unqualElementType) {
4107 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004108 quals = splitType.Quals;
4109 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004110 }
4111
4112 // Otherwise, add in the qualifiers from the outermost type, then
4113 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004114 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004115
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004116 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004117 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004118 CAT->getSizeModifier(), 0);
4119 }
4120
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004121 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004122 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004123 }
4124
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004125 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004126 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004127 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004128 VAT->getSizeModifier(),
4129 VAT->getIndexTypeCVRQualifiers(),
4130 VAT->getBracketsRange());
4131 }
4132
4133 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004134 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004135 DSAT->getSizeModifier(), 0,
4136 SourceRange());
4137}
4138
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004139/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4140/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4141/// they point to and return true. If T1 and T2 aren't pointer types
4142/// or pointer-to-member types, or if they are not similar at this
4143/// level, returns false and leaves T1 and T2 unchanged. Top-level
4144/// qualifiers on T1 and T2 are ignored. This function will typically
4145/// be called in a loop that successively "unwraps" pointer and
4146/// pointer-to-member types to compare them at each level.
4147bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4148 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4149 *T2PtrType = T2->getAs<PointerType>();
4150 if (T1PtrType && T2PtrType) {
4151 T1 = T1PtrType->getPointeeType();
4152 T2 = T2PtrType->getPointeeType();
4153 return true;
4154 }
4155
4156 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4157 *T2MPType = T2->getAs<MemberPointerType>();
4158 if (T1MPType && T2MPType &&
4159 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4160 QualType(T2MPType->getClass(), 0))) {
4161 T1 = T1MPType->getPointeeType();
4162 T2 = T2MPType->getPointeeType();
4163 return true;
4164 }
4165
David Blaikiebbafb8a2012-03-11 07:00:24 +00004166 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004167 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4168 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4169 if (T1OPType && T2OPType) {
4170 T1 = T1OPType->getPointeeType();
4171 T2 = T2OPType->getPointeeType();
4172 return true;
4173 }
4174 }
4175
4176 // FIXME: Block pointers, too?
4177
4178 return false;
4179}
4180
Jay Foad39c79802011-01-12 09:06:06 +00004181DeclarationNameInfo
4182ASTContext::getNameForTemplate(TemplateName Name,
4183 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004184 switch (Name.getKind()) {
4185 case TemplateName::QualifiedTemplate:
4186 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004187 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004188 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4189 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004190
John McCalld9dfe3a2011-06-30 08:33:18 +00004191 case TemplateName::OverloadedTemplate: {
4192 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4193 // DNInfo work in progress: CHECKME: what about DNLoc?
4194 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4195 }
4196
4197 case TemplateName::DependentTemplate: {
4198 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004199 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004200 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004201 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4202 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004203 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004204 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4205 // DNInfo work in progress: FIXME: source locations?
4206 DeclarationNameLoc DNLoc;
4207 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4208 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4209 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004210 }
4211 }
4212
John McCalld9dfe3a2011-06-30 08:33:18 +00004213 case TemplateName::SubstTemplateTemplateParm: {
4214 SubstTemplateTemplateParmStorage *subst
4215 = Name.getAsSubstTemplateTemplateParm();
4216 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4217 NameLoc);
4218 }
4219
4220 case TemplateName::SubstTemplateTemplateParmPack: {
4221 SubstTemplateTemplateParmPackStorage *subst
4222 = Name.getAsSubstTemplateTemplateParmPack();
4223 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4224 NameLoc);
4225 }
4226 }
4227
4228 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004229}
4230
Jay Foad39c79802011-01-12 09:06:06 +00004231TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004232 switch (Name.getKind()) {
4233 case TemplateName::QualifiedTemplate:
4234 case TemplateName::Template: {
4235 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004236 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004237 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004238 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4239
4240 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004241 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004242 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004243
John McCalld9dfe3a2011-06-30 08:33:18 +00004244 case TemplateName::OverloadedTemplate:
4245 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004246
John McCalld9dfe3a2011-06-30 08:33:18 +00004247 case TemplateName::DependentTemplate: {
4248 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4249 assert(DTN && "Non-dependent template names must refer to template decls.");
4250 return DTN->CanonicalTemplateName;
4251 }
4252
4253 case TemplateName::SubstTemplateTemplateParm: {
4254 SubstTemplateTemplateParmStorage *subst
4255 = Name.getAsSubstTemplateTemplateParm();
4256 return getCanonicalTemplateName(subst->getReplacement());
4257 }
4258
4259 case TemplateName::SubstTemplateTemplateParmPack: {
4260 SubstTemplateTemplateParmPackStorage *subst
4261 = Name.getAsSubstTemplateTemplateParmPack();
4262 TemplateTemplateParmDecl *canonParameter
4263 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4264 TemplateArgument canonArgPack
4265 = getCanonicalTemplateArgument(subst->getArgumentPack());
4266 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4267 }
4268 }
4269
4270 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004271}
4272
Douglas Gregoradee3e32009-11-11 23:06:43 +00004273bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4274 X = getCanonicalTemplateName(X);
4275 Y = getCanonicalTemplateName(Y);
4276 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4277}
4278
Mike Stump11289f42009-09-09 15:08:12 +00004279TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004280ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004281 switch (Arg.getKind()) {
4282 case TemplateArgument::Null:
4283 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004284
Douglas Gregora8e02e72009-07-28 23:00:59 +00004285 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004286 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004287
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004288 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004289 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004290 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004291 }
Mike Stump11289f42009-09-09 15:08:12 +00004292
Eli Friedmanb826a002012-09-26 02:36:12 +00004293 case TemplateArgument::NullPtr:
4294 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4295 /*isNullPtr*/true);
4296
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004297 case TemplateArgument::Template:
4298 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004299
4300 case TemplateArgument::TemplateExpansion:
4301 return TemplateArgument(getCanonicalTemplateName(
4302 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004303 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004304
Douglas Gregora8e02e72009-07-28 23:00:59 +00004305 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004306 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004307
Douglas Gregora8e02e72009-07-28 23:00:59 +00004308 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004309 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004310
Douglas Gregora8e02e72009-07-28 23:00:59 +00004311 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004312 if (Arg.pack_size() == 0)
4313 return Arg;
4314
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004315 TemplateArgument *CanonArgs
4316 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004317 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004318 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004319 AEnd = Arg.pack_end();
4320 A != AEnd; (void)++A, ++Idx)
4321 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004322
Benjamin Kramercce63472015-08-05 09:40:22 +00004323 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004324 }
4325 }
4326
4327 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004328 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004329}
4330
Douglas Gregor333489b2009-03-27 23:10:48 +00004331NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004332ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004333 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004334 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004335
4336 switch (NNS->getKind()) {
4337 case NestedNameSpecifier::Identifier:
4338 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004339 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004340 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4341 NNS->getAsIdentifier());
4342
4343 case NestedNameSpecifier::Namespace:
4344 // A namespace is canonical; build a nested-name-specifier with
4345 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004346 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004347 NNS->getAsNamespace()->getOriginalNamespace());
4348
4349 case NestedNameSpecifier::NamespaceAlias:
4350 // A namespace is canonical; build a nested-name-specifier with
4351 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004352 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004353 NNS->getAsNamespaceAlias()->getNamespace()
4354 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004355
4356 case NestedNameSpecifier::TypeSpec:
4357 case NestedNameSpecifier::TypeSpecWithTemplate: {
4358 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004359
4360 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4361 // break it apart into its prefix and identifier, then reconsititute those
4362 // as the canonical nested-name-specifier. This is required to canonicalize
4363 // a dependent nested-name-specifier involving typedefs of dependent-name
4364 // types, e.g.,
4365 // typedef typename T::type T1;
4366 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004367 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4368 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004369 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004370
Eli Friedman5358a0a2012-03-03 04:09:56 +00004371 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4372 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4373 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004374 return NestedNameSpecifier::Create(*this, nullptr, false,
4375 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004376 }
4377
4378 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004379 case NestedNameSpecifier::Super:
4380 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004381 return NNS;
4382 }
4383
David Blaikie8a40f702012-01-17 06:56:22 +00004384 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004385}
4386
Chris Lattner7adf0762008-08-04 07:31:14 +00004387
Jay Foad39c79802011-01-12 09:06:06 +00004388const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004389 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004390 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004391 // Handle the common positive case fast.
4392 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4393 return AT;
4394 }
Mike Stump11289f42009-09-09 15:08:12 +00004395
John McCall8ccfcb52009-09-24 19:53:00 +00004396 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004397 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004398 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004399
John McCall8ccfcb52009-09-24 19:53:00 +00004400 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004401 // implements C99 6.7.3p8: "If the specification of an array type includes
4402 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004403
Chris Lattner7adf0762008-08-04 07:31:14 +00004404 // If we get here, we either have type qualifiers on the type, or we have
4405 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004406 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004407
John McCall33ddac02011-01-19 10:06:00 +00004408 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004409 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004410
Chris Lattner7adf0762008-08-04 07:31:14 +00004411 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004412 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004413 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004414 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004415
Chris Lattner7adf0762008-08-04 07:31:14 +00004416 // Otherwise, we have an array and we have qualifiers on it. Push the
4417 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004418 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004419
Chris Lattner7adf0762008-08-04 07:31:14 +00004420 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4421 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4422 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004423 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004424 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4425 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4426 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004427 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004428
Mike Stump11289f42009-09-09 15:08:12 +00004429 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004430 = dyn_cast<DependentSizedArrayType>(ATy))
4431 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004432 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004433 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004434 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004435 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004436 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004437
Chris Lattner7adf0762008-08-04 07:31:14 +00004438 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004439 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004440 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004441 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004442 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004443 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004444}
4445
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004446QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004447 if (T->isArrayType() || T->isFunctionType())
4448 return getDecayedType(T);
4449 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004450}
4451
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004452QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004453 T = getVariableArrayDecayedType(T);
4454 T = getAdjustedParameterType(T);
4455 return T.getUnqualifiedType();
4456}
4457
David Majnemerd09a51c2015-03-03 01:50:05 +00004458QualType ASTContext::getExceptionObjectType(QualType T) const {
4459 // C++ [except.throw]p3:
4460 // A throw-expression initializes a temporary object, called the exception
4461 // object, the type of which is determined by removing any top-level
4462 // cv-qualifiers from the static type of the operand of throw and adjusting
4463 // the type from "array of T" or "function returning T" to "pointer to T"
4464 // or "pointer to function returning T", [...]
4465 T = getVariableArrayDecayedType(T);
4466 if (T->isArrayType() || T->isFunctionType())
4467 T = getDecayedType(T);
4468 return T.getUnqualifiedType();
4469}
4470
Chris Lattnera21ad802008-04-02 05:18:44 +00004471/// getArrayDecayedType - Return the properly qualified result of decaying the
4472/// specified array type to a pointer. This operation is non-trivial when
4473/// handling typedefs etc. The canonical type of "T" must be an array type,
4474/// this returns a pointer to a properly qualified element of the array.
4475///
4476/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004477QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004478 // Get the element type with 'getAsArrayType' so that we don't lose any
4479 // typedefs in the element type of the array. This also handles propagation
4480 // of type qualifiers from the array type into the element type if present
4481 // (C99 6.7.3p8).
4482 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4483 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004484
Chris Lattner7adf0762008-08-04 07:31:14 +00004485 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004486
4487 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004488 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004489}
4490
John McCall33ddac02011-01-19 10:06:00 +00004491QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4492 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004493}
4494
John McCall33ddac02011-01-19 10:06:00 +00004495QualType ASTContext::getBaseElementType(QualType type) const {
4496 Qualifiers qs;
4497 while (true) {
4498 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004499 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004500 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004501
John McCall33ddac02011-01-19 10:06:00 +00004502 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004503 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004504 }
Mike Stump11289f42009-09-09 15:08:12 +00004505
John McCall33ddac02011-01-19 10:06:00 +00004506 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004507}
4508
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004509/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004510uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004511ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4512 uint64_t ElementCount = 1;
4513 do {
4514 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004515 CA = dyn_cast_or_null<ConstantArrayType>(
4516 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004517 } while (CA);
4518 return ElementCount;
4519}
4520
Steve Naroff0af91202007-04-27 21:51:21 +00004521/// getFloatingRank - Return a relative rank for floating point types.
4522/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004523static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004524 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004525 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004526
John McCall9dd450b2009-09-21 23:43:11 +00004527 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4528 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004529 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004530 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004531 case BuiltinType::Float: return FloatRank;
4532 case BuiltinType::Double: return DoubleRank;
4533 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004534 }
4535}
4536
Mike Stump11289f42009-09-09 15:08:12 +00004537/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4538/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004539/// 'typeDomain' is a real floating point or complex type.
4540/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004541QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4542 QualType Domain) const {
4543 FloatingRank EltRank = getFloatingRank(Size);
4544 if (Domain->isComplexType()) {
4545 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004546 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004547 case FloatRank: return FloatComplexTy;
4548 case DoubleRank: return DoubleComplexTy;
4549 case LongDoubleRank: return LongDoubleComplexTy;
4550 }
Steve Naroff0af91202007-04-27 21:51:21 +00004551 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004552
4553 assert(Domain->isRealFloatingType() && "Unknown domain!");
4554 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004555 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004556 case FloatRank: return FloatTy;
4557 case DoubleRank: return DoubleTy;
4558 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004559 }
David Blaikief47fa302012-01-17 02:30:50 +00004560 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004561}
4562
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004563/// getFloatingTypeOrder - Compare the rank of the two specified floating
4564/// point types, ignoring the domain of the type (i.e. 'double' ==
4565/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004566/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004567int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004568 FloatingRank LHSR = getFloatingRank(LHS);
4569 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004570
Chris Lattnerb90739d2008-04-06 23:38:49 +00004571 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004572 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004573 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004574 return 1;
4575 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004576}
4577
Chris Lattner76a00cf2008-04-06 22:59:24 +00004578/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4579/// routine will assert if passed a built-in type that isn't an integer or enum,
4580/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004581unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004582 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004583
Chris Lattner76a00cf2008-04-06 22:59:24 +00004584 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004585 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004586 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004587 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004588 case BuiltinType::Char_S:
4589 case BuiltinType::Char_U:
4590 case BuiltinType::SChar:
4591 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004592 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004593 case BuiltinType::Short:
4594 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004595 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004596 case BuiltinType::Int:
4597 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004598 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004599 case BuiltinType::Long:
4600 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004601 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004602 case BuiltinType::LongLong:
4603 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004604 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004605 case BuiltinType::Int128:
4606 case BuiltinType::UInt128:
4607 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004608 }
4609}
4610
Eli Friedman629ffb92009-08-20 04:21:42 +00004611/// \brief Whether this is a promotable bitfield reference according
4612/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4613///
4614/// \returns the type this bit-field will promote to, or NULL if no
4615/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004616QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004617 if (E->isTypeDependent() || E->isValueDependent())
4618 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004619
4620 // FIXME: We should not do this unless E->refersToBitField() is true. This
4621 // matters in C where getSourceBitField() will find bit-fields for various
4622 // cases where the source expression is not a bit-field designator.
4623
John McCalld25db7e2013-05-06 21:39:12 +00004624 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004625 if (!Field)
4626 return QualType();
4627
4628 QualType FT = Field->getType();
4629
Richard Smithcaf33902011-10-10 18:28:20 +00004630 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004631 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004632 // C++ [conv.prom]p5:
4633 // A prvalue for an integral bit-field can be converted to a prvalue of type
4634 // int if int can represent all the values of the bit-field; otherwise, it
4635 // can be converted to unsigned int if unsigned int can represent all the
4636 // values of the bit-field. If the bit-field is larger yet, no integral
4637 // promotion applies to it.
4638 // C11 6.3.1.1/2:
4639 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4640 // If an int can represent all values of the original type (as restricted by
4641 // the width, for a bit-field), the value is converted to an int; otherwise,
4642 // it is converted to an unsigned int.
4643 //
4644 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4645 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004646 if (BitWidth < IntSize)
4647 return IntTy;
4648
4649 if (BitWidth == IntSize)
4650 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4651
4652 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004653 // like the base type. GCC has some weird bugs in this area that we
4654 // deliberately do not follow (GCC follows a pre-standard resolution to
4655 // C's DR315 which treats bit-width as being part of the type, and this leaks
4656 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004657 return QualType();
4658}
4659
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004660/// getPromotedIntegerType - Returns the type that Promotable will
4661/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4662/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004663QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004664 assert(!Promotable.isNull());
4665 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004666 if (const EnumType *ET = Promotable->getAs<EnumType>())
4667 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004668
4669 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4670 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4671 // (3.9.1) can be converted to a prvalue of the first of the following
4672 // types that can represent all the values of its underlying type:
4673 // int, unsigned int, long int, unsigned long int, long long int, or
4674 // unsigned long long int [...]
4675 // FIXME: Is there some better way to compute this?
4676 if (BT->getKind() == BuiltinType::WChar_S ||
4677 BT->getKind() == BuiltinType::WChar_U ||
4678 BT->getKind() == BuiltinType::Char16 ||
4679 BT->getKind() == BuiltinType::Char32) {
4680 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4681 uint64_t FromSize = getTypeSize(BT);
4682 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4683 LongLongTy, UnsignedLongLongTy };
4684 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4685 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4686 if (FromSize < ToSize ||
4687 (FromSize == ToSize &&
4688 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4689 return PromoteTypes[Idx];
4690 }
4691 llvm_unreachable("char type should fit into long long");
4692 }
4693 }
4694
4695 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004696 if (Promotable->isSignedIntegerType())
4697 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004698 uint64_t PromotableSize = getIntWidth(Promotable);
4699 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004700 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4701 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4702}
4703
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004704/// \brief Recurses in pointer/array types until it finds an objc retainable
4705/// type and returns its ownership.
4706Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4707 while (!T.isNull()) {
4708 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4709 return T.getObjCLifetime();
4710 if (T->isArrayType())
4711 T = getBaseElementType(T);
4712 else if (const PointerType *PT = T->getAs<PointerType>())
4713 T = PT->getPointeeType();
4714 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004715 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004716 else
4717 break;
4718 }
4719
4720 return Qualifiers::OCL_None;
4721}
4722
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004723static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4724 // Incomplete enum types are not treated as integer types.
4725 // FIXME: In C++, enum types are never integer types.
4726 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4727 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004728 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004729}
4730
Mike Stump11289f42009-09-09 15:08:12 +00004731/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004732/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004733/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004734int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004735 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4736 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004737
4738 // Unwrap enums to their underlying type.
4739 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4740 LHSC = getIntegerTypeForEnum(ET);
4741 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4742 RHSC = getIntegerTypeForEnum(ET);
4743
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004744 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004745
Chris Lattner76a00cf2008-04-06 22:59:24 +00004746 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4747 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004748
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004749 unsigned LHSRank = getIntegerRank(LHSC);
4750 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004751
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004752 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4753 if (LHSRank == RHSRank) return 0;
4754 return LHSRank > RHSRank ? 1 : -1;
4755 }
Mike Stump11289f42009-09-09 15:08:12 +00004756
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004757 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4758 if (LHSUnsigned) {
4759 // If the unsigned [LHS] type is larger, return it.
4760 if (LHSRank >= RHSRank)
4761 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004762
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004763 // If the signed type can represent all values of the unsigned type, it
4764 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004765 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004766 return -1;
4767 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004768
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004769 // If the unsigned [RHS] type is larger, return it.
4770 if (RHSRank >= LHSRank)
4771 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004772
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004773 // If the signed type can represent all values of the unsigned type, it
4774 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004775 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004776 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004777}
Anders Carlsson98f07902007-08-17 05:31:46 +00004778
Mike Stump11289f42009-09-09 15:08:12 +00004779// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004780QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004781 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004782 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004783 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004784
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004785 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004786
Anders Carlsson98f07902007-08-17 05:31:46 +00004787 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004788 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004789 // int flags;
4790 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004791 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004792 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004793 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004794 FieldTypes[3] = LongTy;
4795
Anders Carlsson98f07902007-08-17 05:31:46 +00004796 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004797 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004798 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004799 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004800 SourceLocation(), nullptr,
4801 FieldTypes[i], /*TInfo=*/nullptr,
4802 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004803 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004804 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004805 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004806 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004807 }
4808
Douglas Gregord5058122010-02-11 01:19:42 +00004809 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811
Anders Carlsson98f07902007-08-17 05:31:46 +00004812 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004813}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004814
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004815QualType ASTContext::getObjCSuperType() const {
4816 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004817 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004818 TUDecl->addDecl(ObjCSuperTypeDecl);
4819 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4820 }
4821 return ObjCSuperType;
4822}
4823
Douglas Gregor512b0772009-04-23 22:29:11 +00004824void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004825 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004826 assert(Rec && "Invalid CFConstantStringType");
4827 CFConstantStringTypeDecl = Rec->getDecl();
4828}
4829
Jay Foad39c79802011-01-12 09:06:06 +00004830QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004831 if (BlockDescriptorType)
4832 return getTagDeclType(BlockDescriptorType);
4833
Alp Toker2dea15b2013-12-17 01:22:38 +00004834 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004835 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004836 RD = buildImplicitRecord("__block_descriptor");
4837 RD->startDefinition();
4838
Mike Stumpd0153282009-10-20 02:12:22 +00004839 QualType FieldTypes[] = {
4840 UnsignedLongTy,
4841 UnsignedLongTy,
4842 };
4843
Craig Topperd6d31ac2013-07-15 08:24:27 +00004844 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004845 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004846 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004847 };
4848
4849 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004850 FieldDecl *Field = FieldDecl::Create(
4851 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004852 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4853 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004854 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004855 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004856 }
4857
Alp Toker2dea15b2013-12-17 01:22:38 +00004858 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004859
Alp Toker2dea15b2013-12-17 01:22:38 +00004860 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004861
4862 return getTagDeclType(BlockDescriptorType);
4863}
4864
Jay Foad39c79802011-01-12 09:06:06 +00004865QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004866 if (BlockDescriptorExtendedType)
4867 return getTagDeclType(BlockDescriptorExtendedType);
4868
Alp Toker2dea15b2013-12-17 01:22:38 +00004869 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004870 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004871 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4872 RD->startDefinition();
4873
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004874 QualType FieldTypes[] = {
4875 UnsignedLongTy,
4876 UnsignedLongTy,
4877 getPointerType(VoidPtrTy),
4878 getPointerType(VoidPtrTy)
4879 };
4880
Craig Topperd6d31ac2013-07-15 08:24:27 +00004881 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004882 "reserved",
4883 "Size",
4884 "CopyFuncPtr",
4885 "DestroyFuncPtr"
4886 };
4887
4888 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004889 FieldDecl *Field = FieldDecl::Create(
4890 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004891 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4892 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004893 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004894 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004895 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004896 }
4897
Alp Toker2dea15b2013-12-17 01:22:38 +00004898 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004899
Alp Toker2dea15b2013-12-17 01:22:38 +00004900 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004901 return getTagDeclType(BlockDescriptorExtendedType);
4902}
4903
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004904/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4905/// requires copy/dispose. Note that this must match the logic
4906/// in buildByrefHelpers.
4907bool ASTContext::BlockRequiresCopying(QualType Ty,
4908 const VarDecl *D) {
4909 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4910 const Expr *copyExpr = getBlockVarCopyInits(D);
4911 if (!copyExpr && record->hasTrivialDestructor()) return false;
4912
Mike Stump94967902009-10-21 18:16:27 +00004913 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004914 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004915
4916 if (!Ty->isObjCRetainableType()) return false;
4917
4918 Qualifiers qs = Ty.getQualifiers();
4919
4920 // If we have lifetime, that dominates.
4921 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4922 assert(getLangOpts().ObjCAutoRefCount);
4923
4924 switch (lifetime) {
4925 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4926
4927 // These are just bits as far as the runtime is concerned.
4928 case Qualifiers::OCL_ExplicitNone:
4929 case Qualifiers::OCL_Autoreleasing:
4930 return false;
4931
4932 // Tell the runtime that this is ARC __weak, called by the
4933 // byref routines.
4934 case Qualifiers::OCL_Weak:
4935 // ARC __strong __block variables need to be retained.
4936 case Qualifiers::OCL_Strong:
4937 return true;
4938 }
4939 llvm_unreachable("fell out of lifetime switch!");
4940 }
4941 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4942 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004943}
4944
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004945bool ASTContext::getByrefLifetime(QualType Ty,
4946 Qualifiers::ObjCLifetime &LifeTime,
4947 bool &HasByrefExtendedLayout) const {
4948
4949 if (!getLangOpts().ObjC1 ||
4950 getLangOpts().getGC() != LangOptions::NonGC)
4951 return false;
4952
4953 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004954 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004955 HasByrefExtendedLayout = true;
4956 LifeTime = Qualifiers::OCL_None;
4957 }
4958 else if (getLangOpts().ObjCAutoRefCount)
4959 LifeTime = Ty.getObjCLifetime();
4960 // MRR.
4961 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4962 LifeTime = Qualifiers::OCL_ExplicitNone;
4963 else
4964 LifeTime = Qualifiers::OCL_None;
4965 return true;
4966}
4967
Douglas Gregorbab8a962011-09-08 01:46:34 +00004968TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4969 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004970 ObjCInstanceTypeDecl =
4971 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004972 return ObjCInstanceTypeDecl;
4973}
4974
Anders Carlsson18acd442007-10-29 06:33:42 +00004975// This returns true if a type has been typedefed to BOOL:
4976// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004977static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004978 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004979 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4980 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004981
Anders Carlssond8499822007-10-29 05:01:08 +00004982 return false;
4983}
4984
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004985/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004986/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004987CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004988 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4989 return CharUnits::Zero();
4990
Ken Dyck40775002010-01-11 17:06:35 +00004991 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004992
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004993 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004994 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004995 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004996 // Treat arrays as pointers, since that's how they're passed in.
4997 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004998 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004999 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005000}
5001
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005002bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5003 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
5004 VD->getType()->isIntegralOrEnumerationType() &&
Alexey Bataev15413ea2015-05-20 11:57:02 +00005005 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005006}
5007
Ken Dyck40775002010-01-11 17:06:35 +00005008static inline
5009std::string charUnitsToString(const CharUnits &CU) {
5010 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005011}
5012
John McCall351762c2011-02-07 10:33:21 +00005013/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005014/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005015std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5016 std::string S;
5017
David Chisnall950a9512009-11-17 19:33:30 +00005018 const BlockDecl *Decl = Expr->getBlockDecl();
5019 QualType BlockTy =
5020 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5021 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005022 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005023 getObjCEncodingForMethodParameter(
5024 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5025 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005026 else
Alp Toker314cc812014-01-25 16:55:45 +00005027 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005028 // Compute size of all parameters.
5029 // Start with computing size of a pointer in number of bytes.
5030 // FIXME: There might(should) be a better way of doing this computation!
5031 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005032 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5033 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005034 for (auto PI : Decl->params()) {
5035 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005036 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005037 if (sz.isZero())
5038 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005039 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005040 ParmOffset += sz;
5041 }
5042 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005043 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005044 // Block pointer and offset.
5045 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005046
5047 // Argument types.
5048 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005049 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005050 QualType PType = PVDecl->getOriginalType();
5051 if (const ArrayType *AT =
5052 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5053 // Use array's original type only if it has known number of
5054 // elements.
5055 if (!isa<ConstantArrayType>(AT))
5056 PType = PVDecl->getType();
5057 } else if (PType->isFunctionType())
5058 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005059 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005060 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5061 S, true /*Extended*/);
5062 else
5063 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005064 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005065 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005066 }
John McCall351762c2011-02-07 10:33:21 +00005067
5068 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005069}
5070
Douglas Gregora9d84932011-05-27 01:19:52 +00005071bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005072 std::string& S) {
5073 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005074 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005075 CharUnits ParmOffset;
5076 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005077 for (auto PI : Decl->params()) {
5078 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005079 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005080 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005081 continue;
5082
David Chisnall50e4eba2010-12-30 14:05:53 +00005083 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005084 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005085 ParmOffset += sz;
5086 }
5087 S += charUnitsToString(ParmOffset);
5088 ParmOffset = CharUnits::Zero();
5089
5090 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005091 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005092 QualType PType = PVDecl->getOriginalType();
5093 if (const ArrayType *AT =
5094 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5095 // Use array's original type only if it has known number of
5096 // elements.
5097 if (!isa<ConstantArrayType>(AT))
5098 PType = PVDecl->getType();
5099 } else if (PType->isFunctionType())
5100 PType = PVDecl->getType();
5101 getObjCEncodingForType(PType, S);
5102 S += charUnitsToString(ParmOffset);
5103 ParmOffset += getObjCEncodingTypeSize(PType);
5104 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005105
5106 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005107}
5108
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005109/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5110/// method parameter or return type. If Extended, include class names and
5111/// block object types.
5112void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5113 QualType T, std::string& S,
5114 bool Extended) const {
5115 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5116 getObjCEncodingForTypeQualifier(QT, S);
5117 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005118 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005119 true /*OutermostType*/,
5120 false /*EncodingProperty*/,
5121 false /*StructField*/,
5122 Extended /*EncodeBlockParameters*/,
5123 Extended /*EncodeClassNames*/);
5124}
5125
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005126/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005127/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005128bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005129 std::string& S,
5130 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005131 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005132 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005133 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5134 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005135 // Compute size of all parameters.
5136 // Start with computing size of a pointer in number of bytes.
5137 // FIXME: There might(should) be a better way of doing this computation!
5138 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005139 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005140 // The first two arguments (self and _cmd) are pointers; account for
5141 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005142 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005143 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005144 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005145 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005146 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005147 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005148 continue;
5149
Ken Dyck40775002010-01-11 17:06:35 +00005150 assert (sz.isPositive() &&
5151 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005152 ParmOffset += sz;
5153 }
Ken Dyck40775002010-01-11 17:06:35 +00005154 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005155 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005156 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005157
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005158 // Argument types.
5159 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005160 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005161 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005162 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005163 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005164 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005165 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5166 // Use array's original type only if it has known number of
5167 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005168 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005169 PType = PVDecl->getType();
5170 } else if (PType->isFunctionType())
5171 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005172 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5173 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005174 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005175 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005176 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005177
5178 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005179}
5180
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005181ObjCPropertyImplDecl *
5182ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5183 const ObjCPropertyDecl *PD,
5184 const Decl *Container) const {
5185 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005186 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005187 if (const ObjCCategoryImplDecl *CID =
5188 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005189 for (auto *PID : CID->property_impls())
5190 if (PID->getPropertyDecl() == PD)
5191 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005192 } else {
5193 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5194 for (auto *PID : OID->property_impls())
5195 if (PID->getPropertyDecl() == PD)
5196 return PID;
5197 }
5198 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005199}
5200
Daniel Dunbar4932b362008-08-28 04:38:10 +00005201/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005202/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005203/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5204/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005205/// Property attributes are stored as a comma-delimited C string. The simple
5206/// attributes readonly and bycopy are encoded as single characters. The
5207/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5208/// encoded as single characters, followed by an identifier. Property types
5209/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005210/// these attributes are defined by the following enumeration:
5211/// @code
5212/// enum PropertyAttributes {
5213/// kPropertyReadOnly = 'R', // property is read-only.
5214/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5215/// kPropertyByref = '&', // property is a reference to the value last assigned
5216/// kPropertyDynamic = 'D', // property is dynamic
5217/// kPropertyGetter = 'G', // followed by getter selector name
5218/// kPropertySetter = 'S', // followed by setter selector name
5219/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005220/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005221/// kPropertyWeak = 'W' // 'weak' property
5222/// kPropertyStrong = 'P' // property GC'able
5223/// kPropertyNonAtomic = 'N' // property non-atomic
5224/// };
5225/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005226void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005227 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005228 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005229 // Collect information from the property implementation decl(s).
5230 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005231 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005232
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005233 if (ObjCPropertyImplDecl *PropertyImpDecl =
5234 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5235 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5236 Dynamic = true;
5237 else
5238 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005239 }
5240
5241 // FIXME: This is not very efficient.
5242 S = "T";
5243
5244 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005245 // GCC has some special rules regarding encoding of properties which
5246 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005247 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005248
5249 if (PD->isReadOnly()) {
5250 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005251 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5252 S += ",C";
5253 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5254 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005255 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5256 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005257 } else {
5258 switch (PD->getSetterKind()) {
5259 case ObjCPropertyDecl::Assign: break;
5260 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005261 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005262 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005263 }
5264 }
5265
5266 // It really isn't clear at all what this means, since properties
5267 // are "dynamic by default".
5268 if (Dynamic)
5269 S += ",D";
5270
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005271 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5272 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005273
Daniel Dunbar4932b362008-08-28 04:38:10 +00005274 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5275 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005276 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005277 }
5278
5279 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5280 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005281 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005282 }
5283
5284 if (SynthesizePID) {
5285 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5286 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005287 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005288 }
5289
5290 // FIXME: OBJCGC: weak & strong
5291}
5292
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005293/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005294/// Another legacy compatibility encoding: 32-bit longs are encoded as
5295/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005296/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5297///
5298void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005299 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005300 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005301 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005302 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005303 else
Jay Foad39c79802011-01-12 09:06:06 +00005304 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005305 PointeeTy = IntTy;
5306 }
5307 }
5308}
5309
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005310void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005311 const FieldDecl *Field,
5312 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005313 // We follow the behavior of gcc, expanding structures which are
5314 // directly pointed to, and expanding embedded structures. Note that
5315 // these rules are sufficient to prevent recursive encoding of the
5316 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005317 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005318 true /* outermost type */, false, false,
5319 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005320}
5321
Joe Groff98ac7d22014-07-07 22:25:15 +00005322void ASTContext::getObjCEncodingForPropertyType(QualType T,
5323 std::string& S) const {
5324 // Encode result type.
5325 // GCC has some special rules regarding encoding of properties which
5326 // closely resembles encoding of ivars.
5327 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5328 true /* outermost type */,
5329 true /* encoding property */);
5330}
5331
John McCall393a78d2012-12-20 02:45:14 +00005332static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5333 BuiltinType::Kind kind) {
5334 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005335 case BuiltinType::Void: return 'v';
5336 case BuiltinType::Bool: return 'B';
5337 case BuiltinType::Char_U:
5338 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005339 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005340 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005341 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005342 case BuiltinType::UInt: return 'I';
5343 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005344 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005345 case BuiltinType::UInt128: return 'T';
5346 case BuiltinType::ULongLong: return 'Q';
5347 case BuiltinType::Char_S:
5348 case BuiltinType::SChar: return 'c';
5349 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005350 case BuiltinType::WChar_S:
5351 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005352 case BuiltinType::Int: return 'i';
5353 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005354 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005355 case BuiltinType::LongLong: return 'q';
5356 case BuiltinType::Int128: return 't';
5357 case BuiltinType::Float: return 'f';
5358 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005359 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005360 case BuiltinType::NullPtr: return '*'; // like char*
5361
5362 case BuiltinType::Half:
5363 // FIXME: potentially need @encodes for these!
5364 return ' ';
5365
5366 case BuiltinType::ObjCId:
5367 case BuiltinType::ObjCClass:
5368 case BuiltinType::ObjCSel:
5369 llvm_unreachable("@encoding ObjC primitive type");
5370
5371 // OpenCL and placeholder types don't need @encodings.
5372 case BuiltinType::OCLImage1d:
5373 case BuiltinType::OCLImage1dArray:
5374 case BuiltinType::OCLImage1dBuffer:
5375 case BuiltinType::OCLImage2d:
5376 case BuiltinType::OCLImage2dArray:
5377 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005378 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005379 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005380 case BuiltinType::Dependent:
5381#define BUILTIN_TYPE(KIND, ID)
5382#define PLACEHOLDER_TYPE(KIND, ID) \
5383 case BuiltinType::KIND:
5384#include "clang/AST/BuiltinTypes.def"
5385 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005386 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005387 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005388}
5389
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005390static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5391 EnumDecl *Enum = ET->getDecl();
5392
5393 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5394 if (!Enum->isFixed())
5395 return 'i';
5396
5397 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005398 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5399 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005400}
5401
Jay Foad39c79802011-01-12 09:06:06 +00005402static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005403 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005404 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005405 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005406 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5407 // The GNU runtime requires more information; bitfields are encoded as b,
5408 // then the offset (in bits) of the first element, then the type of the
5409 // bitfield, then the size in bits. For example, in this structure:
5410 //
5411 // struct
5412 // {
5413 // int integer;
5414 // int flags:2;
5415 // };
5416 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5417 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5418 // information is not especially sensible, but we're stuck with it for
5419 // compatibility with GCC, although providing it breaks anything that
5420 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005421 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005422 const RecordDecl *RD = FD->getParent();
5423 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005424 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005425 if (const EnumType *ET = T->getAs<EnumType>())
5426 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005427 else {
5428 const BuiltinType *BT = T->castAs<BuiltinType>();
5429 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5430 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005431 }
Richard Smithcaf33902011-10-10 18:28:20 +00005432 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005433}
5434
Daniel Dunbar07d07852009-10-18 21:17:35 +00005435// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005436void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5437 bool ExpandPointedToStructures,
5438 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005439 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005440 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005441 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005442 bool StructField,
5443 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005444 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005445 bool EncodePointerToObjCTypedef,
5446 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005447 CanQualType CT = getCanonicalType(T);
5448 switch (CT->getTypeClass()) {
5449 case Type::Builtin:
5450 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005451 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005452 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005453 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5454 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5455 else
5456 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005457 return;
Mike Stump11289f42009-09-09 15:08:12 +00005458
John McCall393a78d2012-12-20 02:45:14 +00005459 case Type::Complex: {
5460 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005461 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005462 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005463 return;
5464 }
John McCall393a78d2012-12-20 02:45:14 +00005465
5466 case Type::Atomic: {
5467 const AtomicType *AT = T->castAs<AtomicType>();
5468 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005469 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005470 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005471 }
John McCall393a78d2012-12-20 02:45:14 +00005472
5473 // encoding for pointer or reference types.
5474 case Type::Pointer:
5475 case Type::LValueReference:
5476 case Type::RValueReference: {
5477 QualType PointeeTy;
5478 if (isa<PointerType>(CT)) {
5479 const PointerType *PT = T->castAs<PointerType>();
5480 if (PT->isObjCSelType()) {
5481 S += ':';
5482 return;
5483 }
5484 PointeeTy = PT->getPointeeType();
5485 } else {
5486 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5487 }
5488
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005489 bool isReadOnly = false;
5490 // For historical/compatibility reasons, the read-only qualifier of the
5491 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5492 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005493 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005494 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005495 if (OutermostType && T.isConstQualified()) {
5496 isReadOnly = true;
5497 S += 'r';
5498 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005499 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005500 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005501 while (P->getAs<PointerType>())
5502 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005503 if (P.isConstQualified()) {
5504 isReadOnly = true;
5505 S += 'r';
5506 }
5507 }
5508 if (isReadOnly) {
5509 // Another legacy compatibility encoding. Some ObjC qualifier and type
5510 // combinations need to be rearranged.
5511 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005512 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005513 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005514 }
Mike Stump11289f42009-09-09 15:08:12 +00005515
Anders Carlssond8499822007-10-29 05:01:08 +00005516 if (PointeeTy->isCharType()) {
5517 // char pointer types should be encoded as '*' unless it is a
5518 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005519 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005520 S += '*';
5521 return;
5522 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005523 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005524 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5525 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5526 S += '#';
5527 return;
5528 }
5529 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5530 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5531 S += '@';
5532 return;
5533 }
5534 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005535 }
Anders Carlssond8499822007-10-29 05:01:08 +00005536 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005537 getLegacyIntegralTypeEncoding(PointeeTy);
5538
Mike Stump11289f42009-09-09 15:08:12 +00005539 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005540 nullptr, false, false, false, false, false, false,
5541 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005542 return;
5543 }
John McCall393a78d2012-12-20 02:45:14 +00005544
5545 case Type::ConstantArray:
5546 case Type::IncompleteArray:
5547 case Type::VariableArray: {
5548 const ArrayType *AT = cast<ArrayType>(CT);
5549
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005550 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005551 // Incomplete arrays are encoded as a pointer to the array element.
5552 S += '^';
5553
Mike Stump11289f42009-09-09 15:08:12 +00005554 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005555 false, ExpandStructures, FD);
5556 } else {
5557 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005558
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005559 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5560 S += llvm::utostr(CAT->getSize().getZExtValue());
5561 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005562 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005563 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5564 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005565 S += '0';
5566 }
Mike Stump11289f42009-09-09 15:08:12 +00005567
5568 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005569 false, ExpandStructures, FD,
5570 false, false, false, false, false, false,
5571 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005572 S += ']';
5573 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005574 return;
5575 }
Mike Stump11289f42009-09-09 15:08:12 +00005576
John McCall393a78d2012-12-20 02:45:14 +00005577 case Type::FunctionNoProto:
5578 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005579 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005580 return;
Mike Stump11289f42009-09-09 15:08:12 +00005581
John McCall393a78d2012-12-20 02:45:14 +00005582 case Type::Record: {
5583 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005584 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005585 // Anonymous structures print as '?'
5586 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5587 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005588 if (ClassTemplateSpecializationDecl *Spec
5589 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5590 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005591 llvm::raw_string_ostream OS(S);
5592 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005593 TemplateArgs.data(),
5594 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005595 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005596 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005597 } else {
5598 S += '?';
5599 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005600 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005601 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005602 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005603 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005604 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005605 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005606 if (FD) {
5607 S += '"';
5608 S += Field->getNameAsString();
5609 S += '"';
5610 }
Mike Stump11289f42009-09-09 15:08:12 +00005611
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005612 // Special case bit-fields.
5613 if (Field->isBitField()) {
5614 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005615 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005616 } else {
5617 QualType qt = Field->getType();
5618 getLegacyIntegralTypeEncoding(qt);
5619 getObjCEncodingForTypeImpl(qt, S, false, true,
5620 FD, /*OutermostType*/false,
5621 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005622 /*StructField*/true,
5623 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005624 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005625 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005626 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005627 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005628 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005629 return;
5630 }
Mike Stump11289f42009-09-09 15:08:12 +00005631
John McCall393a78d2012-12-20 02:45:14 +00005632 case Type::BlockPointer: {
5633 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005634 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005635 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005636 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005637
5638 S += '<';
5639 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005640 getObjCEncodingForTypeImpl(
5641 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5642 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005643 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5644 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005645 // Block self
5646 S += "@?";
5647 // Block parameters
5648 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005649 for (const auto &I : FPT->param_types())
5650 getObjCEncodingForTypeImpl(
5651 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5652 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005653 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5654 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005655 }
5656 S += '>';
5657 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005658 return;
5659 }
Mike Stump11289f42009-09-09 15:08:12 +00005660
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005661 case Type::ObjCObject: {
5662 // hack to match legacy encoding of *id and *Class
5663 QualType Ty = getObjCObjectPointerType(CT);
5664 if (Ty->isObjCIdType()) {
5665 S += "{objc_object=}";
5666 return;
5667 }
5668 else if (Ty->isObjCClassType()) {
5669 S += "{objc_class=}";
5670 return;
5671 }
5672 }
5673
John McCall393a78d2012-12-20 02:45:14 +00005674 case Type::ObjCInterface: {
5675 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005676 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005677 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005678 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005679 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005680 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005681 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005682 DeepCollectObjCIvars(OI, true, Ivars);
5683 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005684 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005685 if (Field->isBitField())
5686 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005687 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005688 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5689 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005690 EncodePointerToObjCTypedef,
5691 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005692 }
5693 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005694 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005695 }
Mike Stump11289f42009-09-09 15:08:12 +00005696
John McCall393a78d2012-12-20 02:45:14 +00005697 case Type::ObjCObjectPointer: {
5698 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005699 if (OPT->isObjCIdType()) {
5700 S += '@';
5701 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005702 }
Mike Stump11289f42009-09-09 15:08:12 +00005703
Steve Narofff0c86112009-10-28 22:03:49 +00005704 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5705 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5706 // Since this is a binary compatibility issue, need to consult with runtime
5707 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005708 S += '#';
5709 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005710 }
Mike Stump11289f42009-09-09 15:08:12 +00005711
Chris Lattnere7cabb92009-07-13 00:10:46 +00005712 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005713 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005714 ExpandPointedToStructures,
5715 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005716 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005717 // Note that we do extended encoding of protocol qualifer list
5718 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005719 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005720 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005721 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005722 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005723 S += '>';
5724 }
5725 S += '"';
5726 }
5727 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005728 }
Mike Stump11289f42009-09-09 15:08:12 +00005729
Chris Lattnere7cabb92009-07-13 00:10:46 +00005730 QualType PointeeTy = OPT->getPointeeType();
5731 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005732 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5733 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005734 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005735 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005736 // {...};
5737 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005738 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005739 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005740 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5741 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5742 DeepCollectObjCIvars(OI, true, Ivars);
5743 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5744 if (cast<FieldDecl>(Ivars[i]) == FD) {
5745 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005746 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005747 S += '}';
5748 return;
5749 }
5750 }
5751 }
Mike Stump11289f42009-09-09 15:08:12 +00005752 getObjCEncodingForTypeImpl(PointeeTy, S,
5753 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005754 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005755 false, false, false, false, false,
5756 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005757 return;
5758 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005759
5760 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005761 if (OPT->getInterfaceDecl() &&
5762 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005763 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005764 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005765 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005766 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005767 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005768 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005769 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005770 S += '"';
5771 }
5772 return;
5773 }
Mike Stump11289f42009-09-09 15:08:12 +00005774
John McCalla9e6e8d2010-05-17 23:56:34 +00005775 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005776 // FIXME: we shoul do better than that. 'M' is available.
5777 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005778 // This matches gcc's encoding, even though technically it is insufficient.
5779 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005780 case Type::Vector:
5781 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005782 // Until we have a coherent encoding of these three types, issue warning.
5783 { if (NotEncodedT)
5784 *NotEncodedT = T;
5785 return;
5786 }
5787
5788 // We could see an undeduced auto type here during error recovery.
5789 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005790 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005791 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005792
Richard Smith27d807c2013-04-30 13:56:41 +00005793
John McCall393a78d2012-12-20 02:45:14 +00005794#define ABSTRACT_TYPE(KIND, BASE)
5795#define TYPE(KIND, BASE)
5796#define DEPENDENT_TYPE(KIND, BASE) \
5797 case Type::KIND:
5798#define NON_CANONICAL_TYPE(KIND, BASE) \
5799 case Type::KIND:
5800#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5801 case Type::KIND:
5802#include "clang/AST/TypeNodes.def"
5803 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005804 }
John McCall393a78d2012-12-20 02:45:14 +00005805 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005806}
5807
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005808void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5809 std::string &S,
5810 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005811 bool includeVBases,
5812 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005813 assert(RDecl && "Expected non-null RecordDecl");
5814 assert(!RDecl->isUnion() && "Should not be called for unions");
5815 if (!RDecl->getDefinition())
5816 return;
5817
5818 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5819 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5820 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5821
5822 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005823 for (const auto &BI : CXXRec->bases()) {
5824 if (!BI.isVirtual()) {
5825 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005826 if (base->isEmpty())
5827 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005828 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005829 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5830 std::make_pair(offs, base));
5831 }
5832 }
5833 }
5834
5835 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005836 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005837 uint64_t offs = layout.getFieldOffset(i);
5838 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005839 std::make_pair(offs, Field));
5840 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005841 }
5842
5843 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005844 for (const auto &BI : CXXRec->vbases()) {
5845 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005846 if (base->isEmpty())
5847 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005848 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005849 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5850 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005851 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5852 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005853 }
5854 }
5855
5856 CharUnits size;
5857 if (CXXRec) {
5858 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5859 } else {
5860 size = layout.getSize();
5861 }
5862
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005863#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005864 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005865#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005866 std::multimap<uint64_t, NamedDecl *>::iterator
5867 CurLayObj = FieldOrBaseOffsets.begin();
5868
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005869 if (CXXRec && CXXRec->isDynamicClass() &&
5870 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005871 if (FD) {
5872 S += "\"_vptr$";
5873 std::string recname = CXXRec->getNameAsString();
5874 if (recname.empty()) recname = "?";
5875 S += recname;
5876 S += '"';
5877 }
5878 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005879#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005880 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005881#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005882 }
5883
5884 if (!RDecl->hasFlexibleArrayMember()) {
5885 // Mark the end of the structure.
5886 uint64_t offs = toBits(size);
5887 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005888 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005889 }
5890
5891 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005892#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005893 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005894 if (CurOffs < CurLayObj->first) {
5895 uint64_t padding = CurLayObj->first - CurOffs;
5896 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5897 // packing/alignment of members is different that normal, in which case
5898 // the encoding will be out-of-sync with the real layout.
5899 // If the runtime switches to just consider the size of types without
5900 // taking into account alignment, we could make padding explicit in the
5901 // encoding (e.g. using arrays of chars). The encoding strings would be
5902 // longer then though.
5903 CurOffs += padding;
5904 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005905#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005906
5907 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005908 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005909 break; // reached end of structure.
5910
5911 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5912 // We expand the bases without their virtual bases since those are going
5913 // in the initial structure. Note that this differs from gcc which
5914 // expands virtual bases each time one is encountered in the hierarchy,
5915 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005916 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5917 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005918 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005919#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005920 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005921#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005922 } else {
5923 FieldDecl *field = cast<FieldDecl>(dcl);
5924 if (FD) {
5925 S += '"';
5926 S += field->getNameAsString();
5927 S += '"';
5928 }
5929
5930 if (field->isBitField()) {
5931 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005932#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005933 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005934#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005935 } else {
5936 QualType qt = field->getType();
5937 getLegacyIntegralTypeEncoding(qt);
5938 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5939 /*OutermostType*/false,
5940 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005941 /*StructField*/true,
5942 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005943#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005944 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005945#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005946 }
5947 }
5948 }
5949}
5950
Mike Stump11289f42009-09-09 15:08:12 +00005951void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005952 std::string& S) const {
5953 if (QT & Decl::OBJC_TQ_In)
5954 S += 'n';
5955 if (QT & Decl::OBJC_TQ_Inout)
5956 S += 'N';
5957 if (QT & Decl::OBJC_TQ_Out)
5958 S += 'o';
5959 if (QT & Decl::OBJC_TQ_Bycopy)
5960 S += 'O';
5961 if (QT & Decl::OBJC_TQ_Byref)
5962 S += 'R';
5963 if (QT & Decl::OBJC_TQ_Oneway)
5964 S += 'V';
5965}
5966
Douglas Gregor3ea72692011-08-12 05:46:01 +00005967TypedefDecl *ASTContext::getObjCIdDecl() const {
5968 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00005969 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00005970 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005971 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005972 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005973 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005974}
5975
Douglas Gregor52e02802011-08-12 06:17:30 +00005976TypedefDecl *ASTContext::getObjCSelDecl() const {
5977 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005978 QualType T = getPointerType(ObjCBuiltinSelTy);
5979 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005980 }
5981 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005982}
5983
Douglas Gregor0a586182011-08-12 05:59:41 +00005984TypedefDecl *ASTContext::getObjCClassDecl() const {
5985 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00005986 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00005987 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005988 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005989 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005990 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005991}
5992
Douglas Gregord53ae832012-01-17 18:09:05 +00005993ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5994 if (!ObjCProtocolClassDecl) {
5995 ObjCProtocolClassDecl
5996 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5997 SourceLocation(),
5998 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00005999 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006000 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006001 SourceLocation(), true);
6002 }
6003
6004 return ObjCProtocolClassDecl;
6005}
6006
Meador Inge5d3fb222012-06-16 03:34:49 +00006007//===----------------------------------------------------------------------===//
6008// __builtin_va_list Construction Functions
6009//===----------------------------------------------------------------------===//
6010
6011static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6012 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006013 QualType T = Context->getPointerType(Context->CharTy);
6014 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006015}
6016
6017static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6018 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006019 QualType T = Context->getPointerType(Context->VoidTy);
6020 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006021}
6022
Tim Northover9bb857a2013-01-31 12:13:10 +00006023static TypedefDecl *
6024CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006025 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006026 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006027 if (Context->getLangOpts().CPlusPlus) {
6028 // namespace std { struct __va_list {
6029 NamespaceDecl *NS;
6030 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6031 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006032 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006033 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006034 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006035 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006036 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006037 }
6038
6039 VaListTagDecl->startDefinition();
6040
6041 const size_t NumFields = 5;
6042 QualType FieldTypes[NumFields];
6043 const char *FieldNames[NumFields];
6044
6045 // void *__stack;
6046 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6047 FieldNames[0] = "__stack";
6048
6049 // void *__gr_top;
6050 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6051 FieldNames[1] = "__gr_top";
6052
6053 // void *__vr_top;
6054 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6055 FieldNames[2] = "__vr_top";
6056
6057 // int __gr_offs;
6058 FieldTypes[3] = Context->IntTy;
6059 FieldNames[3] = "__gr_offs";
6060
6061 // int __vr_offs;
6062 FieldTypes[4] = Context->IntTy;
6063 FieldNames[4] = "__vr_offs";
6064
6065 // Create fields
6066 for (unsigned i = 0; i < NumFields; ++i) {
6067 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6068 VaListTagDecl,
6069 SourceLocation(),
6070 SourceLocation(),
6071 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006072 FieldTypes[i], /*TInfo=*/nullptr,
6073 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006074 /*Mutable=*/false,
6075 ICIS_NoInit);
6076 Field->setAccess(AS_public);
6077 VaListTagDecl->addDecl(Field);
6078 }
6079 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006080 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006081 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006082
6083 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006084 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006085}
6086
Meador Inge5d3fb222012-06-16 03:34:49 +00006087static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6088 // typedef struct __va_list_tag {
6089 RecordDecl *VaListTagDecl;
6090
Alp Toker2dea15b2013-12-17 01:22:38 +00006091 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006092 VaListTagDecl->startDefinition();
6093
6094 const size_t NumFields = 5;
6095 QualType FieldTypes[NumFields];
6096 const char *FieldNames[NumFields];
6097
6098 // unsigned char gpr;
6099 FieldTypes[0] = Context->UnsignedCharTy;
6100 FieldNames[0] = "gpr";
6101
6102 // unsigned char fpr;
6103 FieldTypes[1] = Context->UnsignedCharTy;
6104 FieldNames[1] = "fpr";
6105
6106 // unsigned short reserved;
6107 FieldTypes[2] = Context->UnsignedShortTy;
6108 FieldNames[2] = "reserved";
6109
6110 // void* overflow_arg_area;
6111 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6112 FieldNames[3] = "overflow_arg_area";
6113
6114 // void* reg_save_area;
6115 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6116 FieldNames[4] = "reg_save_area";
6117
6118 // Create fields
6119 for (unsigned i = 0; i < NumFields; ++i) {
6120 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6121 SourceLocation(),
6122 SourceLocation(),
6123 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006124 FieldTypes[i], /*TInfo=*/nullptr,
6125 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006126 /*Mutable=*/false,
6127 ICIS_NoInit);
6128 Field->setAccess(AS_public);
6129 VaListTagDecl->addDecl(Field);
6130 }
6131 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006132 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006133 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6134
6135 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006136 TypedefDecl *VaListTagTypedefDecl =
6137 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6138
Meador Inge5d3fb222012-06-16 03:34:49 +00006139 QualType VaListTagTypedefType =
6140 Context->getTypedefType(VaListTagTypedefDecl);
6141
6142 // typedef __va_list_tag __builtin_va_list[1];
6143 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6144 QualType VaListTagArrayType
6145 = Context->getConstantArrayType(VaListTagTypedefType,
6146 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006147 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006148}
6149
6150static TypedefDecl *
6151CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006152 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006153 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006154 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006155 VaListTagDecl->startDefinition();
6156
6157 const size_t NumFields = 4;
6158 QualType FieldTypes[NumFields];
6159 const char *FieldNames[NumFields];
6160
6161 // unsigned gp_offset;
6162 FieldTypes[0] = Context->UnsignedIntTy;
6163 FieldNames[0] = "gp_offset";
6164
6165 // unsigned fp_offset;
6166 FieldTypes[1] = Context->UnsignedIntTy;
6167 FieldNames[1] = "fp_offset";
6168
6169 // void* overflow_arg_area;
6170 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6171 FieldNames[2] = "overflow_arg_area";
6172
6173 // void* reg_save_area;
6174 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6175 FieldNames[3] = "reg_save_area";
6176
6177 // Create fields
6178 for (unsigned i = 0; i < NumFields; ++i) {
6179 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6180 VaListTagDecl,
6181 SourceLocation(),
6182 SourceLocation(),
6183 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006184 FieldTypes[i], /*TInfo=*/nullptr,
6185 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006186 /*Mutable=*/false,
6187 ICIS_NoInit);
6188 Field->setAccess(AS_public);
6189 VaListTagDecl->addDecl(Field);
6190 }
6191 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006192 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006193 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6194
Richard Smith9b88a4c2015-07-27 05:40:23 +00006195 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006196
Richard Smith9b88a4c2015-07-27 05:40:23 +00006197 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006198 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006199 QualType VaListTagArrayType =
6200 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006201 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006202}
6203
6204static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6205 // typedef int __builtin_va_list[4];
6206 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6207 QualType IntArrayType
6208 = Context->getConstantArrayType(Context->IntTy,
6209 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006210 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006211}
6212
Logan Chien57086ce2012-10-10 06:56:20 +00006213static TypedefDecl *
6214CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006215 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006216 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006217 if (Context->getLangOpts().CPlusPlus) {
6218 // namespace std { struct __va_list {
6219 NamespaceDecl *NS;
6220 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6221 Context->getTranslationUnitDecl(),
6222 /*Inline*/false, SourceLocation(),
6223 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006224 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006225 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006226 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006227 }
6228
6229 VaListDecl->startDefinition();
6230
6231 // void * __ap;
6232 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6233 VaListDecl,
6234 SourceLocation(),
6235 SourceLocation(),
6236 &Context->Idents.get("__ap"),
6237 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006238 /*TInfo=*/nullptr,
6239 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006240 /*Mutable=*/false,
6241 ICIS_NoInit);
6242 Field->setAccess(AS_public);
6243 VaListDecl->addDecl(Field);
6244
6245 // };
6246 VaListDecl->completeDefinition();
6247
6248 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006249 QualType T = Context->getRecordType(VaListDecl);
6250 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006251}
6252
Ulrich Weigand47445072013-05-06 16:26:41 +00006253static TypedefDecl *
6254CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006255 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006256 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006257 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006258 VaListTagDecl->startDefinition();
6259
6260 const size_t NumFields = 4;
6261 QualType FieldTypes[NumFields];
6262 const char *FieldNames[NumFields];
6263
6264 // long __gpr;
6265 FieldTypes[0] = Context->LongTy;
6266 FieldNames[0] = "__gpr";
6267
6268 // long __fpr;
6269 FieldTypes[1] = Context->LongTy;
6270 FieldNames[1] = "__fpr";
6271
6272 // void *__overflow_arg_area;
6273 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6274 FieldNames[2] = "__overflow_arg_area";
6275
6276 // void *__reg_save_area;
6277 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6278 FieldNames[3] = "__reg_save_area";
6279
6280 // Create fields
6281 for (unsigned i = 0; i < NumFields; ++i) {
6282 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6283 VaListTagDecl,
6284 SourceLocation(),
6285 SourceLocation(),
6286 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006287 FieldTypes[i], /*TInfo=*/nullptr,
6288 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006289 /*Mutable=*/false,
6290 ICIS_NoInit);
6291 Field->setAccess(AS_public);
6292 VaListTagDecl->addDecl(Field);
6293 }
6294 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006295 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006296 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006297
Richard Smith9b88a4c2015-07-27 05:40:23 +00006298 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006299
6300 // typedef __va_list_tag __builtin_va_list[1];
6301 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006302 QualType VaListTagArrayType =
6303 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006304
Alp Toker56b5cc92013-12-15 10:36:26 +00006305 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006306}
6307
Meador Inge5d3fb222012-06-16 03:34:49 +00006308static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6309 TargetInfo::BuiltinVaListKind Kind) {
6310 switch (Kind) {
6311 case TargetInfo::CharPtrBuiltinVaList:
6312 return CreateCharPtrBuiltinVaListDecl(Context);
6313 case TargetInfo::VoidPtrBuiltinVaList:
6314 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006315 case TargetInfo::AArch64ABIBuiltinVaList:
6316 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006317 case TargetInfo::PowerABIBuiltinVaList:
6318 return CreatePowerABIBuiltinVaListDecl(Context);
6319 case TargetInfo::X86_64ABIBuiltinVaList:
6320 return CreateX86_64ABIBuiltinVaListDecl(Context);
6321 case TargetInfo::PNaClABIBuiltinVaList:
6322 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006323 case TargetInfo::AAPCSABIBuiltinVaList:
6324 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006325 case TargetInfo::SystemZBuiltinVaList:
6326 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006327 }
6328
6329 llvm_unreachable("Unhandled __builtin_va_list type kind");
6330}
6331
6332TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006333 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006334 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006335 assert(BuiltinVaListDecl->isImplicit());
6336 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006337
6338 return BuiltinVaListDecl;
6339}
6340
Richard Smith9b88a4c2015-07-27 05:40:23 +00006341Decl *ASTContext::getVaListTagDecl() const {
6342 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006343 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006344 if (!VaListTagDecl)
6345 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006346
Richard Smith9b88a4c2015-07-27 05:40:23 +00006347 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006348}
6349
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006350void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006351 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006352 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006353
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006354 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006355}
6356
John McCalld28ae272009-12-02 08:04:21 +00006357/// \brief Retrieve the template name that corresponds to a non-empty
6358/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006359TemplateName
6360ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6361 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006362 unsigned size = End - Begin;
6363 assert(size > 1 && "set is not overloaded!");
6364
6365 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6366 size * sizeof(FunctionTemplateDecl*));
6367 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6368
6369 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006370 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006371 NamedDecl *D = *I;
6372 assert(isa<FunctionTemplateDecl>(D) ||
6373 (isa<UsingShadowDecl>(D) &&
6374 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6375 *Storage++ = D;
6376 }
6377
6378 return TemplateName(OT);
6379}
6380
Douglas Gregordc572a32009-03-30 22:58:21 +00006381/// \brief Retrieve the template name that represents a qualified
6382/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006383TemplateName
6384ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6385 bool TemplateKeyword,
6386 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006387 assert(NNS && "Missing nested-name-specifier in qualified template name");
6388
Douglas Gregorc42075a2010-02-04 18:10:26 +00006389 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006390 llvm::FoldingSetNodeID ID;
6391 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6392
Craig Topper36250ad2014-05-12 05:36:57 +00006393 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006394 QualifiedTemplateName *QTN =
6395 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6396 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006397 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6398 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006399 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6400 }
6401
6402 return TemplateName(QTN);
6403}
6404
6405/// \brief Retrieve the template name that represents a dependent
6406/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006407TemplateName
6408ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6409 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006410 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006411 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006412
6413 llvm::FoldingSetNodeID ID;
6414 DependentTemplateName::Profile(ID, NNS, Name);
6415
Craig Topper36250ad2014-05-12 05:36:57 +00006416 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006417 DependentTemplateName *QTN =
6418 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6419
6420 if (QTN)
6421 return TemplateName(QTN);
6422
6423 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6424 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006425 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6426 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006427 } else {
6428 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006429 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6430 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006431 DependentTemplateName *CheckQTN =
6432 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6433 assert(!CheckQTN && "Dependent type name canonicalization broken");
6434 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006435 }
6436
6437 DependentTemplateNames.InsertNode(QTN, InsertPos);
6438 return TemplateName(QTN);
6439}
6440
Douglas Gregor71395fa2009-11-04 00:56:37 +00006441/// \brief Retrieve the template name that represents a dependent
6442/// template name such as \c MetaFun::template operator+.
6443TemplateName
6444ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006445 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006446 assert((!NNS || NNS->isDependent()) &&
6447 "Nested name specifier must be dependent");
6448
6449 llvm::FoldingSetNodeID ID;
6450 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006451
6452 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006453 DependentTemplateName *QTN
6454 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006455
6456 if (QTN)
6457 return TemplateName(QTN);
6458
6459 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6460 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006461 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6462 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006463 } else {
6464 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006465 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6466 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006467
6468 DependentTemplateName *CheckQTN
6469 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6470 assert(!CheckQTN && "Dependent template name canonicalization broken");
6471 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006472 }
6473
6474 DependentTemplateNames.InsertNode(QTN, InsertPos);
6475 return TemplateName(QTN);
6476}
6477
Douglas Gregor5590be02011-01-15 06:45:20 +00006478TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006479ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6480 TemplateName replacement) const {
6481 llvm::FoldingSetNodeID ID;
6482 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006483
6484 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006485 SubstTemplateTemplateParmStorage *subst
6486 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6487
6488 if (!subst) {
6489 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6490 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6491 }
6492
6493 return TemplateName(subst);
6494}
6495
6496TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006497ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6498 const TemplateArgument &ArgPack) const {
6499 ASTContext &Self = const_cast<ASTContext &>(*this);
6500 llvm::FoldingSetNodeID ID;
6501 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006502
6503 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006504 SubstTemplateTemplateParmPackStorage *Subst
6505 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6506
6507 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006508 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006509 ArgPack.pack_size(),
6510 ArgPack.pack_begin());
6511 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6512 }
6513
6514 return TemplateName(Subst);
6515}
6516
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006517/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006518/// TargetInfo, produce the corresponding type. The unsigned @p Type
6519/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006520CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006521 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006522 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006523 case TargetInfo::SignedChar: return SignedCharTy;
6524 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006525 case TargetInfo::SignedShort: return ShortTy;
6526 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6527 case TargetInfo::SignedInt: return IntTy;
6528 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6529 case TargetInfo::SignedLong: return LongTy;
6530 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6531 case TargetInfo::SignedLongLong: return LongLongTy;
6532 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6533 }
6534
David Blaikie83d382b2011-09-23 05:06:16 +00006535 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006536}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006537
6538//===----------------------------------------------------------------------===//
6539// Type Predicates.
6540//===----------------------------------------------------------------------===//
6541
Fariborz Jahanian96207692009-02-18 21:49:28 +00006542/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6543/// garbage collection attribute.
6544///
John McCall553d45a2011-01-12 00:34:59 +00006545Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006546 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006547 return Qualifiers::GCNone;
6548
David Blaikiebbafb8a2012-03-11 07:00:24 +00006549 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006550 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6551
6552 // Default behaviour under objective-C's gc is for ObjC pointers
6553 // (or pointers to them) be treated as though they were declared
6554 // as __strong.
6555 if (GCAttrs == Qualifiers::GCNone) {
6556 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6557 return Qualifiers::Strong;
6558 else if (Ty->isPointerType())
6559 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6560 } else {
6561 // It's not valid to set GC attributes on anything that isn't a
6562 // pointer.
6563#ifndef NDEBUG
6564 QualType CT = Ty->getCanonicalTypeInternal();
6565 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6566 CT = AT->getElementType();
6567 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6568#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006569 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006570 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006571}
6572
Chris Lattner49af6a42008-04-07 06:51:04 +00006573//===----------------------------------------------------------------------===//
6574// Type Compatibility Testing
6575//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006576
Mike Stump11289f42009-09-09 15:08:12 +00006577/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006578/// compatible.
6579static bool areCompatVectorTypes(const VectorType *LHS,
6580 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006581 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006582 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006583 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006584}
6585
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006586bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6587 QualType SecondVec) {
6588 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6589 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6590
6591 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6592 return true;
6593
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006594 // Treat Neon vector types and most AltiVec vector types as if they are the
6595 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006596 const VectorType *First = FirstVec->getAs<VectorType>();
6597 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006598 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006599 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006600 First->getVectorKind() != VectorType::AltiVecPixel &&
6601 First->getVectorKind() != VectorType::AltiVecBool &&
6602 Second->getVectorKind() != VectorType::AltiVecPixel &&
6603 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006604 return true;
6605
6606 return false;
6607}
6608
Steve Naroff8e6aee52009-07-23 01:01:38 +00006609//===----------------------------------------------------------------------===//
6610// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6611//===----------------------------------------------------------------------===//
6612
6613/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6614/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006615bool
6616ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6617 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006618 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006619 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006620 for (auto *PI : rProto->protocols())
6621 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006622 return true;
6623 return false;
6624}
6625
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006626/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6627/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006628bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6629 QualType rhs) {
6630 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6631 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6632 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6633
Aaron Ballman83731462014-03-17 16:14:00 +00006634 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006635 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006636 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006637 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6638 match = true;
6639 break;
6640 }
6641 }
6642 if (!match)
6643 return false;
6644 }
6645 return true;
6646}
6647
Steve Naroff8e6aee52009-07-23 01:01:38 +00006648/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6649/// ObjCQualifiedIDType.
6650bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6651 bool compare) {
6652 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006653 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006654 lhs->isObjCIdType() || lhs->isObjCClassType())
6655 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006656 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006657 rhs->isObjCIdType() || rhs->isObjCClassType())
6658 return true;
6659
6660 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006661 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006662
Steve Naroff8e6aee52009-07-23 01:01:38 +00006663 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006664
Steve Naroff8e6aee52009-07-23 01:01:38 +00006665 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006666 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006667 // make sure we check the class hierarchy.
6668 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006669 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006670 // when comparing an id<P> on lhs with a static type on rhs,
6671 // see if static class implements all of id's protocols, directly or
6672 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006673 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006674 return false;
6675 }
6676 }
6677 // If there are no qualifiers and no interface, we have an 'id'.
6678 return true;
6679 }
Mike Stump11289f42009-09-09 15:08:12 +00006680 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006681 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006682 bool match = false;
6683
6684 // when comparing an id<P> on lhs with a static type on rhs,
6685 // see if static class implements all of id's protocols, directly or
6686 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006687 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006688 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6689 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6690 match = true;
6691 break;
6692 }
6693 }
Mike Stump11289f42009-09-09 15:08:12 +00006694 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006695 // make sure we check the class hierarchy.
6696 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006697 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006698 // when comparing an id<P> on lhs with a static type on rhs,
6699 // see if static class implements all of id's protocols, directly or
6700 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006701 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006702 match = true;
6703 break;
6704 }
6705 }
6706 }
6707 if (!match)
6708 return false;
6709 }
Mike Stump11289f42009-09-09 15:08:12 +00006710
Steve Naroff8e6aee52009-07-23 01:01:38 +00006711 return true;
6712 }
Mike Stump11289f42009-09-09 15:08:12 +00006713
Steve Naroff8e6aee52009-07-23 01:01:38 +00006714 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6715 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6716
Mike Stump11289f42009-09-09 15:08:12 +00006717 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006718 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006719 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006720 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006721 bool match = false;
6722
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006723 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006724 // see if static class implements all of id's protocols, directly or
6725 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006726 // First, lhs protocols in the qualifier list must be found, direct
6727 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006728 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006729 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6730 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6731 match = true;
6732 break;
6733 }
6734 }
6735 if (!match)
6736 return false;
6737 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006738
6739 // Static class's protocols, or its super class or category protocols
6740 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6741 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6742 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6743 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6744 // This is rather dubious but matches gcc's behavior. If lhs has
6745 // no type qualifier and its class has no static protocol(s)
6746 // assume that it is mismatch.
6747 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6748 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006749 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006750 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006751 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006752 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6753 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6754 match = true;
6755 break;
6756 }
6757 }
6758 if (!match)
6759 return false;
6760 }
6761 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006762 return true;
6763 }
6764 return false;
6765}
6766
Eli Friedman47f77112008-08-22 00:56:42 +00006767/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006768/// compatible for assignment from RHS to LHS. This handles validation of any
6769/// protocol qualifiers on the LHS or RHS.
6770///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006771bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6772 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006773 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6774 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6775
Steve Naroff1329fa02009-07-15 18:40:39 +00006776 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006777 if (LHS->isObjCUnqualifiedIdOrClass() ||
6778 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006779 return true;
6780
Douglas Gregorab209d82015-07-07 03:58:42 +00006781 // Function object that propagates a successful result or handles
6782 // __kindof types.
6783 auto finish = [&](bool succeeded) -> bool {
6784 if (succeeded)
6785 return true;
6786
6787 if (!RHS->isKindOfType())
6788 return false;
6789
6790 // Strip off __kindof and protocol qualifiers, then check whether
6791 // we can assign the other way.
6792 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6793 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6794 };
6795
6796 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6797 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6798 QualType(RHSOPT,0),
6799 false));
6800 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006801
Douglas Gregorab209d82015-07-07 03:58:42 +00006802 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6803 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6804 QualType(RHSOPT,0)));
6805 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006806
John McCall8b07ec22010-05-15 11:32:37 +00006807 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006808 if (LHS->getInterface() && RHS->getInterface()) {
6809 return finish(canAssignObjCInterfaces(LHS, RHS));
6810 }
Mike Stump11289f42009-09-09 15:08:12 +00006811
Steve Naroff8e6aee52009-07-23 01:01:38 +00006812 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006813}
6814
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006815/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006816/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006817/// arguments in block literals. When passed as arguments, passing 'A*' where
6818/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6819/// not OK. For the return type, the opposite is not OK.
6820bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6821 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006822 const ObjCObjectPointerType *RHSOPT,
6823 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006824
6825 // Function object that propagates a successful result or handles
6826 // __kindof types.
6827 auto finish = [&](bool succeeded) -> bool {
6828 if (succeeded)
6829 return true;
6830
6831 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6832 if (!Expected->isKindOfType())
6833 return false;
6834
6835 // Strip off __kindof and protocol qualifiers, then check whether
6836 // we can assign the other way.
6837 return canAssignObjCInterfacesInBlockPointer(
6838 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6839 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6840 BlockReturnType);
6841 };
6842
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006843 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006844 return true;
6845
6846 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006847 return finish(RHSOPT->isObjCBuiltinType() ||
6848 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006849 }
6850
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006851 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006852 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6853 QualType(RHSOPT,0),
6854 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006855
6856 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6857 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6858 if (LHS && RHS) { // We have 2 user-defined types.
6859 if (LHS != RHS) {
6860 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006861 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006862 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006863 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006864 }
6865 else
6866 return true;
6867 }
6868 return false;
6869}
6870
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006871/// Comparison routine for Objective-C protocols to be used with
6872/// llvm::array_pod_sort.
6873static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6874 ObjCProtocolDecl * const *rhs) {
6875 return (*lhs)->getName().compare((*rhs)->getName());
6876
6877}
6878
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006879/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006880/// of protocols inherited from two distinct objective-c pointer objects with
6881/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006882/// It is used to build composite qualifier list of the composite type of
6883/// the conditional expression involving two objective-c pointer objects.
6884static
6885void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006886 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006887 const ObjCObjectPointerType *LHSOPT,
6888 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006889 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006890
John McCall8b07ec22010-05-15 11:32:37 +00006891 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6892 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6893 assert(LHS->getInterface() && "LHS must have an interface base");
6894 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006895
6896 // Add all of the protocols for the LHS.
6897 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6898
6899 // Start with the protocol qualifiers.
6900 for (auto proto : LHS->quals()) {
6901 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006902 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006903
6904 // Also add the protocols associated with the LHS interface.
6905 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6906
6907 // Add all of the protocls for the RHS.
6908 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6909
6910 // Start with the protocol qualifiers.
6911 for (auto proto : RHS->quals()) {
6912 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006913 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006914
6915 // Also add the protocols associated with the RHS interface.
6916 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6917
6918 // Compute the intersection of the collected protocol sets.
6919 for (auto proto : LHSProtocolSet) {
6920 if (RHSProtocolSet.count(proto))
6921 IntersectionSet.push_back(proto);
6922 }
6923
6924 // Compute the set of protocols that is implied by either the common type or
6925 // the protocols within the intersection.
6926 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6927 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6928
6929 // Remove any implied protocols from the list of inherited protocols.
6930 if (!ImpliedProtocols.empty()) {
6931 IntersectionSet.erase(
6932 std::remove_if(IntersectionSet.begin(),
6933 IntersectionSet.end(),
6934 [&](ObjCProtocolDecl *proto) -> bool {
6935 return ImpliedProtocols.count(proto) > 0;
6936 }),
6937 IntersectionSet.end());
6938 }
6939
6940 // Sort the remaining protocols by name.
6941 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
6942 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006943}
6944
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006945/// Determine whether the first type is a subtype of the second.
6946static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
6947 QualType rhs) {
6948 // Common case: two object pointers.
6949 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
6950 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6951 if (lhsOPT && rhsOPT)
6952 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
6953
6954 // Two block pointers.
6955 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
6956 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
6957 if (lhsBlock && rhsBlock)
6958 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
6959
6960 // If either is an unqualified 'id' and the other is a block, it's
6961 // acceptable.
6962 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
6963 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
6964 return true;
6965
6966 return false;
6967}
6968
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006969// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006970static bool sameObjCTypeArgs(ASTContext &ctx,
6971 const ObjCInterfaceDecl *iface,
6972 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00006973 ArrayRef<QualType> rhsArgs,
6974 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006975 if (lhsArgs.size() != rhsArgs.size())
6976 return false;
6977
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006978 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006979 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006980 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
6981 continue;
6982
6983 switch (typeParams->begin()[i]->getVariance()) {
6984 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00006985 if (!stripKindOf ||
6986 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
6987 rhsArgs[i].stripObjCKindOfType(ctx))) {
6988 return false;
6989 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006990 break;
6991
6992 case ObjCTypeParamVariance::Covariant:
6993 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
6994 return false;
6995 break;
6996
6997 case ObjCTypeParamVariance::Contravariant:
6998 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
6999 return false;
7000 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007001 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007002 }
7003
7004 return true;
7005}
7006
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007007QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007008 const ObjCObjectPointerType *Lptr,
7009 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007010 const ObjCObjectType *LHS = Lptr->getObjectType();
7011 const ObjCObjectType *RHS = Rptr->getObjectType();
7012 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7013 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007014
7015 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007016 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007017
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007018 // Follow the left-hand side up the class hierarchy until we either hit a
7019 // root or find the RHS. Record the ancestors in case we don't find it.
7020 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7021 LHSAncestors;
7022 while (true) {
7023 // Record this ancestor. We'll need this if the common type isn't in the
7024 // path from the LHS to the root.
7025 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007026
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007027 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7028 // Get the type arguments.
7029 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7030 bool anyChanges = false;
7031 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7032 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007033 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7034 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007035 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007036 return QualType();
7037 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7038 // If only one has type arguments, the result will not have type
7039 // arguments.
7040 LHSTypeArgs = { };
7041 anyChanges = true;
7042 }
7043
7044 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007045 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007046 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7047 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007048 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007049 anyChanges = true;
7050
7051 // If anything in the LHS will have changed, build a new result type.
7052 if (anyChanges) {
7053 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007054 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7055 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007056 return getObjCObjectPointerType(Result);
7057 }
7058
7059 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007060 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007061
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007062 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007063 QualType LHSSuperType = LHS->getSuperClassType();
7064 if (LHSSuperType.isNull())
7065 break;
7066
7067 LHS = LHSSuperType->castAs<ObjCObjectType>();
7068 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007069
7070 // We didn't find anything by following the LHS to its root; now check
7071 // the RHS against the cached set of ancestors.
7072 while (true) {
7073 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7074 if (KnownLHS != LHSAncestors.end()) {
7075 LHS = KnownLHS->second;
7076
7077 // Get the type arguments.
7078 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7079 bool anyChanges = false;
7080 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7081 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007082 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7083 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007084 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007085 return QualType();
7086 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7087 // If only one has type arguments, the result will not have type
7088 // arguments.
7089 RHSTypeArgs = { };
7090 anyChanges = true;
7091 }
7092
7093 // Compute the intersection of protocols.
7094 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7095 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7096 Protocols);
7097 if (!Protocols.empty())
7098 anyChanges = true;
7099
7100 if (anyChanges) {
7101 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007102 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7103 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007104 return getObjCObjectPointerType(Result);
7105 }
7106
7107 return getObjCObjectPointerType(QualType(RHS, 0));
7108 }
7109
7110 // Find the superclass of the RHS.
7111 QualType RHSSuperType = RHS->getSuperClassType();
7112 if (RHSSuperType.isNull())
7113 break;
7114
7115 RHS = RHSSuperType->castAs<ObjCObjectType>();
7116 }
7117
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007118 return QualType();
7119}
7120
John McCall8b07ec22010-05-15 11:32:37 +00007121bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7122 const ObjCObjectType *RHS) {
7123 assert(LHS->getInterface() && "LHS is not an interface type");
7124 assert(RHS->getInterface() && "RHS is not an interface type");
7125
Chris Lattner49af6a42008-04-07 06:51:04 +00007126 // Verify that the base decls are compatible: the RHS must be a subclass of
7127 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007128 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7129 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7130 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007131 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007132
Douglas Gregore83b9562015-07-07 03:57:53 +00007133 // If the LHS has protocol qualifiers, determine whether all of them are
7134 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7135 // LHS).
7136 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007137 // OK if conversion of LHS to SuperClass results in narrowing of types
7138 // ; i.e., SuperClass may implement at least one of the protocols
7139 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7140 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7141 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7142 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7143 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7144 // qualifiers.
7145 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007146 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007147 // If there is no protocols associated with RHS, it is not a match.
7148 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007149 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007150
7151 for (const auto *LHSProto : LHS->quals()) {
7152 bool SuperImplementsProtocol = false;
7153 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7154 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7155 SuperImplementsProtocol = true;
7156 break;
7157 }
7158 if (!SuperImplementsProtocol)
7159 return false;
7160 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007161 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007162
7163 // If the LHS is specialized, we may need to check type arguments.
7164 if (LHS->isSpecialized()) {
7165 // Follow the superclass chain until we've matched the LHS class in the
7166 // hierarchy. This substitutes type arguments through.
7167 const ObjCObjectType *RHSSuper = RHS;
7168 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7169 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7170
7171 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007172 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007173 !sameObjCTypeArgs(*this, LHS->getInterface(),
7174 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007175 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007176 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007177 }
7178 }
7179
7180 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007181}
7182
Steve Naroffb7605152009-02-12 17:52:19 +00007183bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7184 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007185 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7186 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007187
Steve Naroff7cae42b2009-07-10 23:34:53 +00007188 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007189 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007190
7191 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7192 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007193}
7194
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007195bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7196 return canAssignObjCInterfaces(
7197 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7198 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7199}
7200
Mike Stump11289f42009-09-09 15:08:12 +00007201/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007202/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007203/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007204/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007205bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7206 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007207 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007208 return hasSameType(LHS, RHS);
7209
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007210 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007211}
7212
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007213bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007214 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007215}
7216
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007217bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7218 return !mergeTypes(LHS, RHS, true).isNull();
7219}
7220
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007221/// mergeTransparentUnionType - if T is a transparent union type and a member
7222/// of T is compatible with SubType, return the merged type, else return
7223/// QualType()
7224QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7225 bool OfBlockPointer,
7226 bool Unqualified) {
7227 if (const RecordType *UT = T->getAsUnionType()) {
7228 RecordDecl *UD = UT->getDecl();
7229 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007230 for (const auto *I : UD->fields()) {
7231 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007232 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7233 if (!MT.isNull())
7234 return MT;
7235 }
7236 }
7237 }
7238
7239 return QualType();
7240}
7241
Alp Toker9cacbab2014-01-20 20:26:09 +00007242/// mergeFunctionParameterTypes - merge two types which appear as function
7243/// parameter types
7244QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7245 bool OfBlockPointer,
7246 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007247 // GNU extension: two types are compatible if they appear as a function
7248 // argument, one of the types is a transparent union type and the other
7249 // type is compatible with a union member
7250 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7251 Unqualified);
7252 if (!lmerge.isNull())
7253 return lmerge;
7254
7255 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7256 Unqualified);
7257 if (!rmerge.isNull())
7258 return rmerge;
7259
7260 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7261}
7262
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007263QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007264 bool OfBlockPointer,
7265 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007266 const FunctionType *lbase = lhs->getAs<FunctionType>();
7267 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007268 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7269 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007270 bool allLTypes = true;
7271 bool allRTypes = true;
7272
7273 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007274 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007275 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007276 QualType RHS = rbase->getReturnType();
7277 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007278 bool UnqualifiedResult = Unqualified;
7279 if (!UnqualifiedResult)
7280 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007281 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007282 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007283 else
Alp Toker314cc812014-01-25 16:55:45 +00007284 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007285 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007286 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007287
7288 if (Unqualified)
7289 retType = retType.getUnqualifiedType();
7290
Alp Toker314cc812014-01-25 16:55:45 +00007291 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7292 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007293 if (Unqualified) {
7294 LRetType = LRetType.getUnqualifiedType();
7295 RRetType = RRetType.getUnqualifiedType();
7296 }
7297
7298 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007299 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007300 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007301 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007302
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007303 // FIXME: double check this
7304 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7305 // rbase->getRegParmAttr() != 0 &&
7306 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007307 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7308 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007309
Douglas Gregor8c940862010-01-18 17:14:39 +00007310 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007311 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007312 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007313
John McCall8c6b56f2010-12-15 01:06:38 +00007314 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007315 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7316 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007317 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7318 return QualType();
7319
John McCall31168b02011-06-15 23:02:42 +00007320 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7321 return QualType();
7322
John McCall8c6b56f2010-12-15 01:06:38 +00007323 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7324 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007325
Rafael Espindola8778c282012-11-29 16:09:03 +00007326 if (lbaseInfo.getNoReturn() != NoReturn)
7327 allLTypes = false;
7328 if (rbaseInfo.getNoReturn() != NoReturn)
7329 allRTypes = false;
7330
John McCall31168b02011-06-15 23:02:42 +00007331 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007332
Eli Friedman47f77112008-08-22 00:56:42 +00007333 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007334 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7335 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007336 // Compatible functions must have the same number of parameters
7337 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007338 return QualType();
7339
7340 // Variadic and non-variadic functions aren't compatible
7341 if (lproto->isVariadic() != rproto->isVariadic())
7342 return QualType();
7343
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007344 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7345 return QualType();
7346
Fariborz Jahanian97676972011-09-28 21:52:05 +00007347 if (LangOpts.ObjCAutoRefCount &&
7348 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7349 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007350
7351 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007352 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007353 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7354 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7355 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7356 QualType paramType = mergeFunctionParameterTypes(
7357 lParamType, rParamType, OfBlockPointer, Unqualified);
7358 if (paramType.isNull())
7359 return QualType();
7360
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007361 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007362 paramType = paramType.getUnqualifiedType();
7363
7364 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007365 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007366 lParamType = lParamType.getUnqualifiedType();
7367 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007368 }
Alp Toker601b22c2014-01-21 23:35:24 +00007369
7370 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007371 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007372 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007373 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007374 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007375
Eli Friedman47f77112008-08-22 00:56:42 +00007376 if (allLTypes) return lhs;
7377 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007378
7379 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7380 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007381 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007382 }
7383
7384 if (lproto) allRTypes = false;
7385 if (rproto) allLTypes = false;
7386
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007387 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007388 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007389 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007390 if (proto->isVariadic()) return QualType();
7391 // Check that the types are compatible with the types that
7392 // would result from default argument promotions (C99 6.7.5.3p15).
7393 // The only types actually affected are promotable integer
7394 // types and floats, which would be passed as a different
7395 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007396 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7397 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007398
Eli Friedman448ce402012-08-30 00:44:15 +00007399 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007400 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007401 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7402 paramTy = Enum->getDecl()->getIntegerType();
7403 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007404 return QualType();
7405 }
Alp Toker601b22c2014-01-21 23:35:24 +00007406
7407 if (paramTy->isPromotableIntegerType() ||
7408 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007409 return QualType();
7410 }
7411
7412 if (allLTypes) return lhs;
7413 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007414
7415 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7416 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007417 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007418 }
7419
7420 if (allLTypes) return lhs;
7421 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007422 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007423}
7424
John McCall433c2e62013-03-21 00:10:07 +00007425/// Given that we have an enum type and a non-enum type, try to merge them.
7426static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7427 QualType other, bool isBlockReturnType) {
7428 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7429 // a signed integer type, or an unsigned integer type.
7430 // Compatibility is based on the underlying type, not the promotion
7431 // type.
7432 QualType underlyingType = ET->getDecl()->getIntegerType();
7433 if (underlyingType.isNull()) return QualType();
7434 if (Context.hasSameType(underlyingType, other))
7435 return other;
7436
7437 // In block return types, we're more permissive and accept any
7438 // integral type of the same size.
7439 if (isBlockReturnType && other->isIntegerType() &&
7440 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7441 return other;
7442
7443 return QualType();
7444}
7445
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007446QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007447 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007448 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007449 // C++ [expr]: If an expression initially has the type "reference to T", the
7450 // type is adjusted to "T" prior to any further analysis, the expression
7451 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007452 // expression is an lvalue unless the reference is an rvalue reference and
7453 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007454 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7455 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007456
7457 if (Unqualified) {
7458 LHS = LHS.getUnqualifiedType();
7459 RHS = RHS.getUnqualifiedType();
7460 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007461
Eli Friedman47f77112008-08-22 00:56:42 +00007462 QualType LHSCan = getCanonicalType(LHS),
7463 RHSCan = getCanonicalType(RHS);
7464
7465 // If two types are identical, they are compatible.
7466 if (LHSCan == RHSCan)
7467 return LHS;
7468
John McCall8ccfcb52009-09-24 19:53:00 +00007469 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007470 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7471 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007472 if (LQuals != RQuals) {
7473 // If any of these qualifiers are different, we have a type
7474 // mismatch.
7475 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007476 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7477 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007478 return QualType();
7479
7480 // Exactly one GC qualifier difference is allowed: __strong is
7481 // okay if the other type has no GC qualifier but is an Objective
7482 // C object pointer (i.e. implicitly strong by default). We fix
7483 // this by pretending that the unqualified type was actually
7484 // qualified __strong.
7485 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7486 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7487 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7488
7489 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7490 return QualType();
7491
7492 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7493 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7494 }
7495 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7496 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7497 }
Eli Friedman47f77112008-08-22 00:56:42 +00007498 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007499 }
7500
7501 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007502
Eli Friedmandcca6332009-06-01 01:22:52 +00007503 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7504 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007505
Chris Lattnerfd652912008-01-14 05:45:46 +00007506 // We want to consider the two function types to be the same for these
7507 // comparisons, just force one to the other.
7508 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7509 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007510
7511 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007512 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7513 LHSClass = Type::ConstantArray;
7514 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7515 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007516
John McCall8b07ec22010-05-15 11:32:37 +00007517 // ObjCInterfaces are just specialized ObjCObjects.
7518 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7519 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7520
Nate Begemance4d7fc2008-04-18 23:10:10 +00007521 // Canonicalize ExtVector -> Vector.
7522 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7523 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007524
Chris Lattner95554662008-04-07 05:43:21 +00007525 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007526 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007527 // Note that we only have special rules for turning block enum
7528 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007529 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007530 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007531 }
John McCall9dd450b2009-09-21 23:43:11 +00007532 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007533 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007534 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007535 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007536 if (OfBlockPointer && !BlockReturnType) {
7537 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7538 return LHS;
7539 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7540 return RHS;
7541 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007542
Eli Friedman47f77112008-08-22 00:56:42 +00007543 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007544 }
Eli Friedman47f77112008-08-22 00:56:42 +00007545
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007546 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007547 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007548#define TYPE(Class, Base)
7549#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007550#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007551#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7552#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7553#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007554 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007555
Richard Smith27d807c2013-04-30 13:56:41 +00007556 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007557 case Type::LValueReference:
7558 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007559 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007560 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007561
John McCall8b07ec22010-05-15 11:32:37 +00007562 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007563 case Type::IncompleteArray:
7564 case Type::VariableArray:
7565 case Type::FunctionProto:
7566 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007567 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007568
Chris Lattnerfd652912008-01-14 05:45:46 +00007569 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007570 {
7571 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007572 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7573 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007574 if (Unqualified) {
7575 LHSPointee = LHSPointee.getUnqualifiedType();
7576 RHSPointee = RHSPointee.getUnqualifiedType();
7577 }
7578 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7579 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007580 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007581 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007582 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007583 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007584 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007585 return getPointerType(ResultType);
7586 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007587 case Type::BlockPointer:
7588 {
7589 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007590 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7591 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007592 if (Unqualified) {
7593 LHSPointee = LHSPointee.getUnqualifiedType();
7594 RHSPointee = RHSPointee.getUnqualifiedType();
7595 }
7596 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7597 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007598 if (ResultType.isNull()) return QualType();
7599 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7600 return LHS;
7601 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7602 return RHS;
7603 return getBlockPointerType(ResultType);
7604 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007605 case Type::Atomic:
7606 {
7607 // Merge two pointer types, while trying to preserve typedef info
7608 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7609 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7610 if (Unqualified) {
7611 LHSValue = LHSValue.getUnqualifiedType();
7612 RHSValue = RHSValue.getUnqualifiedType();
7613 }
7614 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7615 Unqualified);
7616 if (ResultType.isNull()) return QualType();
7617 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7618 return LHS;
7619 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7620 return RHS;
7621 return getAtomicType(ResultType);
7622 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007623 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007624 {
7625 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7626 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7627 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7628 return QualType();
7629
7630 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7631 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007632 if (Unqualified) {
7633 LHSElem = LHSElem.getUnqualifiedType();
7634 RHSElem = RHSElem.getUnqualifiedType();
7635 }
7636
7637 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007638 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007639 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7640 return LHS;
7641 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7642 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007643 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7644 ArrayType::ArraySizeModifier(), 0);
7645 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7646 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007647 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7648 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007649 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7650 return LHS;
7651 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7652 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007653 if (LVAT) {
7654 // FIXME: This isn't correct! But tricky to implement because
7655 // the array's size has to be the size of LHS, but the type
7656 // has to be different.
7657 return LHS;
7658 }
7659 if (RVAT) {
7660 // FIXME: This isn't correct! But tricky to implement because
7661 // the array's size has to be the size of RHS, but the type
7662 // has to be different.
7663 return RHS;
7664 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007665 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7666 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007667 return getIncompleteArrayType(ResultType,
7668 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007669 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007670 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007671 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007672 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007673 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007674 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007675 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007676 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007677 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007678 case Type::Complex:
7679 // Distinct complex types are incompatible.
7680 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007681 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007682 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007683 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7684 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007685 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007686 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007687 case Type::ObjCObject: {
7688 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007689 // FIXME: This should be type compatibility, e.g. whether
7690 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007691 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7692 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7693 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007694 return LHS;
7695
Eli Friedman47f77112008-08-22 00:56:42 +00007696 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007697 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007698 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007699 if (OfBlockPointer) {
7700 if (canAssignObjCInterfacesInBlockPointer(
7701 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007702 RHS->getAs<ObjCObjectPointerType>(),
7703 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007704 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007705 return QualType();
7706 }
John McCall9dd450b2009-09-21 23:43:11 +00007707 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7708 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007709 return LHS;
7710
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007711 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007712 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007713 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007714
David Blaikie8a40f702012-01-17 06:56:22 +00007715 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007716}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007717
Fariborz Jahanian97676972011-09-28 21:52:05 +00007718bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7719 const FunctionProtoType *FromFunctionType,
7720 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007721 if (FromFunctionType->hasAnyConsumedParams() !=
7722 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007723 return false;
7724 FunctionProtoType::ExtProtoInfo FromEPI =
7725 FromFunctionType->getExtProtoInfo();
7726 FunctionProtoType::ExtProtoInfo ToEPI =
7727 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007728 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007729 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7730 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007731 return false;
7732 }
7733 return true;
7734}
7735
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007736/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7737/// 'RHS' attributes and returns the merged version; including for function
7738/// return types.
7739QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7740 QualType LHSCan = getCanonicalType(LHS),
7741 RHSCan = getCanonicalType(RHS);
7742 // If two types are identical, they are compatible.
7743 if (LHSCan == RHSCan)
7744 return LHS;
7745 if (RHSCan->isFunctionType()) {
7746 if (!LHSCan->isFunctionType())
7747 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007748 QualType OldReturnType =
7749 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007750 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007751 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007752 QualType ResReturnType =
7753 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7754 if (ResReturnType.isNull())
7755 return QualType();
7756 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7757 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7758 // In either case, use OldReturnType to build the new function type.
7759 const FunctionType *F = LHS->getAs<FunctionType>();
7760 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007761 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7762 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007763 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007764 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007765 return ResultType;
7766 }
7767 }
7768 return QualType();
7769 }
7770
7771 // If the qualifiers are different, the types can still be merged.
7772 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7773 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7774 if (LQuals != RQuals) {
7775 // If any of these qualifiers are different, we have a type mismatch.
7776 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7777 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7778 return QualType();
7779
7780 // Exactly one GC qualifier difference is allowed: __strong is
7781 // okay if the other type has no GC qualifier but is an Objective
7782 // C object pointer (i.e. implicitly strong by default). We fix
7783 // this by pretending that the unqualified type was actually
7784 // qualified __strong.
7785 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7786 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7787 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7788
7789 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7790 return QualType();
7791
7792 if (GC_L == Qualifiers::Strong)
7793 return LHS;
7794 if (GC_R == Qualifiers::Strong)
7795 return RHS;
7796 return QualType();
7797 }
7798
7799 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7800 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7801 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7802 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7803 if (ResQT == LHSBaseQT)
7804 return LHS;
7805 if (ResQT == RHSBaseQT)
7806 return RHS;
7807 }
7808 return QualType();
7809}
7810
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007811//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007812// Integer Predicates
7813//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007814
Jay Foad39c79802011-01-12 09:06:06 +00007815unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007816 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007817 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007818 if (T->isBooleanType())
7819 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007820 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007821 return (unsigned)getTypeSize(T);
7822}
7823
Abramo Bagnara13640492012-09-09 10:21:24 +00007824QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007825 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007826
7827 // Turn <4 x signed int> -> <4 x unsigned int>
7828 if (const VectorType *VTy = T->getAs<VectorType>())
7829 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007830 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007831
7832 // For enums, we return the unsigned version of the base type.
7833 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007834 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007835
7836 const BuiltinType *BTy = T->getAs<BuiltinType>();
7837 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007838 switch (BTy->getKind()) {
7839 case BuiltinType::Char_S:
7840 case BuiltinType::SChar:
7841 return UnsignedCharTy;
7842 case BuiltinType::Short:
7843 return UnsignedShortTy;
7844 case BuiltinType::Int:
7845 return UnsignedIntTy;
7846 case BuiltinType::Long:
7847 return UnsignedLongTy;
7848 case BuiltinType::LongLong:
7849 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007850 case BuiltinType::Int128:
7851 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007852 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007853 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007854 }
7855}
7856
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007857ASTMutationListener::~ASTMutationListener() { }
7858
Richard Smith1fa5d642013-05-11 05:45:24 +00007859void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7860 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007861
7862//===----------------------------------------------------------------------===//
7863// Builtin Type Computation
7864//===----------------------------------------------------------------------===//
7865
7866/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007867/// pointer over the consumed characters. This returns the resultant type. If
7868/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7869/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7870/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007871///
7872/// RequiresICE is filled in on return to indicate whether the value is required
7873/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007874static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007875 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007876 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007877 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007878 // Modifiers.
7879 int HowLong = 0;
7880 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007881 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007882
Chris Lattnerdc226c22010-10-01 22:42:38 +00007883 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007884 bool Done = false;
7885 while (!Done) {
7886 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007887 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007888 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007889 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007890 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007891 case 'S':
7892 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7893 assert(!Signed && "Can't use 'S' modifier multiple times!");
7894 Signed = true;
7895 break;
7896 case 'U':
7897 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007898 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007899 Unsigned = true;
7900 break;
7901 case 'L':
7902 assert(HowLong <= 2 && "Can't have LLLL modifier");
7903 ++HowLong;
7904 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007905 case 'W':
7906 // This modifier represents int64 type.
7907 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7908 switch (Context.getTargetInfo().getInt64Type()) {
7909 default:
7910 llvm_unreachable("Unexpected integer type");
7911 case TargetInfo::SignedLong:
7912 HowLong = 1;
7913 break;
7914 case TargetInfo::SignedLongLong:
7915 HowLong = 2;
7916 break;
7917 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007918 }
7919 }
7920
7921 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007922
Chris Lattnerecd79c62009-06-14 00:45:47 +00007923 // Read the base type.
7924 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007925 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007926 case 'v':
7927 assert(HowLong == 0 && !Signed && !Unsigned &&
7928 "Bad modifiers used with 'v'!");
7929 Type = Context.VoidTy;
7930 break;
Jack Carter24bef982013-08-15 15:16:57 +00007931 case 'h':
7932 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007933 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007934 Type = Context.HalfTy;
7935 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007936 case 'f':
7937 assert(HowLong == 0 && !Signed && !Unsigned &&
7938 "Bad modifiers used with 'f'!");
7939 Type = Context.FloatTy;
7940 break;
7941 case 'd':
7942 assert(HowLong < 2 && !Signed && !Unsigned &&
7943 "Bad modifiers used with 'd'!");
7944 if (HowLong)
7945 Type = Context.LongDoubleTy;
7946 else
7947 Type = Context.DoubleTy;
7948 break;
7949 case 's':
7950 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7951 if (Unsigned)
7952 Type = Context.UnsignedShortTy;
7953 else
7954 Type = Context.ShortTy;
7955 break;
7956 case 'i':
7957 if (HowLong == 3)
7958 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7959 else if (HowLong == 2)
7960 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7961 else if (HowLong == 1)
7962 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7963 else
7964 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7965 break;
7966 case 'c':
7967 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7968 if (Signed)
7969 Type = Context.SignedCharTy;
7970 else if (Unsigned)
7971 Type = Context.UnsignedCharTy;
7972 else
7973 Type = Context.CharTy;
7974 break;
7975 case 'b': // boolean
7976 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7977 Type = Context.BoolTy;
7978 break;
7979 case 'z': // size_t.
7980 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7981 Type = Context.getSizeType();
7982 break;
7983 case 'F':
7984 Type = Context.getCFConstantStringType();
7985 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007986 case 'G':
7987 Type = Context.getObjCIdType();
7988 break;
7989 case 'H':
7990 Type = Context.getObjCSelType();
7991 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007992 case 'M':
7993 Type = Context.getObjCSuperType();
7994 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007995 case 'a':
7996 Type = Context.getBuiltinVaListType();
7997 assert(!Type.isNull() && "builtin va list type not initialized!");
7998 break;
7999 case 'A':
8000 // This is a "reference" to a va_list; however, what exactly
8001 // this means depends on how va_list is defined. There are two
8002 // different kinds of va_list: ones passed by value, and ones
8003 // passed by reference. An example of a by-value va_list is
8004 // x86, where va_list is a char*. An example of by-ref va_list
8005 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8006 // we want this argument to be a char*&; for x86-64, we want
8007 // it to be a __va_list_tag*.
8008 Type = Context.getBuiltinVaListType();
8009 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008010 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008011 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008012 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008013 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008014 break;
8015 case 'V': {
8016 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008017 unsigned NumElements = strtoul(Str, &End, 10);
8018 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008019 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008020
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008021 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8022 RequiresICE, false);
8023 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008024
8025 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008026 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008027 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008028 break;
8029 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008030 case 'E': {
8031 char *End;
8032
8033 unsigned NumElements = strtoul(Str, &End, 10);
8034 assert(End != Str && "Missing vector size");
8035
8036 Str = End;
8037
8038 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8039 false);
8040 Type = Context.getExtVectorType(ElementType, NumElements);
8041 break;
8042 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008043 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008044 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8045 false);
8046 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008047 Type = Context.getComplexType(ElementType);
8048 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008049 }
8050 case 'Y' : {
8051 Type = Context.getPointerDiffType();
8052 break;
8053 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008054 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008055 Type = Context.getFILEType();
8056 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008057 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008058 return QualType();
8059 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008060 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008061 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008062 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008063 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008064 else
8065 Type = Context.getjmp_bufType();
8066
Mike Stump2adb4da2009-07-28 23:47:15 +00008067 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008068 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008069 return QualType();
8070 }
8071 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008072 case 'K':
8073 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8074 Type = Context.getucontext_tType();
8075
8076 if (Type.isNull()) {
8077 Error = ASTContext::GE_Missing_ucontext;
8078 return QualType();
8079 }
8080 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008081 case 'p':
8082 Type = Context.getProcessIDType();
8083 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008084 }
Mike Stump11289f42009-09-09 15:08:12 +00008085
Chris Lattnerdc226c22010-10-01 22:42:38 +00008086 // If there are modifiers and if we're allowed to parse them, go for it.
8087 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008088 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008089 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008090 default: Done = true; --Str; break;
8091 case '*':
8092 case '&': {
8093 // Both pointers and references can have their pointee types
8094 // qualified with an address space.
8095 char *End;
8096 unsigned AddrSpace = strtoul(Str, &End, 10);
8097 if (End != Str && AddrSpace != 0) {
8098 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8099 Str = End;
8100 }
8101 if (c == '*')
8102 Type = Context.getPointerType(Type);
8103 else
8104 Type = Context.getLValueReferenceType(Type);
8105 break;
8106 }
8107 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8108 case 'C':
8109 Type = Type.withConst();
8110 break;
8111 case 'D':
8112 Type = Context.getVolatileType(Type);
8113 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008114 case 'R':
8115 Type = Type.withRestrict();
8116 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008117 }
8118 }
Chris Lattner84733392010-10-01 07:13:18 +00008119
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008120 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008121 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008122
Chris Lattnerecd79c62009-06-14 00:45:47 +00008123 return Type;
8124}
8125
8126/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008127QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008128 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008129 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008130 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008131
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008132 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008133
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008134 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008135 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008136 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8137 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008138 if (Error != GE_None)
8139 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008140
8141 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8142
Chris Lattnerecd79c62009-06-14 00:45:47 +00008143 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008144 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008145 if (Error != GE_None)
8146 return QualType();
8147
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008148 // If this argument is required to be an IntegerConstantExpression and the
8149 // caller cares, fill in the bitmask we return.
8150 if (RequiresICE && IntegerConstantArgs)
8151 *IntegerConstantArgs |= 1 << ArgTypes.size();
8152
Chris Lattnerecd79c62009-06-14 00:45:47 +00008153 // Do array -> pointer decay. The builtin should use the decayed type.
8154 if (Ty->isArrayType())
8155 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008156
Chris Lattnerecd79c62009-06-14 00:45:47 +00008157 ArgTypes.push_back(Ty);
8158 }
8159
David Majnemerba3e5ec2015-03-13 18:26:17 +00008160 if (Id == Builtin::BI__GetExceptionInfo)
8161 return QualType();
8162
Chris Lattnerecd79c62009-06-14 00:45:47 +00008163 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8164 "'.' should only occur at end of builtin type list!");
8165
Reid Kleckner78af0702013-08-27 23:08:25 +00008166 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008167 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8168
8169 bool Variadic = (TypeStr[0] == '.');
8170
8171 // We really shouldn't be making a no-proto type here, especially in C++.
8172 if (ArgTypes.empty() && Variadic)
8173 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008174
John McCalldb40c7f2010-12-14 08:05:40 +00008175 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008176 EPI.ExtInfo = EI;
8177 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008178
Jordan Rose5c382722013-03-08 21:51:21 +00008179 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008180}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008181
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008182static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8183 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008184 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008185 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008186
Rafael Espindola3ae00052013-05-13 00:12:11 +00008187 GVALinkage External = GVA_StrongExternal;
8188 switch (FD->getTemplateSpecializationKind()) {
8189 case TSK_Undeclared:
8190 case TSK_ExplicitSpecialization:
8191 External = GVA_StrongExternal;
8192 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008193
Rafael Espindola3ae00052013-05-13 00:12:11 +00008194 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008195 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008196
David Majnemerc3d07332014-05-15 06:25:57 +00008197 // C++11 [temp.explicit]p10:
8198 // [ Note: The intent is that an inline function that is the subject of
8199 // an explicit instantiation declaration will still be implicitly
8200 // instantiated when used so that the body can be considered for
8201 // inlining, but that no out-of-line copy of the inline function would be
8202 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008203 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008204 return GVA_AvailableExternally;
8205
Rafael Espindola3ae00052013-05-13 00:12:11 +00008206 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008207 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008208 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008209 }
8210
8211 if (!FD->isInlined())
8212 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008213
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008214 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8215 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008216 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008217 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8218
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008219 // GNU or C99 inline semantics. Determine whether this symbol should be
8220 // externally visible.
8221 if (FD->isInlineDefinitionExternallyVisible())
8222 return External;
8223
8224 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008225 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008226 }
8227
David Majnemer54e3ba52014-04-02 23:17:29 +00008228 // Functions specified with extern and inline in -fms-compatibility mode
8229 // forcibly get emitted. While the body of the function cannot be later
8230 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008231 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008232 return GVA_StrongODR;
8233
David Majnemer27d69db2014-04-28 22:17:59 +00008234 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008235}
8236
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008237static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
8238 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8239 // dllexport/dllimport on inline functions.
8240 if (D->hasAttr<DLLImportAttr>()) {
8241 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8242 return GVA_AvailableExternally;
8243 } else if (D->hasAttr<DLLExportAttr>()) {
8244 if (L == GVA_DiscardableODR)
8245 return GVA_StrongODR;
8246 }
8247 return L;
8248}
8249
8250GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8251 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
8252 FD);
8253}
8254
8255static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8256 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008257 if (!VD->isExternallyVisible())
8258 return GVA_Internal;
8259
David Majnemer27d69db2014-04-28 22:17:59 +00008260 if (VD->isStaticLocal()) {
8261 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8262 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8263 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8264 LexicalContext = LexicalContext->getLexicalParent();
8265
Richard Smith9e2341d2015-03-23 03:25:59 +00008266 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008267 // enclosing function.
8268 if (LexicalContext)
8269 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008270 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008271
8272 // GVA_StrongODR function linkage is stronger than what we need,
8273 // downgrade to GVA_DiscardableODR.
8274 // This allows us to discard the variable if we never end up needing it.
8275 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8276 : StaticLocalLinkage;
8277 }
8278
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008279 // MSVC treats in-class initialized static data members as definitions.
8280 // By giving them non-strong linkage, out-of-line definitions won't
8281 // cause link errors.
8282 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8283 return GVA_DiscardableODR;
8284
Richard Smith8809a0c2013-09-27 20:14:12 +00008285 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008286 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008287 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008288
David Majnemer6d1780c2015-07-17 23:36:49 +00008289 case TSK_ExplicitSpecialization:
8290 return Context.getLangOpts().MSVCCompat && VD->isStaticDataMember()
8291 ? GVA_StrongODR
8292 : GVA_StrongExternal;
8293
Rafael Espindola3ae00052013-05-13 00:12:11 +00008294 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008295 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008296
David Majnemer27d69db2014-04-28 22:17:59 +00008297 case TSK_ExplicitInstantiationDeclaration:
8298 return GVA_AvailableExternally;
8299
Rafael Espindola3ae00052013-05-13 00:12:11 +00008300 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008301 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008302 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008303
8304 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008305}
8306
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008307GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8308 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8309 VD);
8310}
8311
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008312bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008313 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8314 if (!VD->isFileVarDecl())
8315 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008316 // Global named register variables (GNU extension) are never emitted.
8317 if (VD->getStorageClass() == SC_Register)
8318 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008319 if (VD->getDescribedVarTemplate() ||
8320 isa<VarTemplatePartialSpecializationDecl>(VD))
8321 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008322 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8323 // We never need to emit an uninstantiated function template.
8324 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8325 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008326 } else if (isa<OMPThreadPrivateDecl>(D))
8327 return true;
8328 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008329 return false;
8330
8331 // If this is a member of a class template, we do not need to emit it.
8332 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008333 return false;
8334
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008335 // Weak references don't produce any output by themselves.
8336 if (D->hasAttr<WeakRefAttr>())
8337 return false;
8338
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008339 // Aliases and used decls are required.
8340 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8341 return true;
8342
8343 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8344 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008345 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008346 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008347
8348 // Constructors and destructors are required.
8349 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8350 return true;
8351
John McCall6bd2a892013-01-25 22:31:03 +00008352 // The key function for a class is required. This rule only comes
8353 // into play when inline functions can be key functions, though.
8354 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8355 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8356 const CXXRecordDecl *RD = MD->getParent();
8357 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8358 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8359 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8360 return true;
8361 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008362 }
8363 }
8364
8365 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8366
8367 // static, static inline, always_inline, and extern inline functions can
8368 // always be deferred. Normal inline functions can be deferred in C99/C++.
8369 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008370 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8371 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008372 return false;
8373 return true;
8374 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008375
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008376 const VarDecl *VD = cast<VarDecl>(D);
8377 assert(VD->isFileVarDecl() && "Expected file scoped var");
8378
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008379 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8380 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008381 return false;
8382
Richard Smitha0e5e542012-11-12 21:38:00 +00008383 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008384 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008385 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8386 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008387 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008388
Richard Smitha0e5e542012-11-12 21:38:00 +00008389 // Variables that have destruction with side-effects are required.
8390 if (VD->getType().isDestructedType())
8391 return true;
8392
8393 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008394 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8395 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008396 return true;
8397
8398 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008399}
Charles Davis53c59df2010-08-16 03:33:14 +00008400
Reid Kleckner78af0702013-08-27 23:08:25 +00008401CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8402 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008403 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008404 if (IsCXXMethod)
8405 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008406
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008407 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8408
8409 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008410}
8411
Jay Foad39c79802011-01-12 09:06:06 +00008412bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008413 // Pass through to the C++ ABI object
8414 return ABI->isNearlyEmpty(RD);
8415}
8416
Reid Kleckner96f8f932014-02-05 17:27:08 +00008417VTableContextBase *ASTContext::getVTableContext() {
8418 if (!VTContext.get()) {
8419 if (Target->getCXXABI().isMicrosoft())
8420 VTContext.reset(new MicrosoftVTableContext(*this));
8421 else
8422 VTContext.reset(new ItaniumVTableContext(*this));
8423 }
8424 return VTContext.get();
8425}
8426
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008427MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008428 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008429 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008430 case TargetCXXABI::GenericItanium:
8431 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008432 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008433 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008434 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008435 case TargetCXXABI::WebAssembly:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008436 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008437 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008438 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008439 }
David Blaikie83d382b2011-09-23 05:06:16 +00008440 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008441}
8442
Charles Davis53c59df2010-08-16 03:33:14 +00008443CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008444
8445size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008446 return ASTRecordLayouts.getMemorySize() +
8447 llvm::capacity_in_bytes(ObjCLayouts) +
8448 llvm::capacity_in_bytes(KeyFunctions) +
8449 llvm::capacity_in_bytes(ObjCImpls) +
8450 llvm::capacity_in_bytes(BlockVarCopyInits) +
8451 llvm::capacity_in_bytes(DeclAttrs) +
8452 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8453 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8454 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8455 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8456 llvm::capacity_in_bytes(OverriddenMethods) +
8457 llvm::capacity_in_bytes(Types) +
8458 llvm::capacity_in_bytes(VariableArrayTypes) +
8459 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008460}
Ted Kremenek540017e2011-10-06 05:00:56 +00008461
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008462/// getIntTypeForBitwidth -
8463/// sets integer QualTy according to specified details:
8464/// bitwidth, signed/unsigned.
8465/// Returns empty type if there is no appropriate target types.
8466QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8467 unsigned Signed) const {
8468 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8469 CanQualType QualTy = getFromTargetType(Ty);
8470 if (!QualTy && DestWidth == 128)
8471 return Signed ? Int128Ty : UnsignedInt128Ty;
8472 return QualTy;
8473}
8474
8475/// getRealTypeForBitwidth -
8476/// sets floating point QualTy according to specified bitwidth.
8477/// Returns empty type if there is no appropriate target types.
8478QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8479 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8480 switch (Ty) {
8481 case TargetInfo::Float:
8482 return FloatTy;
8483 case TargetInfo::Double:
8484 return DoubleTy;
8485 case TargetInfo::LongDouble:
8486 return LongDoubleTy;
8487 case TargetInfo::NoFloat:
8488 return QualType();
8489 }
8490
8491 llvm_unreachable("Unhandled TargetInfo::RealType value");
8492}
8493
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008494void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8495 if (Number > 1)
8496 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008497}
8498
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008499unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8500 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8501 MangleNumbers.find(ND);
8502 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008503}
8504
David Majnemer2206bf52014-03-05 08:57:59 +00008505void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8506 if (Number > 1)
8507 StaticLocalNumbers[VD] = Number;
8508}
8509
8510unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8511 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8512 StaticLocalNumbers.find(VD);
8513 return I != StaticLocalNumbers.end() ? I->second : 1;
8514}
8515
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008516MangleNumberingContext &
8517ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008518 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8519 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8520 if (!MCtx)
8521 MCtx = createMangleNumberingContext();
8522 return *MCtx;
8523}
8524
8525MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8526 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008527}
8528
David Majnemere7a818f2015-03-06 18:53:55 +00008529const CXXConstructorDecl *
8530ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8531 return ABI->getCopyConstructorForExceptionObject(
8532 cast<CXXRecordDecl>(RD->getFirstDecl()));
8533}
8534
8535void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8536 CXXConstructorDecl *CD) {
8537 return ABI->addCopyConstructorForExceptionObject(
8538 cast<CXXRecordDecl>(RD->getFirstDecl()),
8539 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8540}
8541
David Majnemerdfa6d202015-03-11 18:36:39 +00008542void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8543 unsigned ParmIdx, Expr *DAE) {
8544 ABI->addDefaultArgExprForConstructor(
8545 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8546}
8547
8548Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8549 unsigned ParmIdx) {
8550 return ABI->getDefaultArgExprForConstructor(
8551 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8552}
8553
David Majnemer00350522015-08-31 18:48:39 +00008554void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8555 TypedefNameDecl *DD) {
8556 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8557}
8558
8559TypedefNameDecl *
8560ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8561 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8562}
8563
8564void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8565 DeclaratorDecl *DD) {
8566 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8567}
8568
8569DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8570 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8571}
8572
Ted Kremenek540017e2011-10-06 05:00:56 +00008573void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8574 ParamIndices[D] = index;
8575}
8576
8577unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8578 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8579 assert(I != ParamIndices.end() &&
8580 "ParmIndices lacks entry set by ParmVarDecl");
8581 return I->second;
8582}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008583
Richard Smithe6c01442013-06-05 00:46:14 +00008584APValue *
8585ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8586 bool MayCreate) {
8587 assert(E && E->getStorageDuration() == SD_Static &&
8588 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008589 if (MayCreate) {
8590 APValue *&MTVI = MaterializedTemporaryValues[E];
8591 if (!MTVI)
8592 MTVI = new (*this) APValue;
8593 return MTVI;
8594 }
Richard Smithe6c01442013-06-05 00:46:14 +00008595
David Majnemer2dcef9e2015-08-13 23:50:15 +00008596 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008597}
8598
Fariborz Jahanian615de762013-05-28 17:37:39 +00008599bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8600 const llvm::Triple &T = getTargetInfo().getTriple();
8601 if (!T.isOSDarwin())
8602 return false;
8603
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008604 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8605 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8606 return false;
8607
Fariborz Jahanian615de762013-05-28 17:37:39 +00008608 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8609 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8610 uint64_t Size = sizeChars.getQuantity();
8611 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8612 unsigned Align = alignChars.getQuantity();
8613 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8614 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8615}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008616
8617namespace {
8618
8619 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8620 /// parents as defined by the \c RecursiveASTVisitor.
8621 ///
8622 /// Note that the relationship described here is purely in terms of AST
8623 /// traversal - there are other relationships (for example declaration context)
8624 /// in the AST that are better modeled by special matchers.
8625 ///
8626 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8627 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8628
8629 public:
8630 /// \brief Builds and returns the translation unit's parent map.
8631 ///
8632 /// The caller takes ownership of the returned \c ParentMap.
8633 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8634 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8635 Visitor.TraverseDecl(&TU);
8636 return Visitor.Parents;
8637 }
8638
8639 private:
8640 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8641
8642 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8643 }
8644
8645 bool shouldVisitTemplateInstantiations() const {
8646 return true;
8647 }
8648 bool shouldVisitImplicitCode() const {
8649 return true;
8650 }
8651 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8652 // are not triggered during data recursion.
8653 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8654 return false;
8655 }
8656
8657 template <typename T>
8658 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008659 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008660 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008661 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008662 // FIXME: Currently we add the same parent multiple times, but only
8663 // when no memoization data is available for the type.
8664 // For example when we visit all subexpressions of template
8665 // instantiations; this is suboptimal, but benign: the only way to
8666 // visit those is with hasAncestor / hasParent, and those do not create
8667 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008668 // The plan is to enable DynTypedNode to be storable in a map or hash
8669 // map. The main problem there is to implement hash functions /
8670 // comparison operators for all types that DynTypedNode supports that
8671 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008672 auto &NodeOrVector = (*Parents)[Node];
8673 if (NodeOrVector.isNull()) {
8674 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008675 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008676 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8677 auto *Node =
8678 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8679 auto *Vector = new ASTContext::ParentVector(1, *Node);
8680 NodeOrVector = Vector;
8681 delete Node;
8682 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008683 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008684
8685 auto *Vector =
8686 NodeOrVector.template get<ASTContext::ParentVector *>();
8687 // Skip duplicates for types that have memoization data.
8688 // We must check that the type has memoization data before calling
8689 // std::find() because DynTypedNode::operator== can't compare all
8690 // types.
8691 bool Found = ParentStack.back().getMemoizationData() &&
8692 std::find(Vector->begin(), Vector->end(),
8693 ParentStack.back()) != Vector->end();
8694 if (!Found)
8695 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008696 }
8697 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008698 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8699 bool Result = (this ->* traverse) (Node);
8700 ParentStack.pop_back();
8701 return Result;
8702 }
8703
8704 bool TraverseDecl(Decl *DeclNode) {
8705 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8706 }
8707
8708 bool TraverseStmt(Stmt *StmtNode) {
8709 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8710 }
8711
8712 ASTContext::ParentMap *Parents;
8713 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8714
8715 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8716 };
8717
8718} // end namespace
8719
Benjamin Kramer07935292014-10-04 17:01:26 +00008720ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008721ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8722 assert(Node.getMemoizationData() &&
8723 "Invariant broken: only nodes that support memoization may be "
8724 "used in the parent map.");
8725 if (!AllParents) {
8726 // We always need to run over the whole translation unit, as
8727 // hasAncestor can escape any subtree.
8728 AllParents.reset(
8729 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8730 }
8731 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8732 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008733 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008734 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008735 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8736 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008737 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008738 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008739}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008740
8741bool
8742ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8743 const ObjCMethodDecl *MethodImpl) {
8744 // No point trying to match an unavailable/deprecated mothod.
8745 if (MethodDecl->hasAttr<UnavailableAttr>()
8746 || MethodDecl->hasAttr<DeprecatedAttr>())
8747 return false;
8748 if (MethodDecl->getObjCDeclQualifier() !=
8749 MethodImpl->getObjCDeclQualifier())
8750 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008751 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008752 return false;
8753
8754 if (MethodDecl->param_size() != MethodImpl->param_size())
8755 return false;
8756
8757 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8758 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8759 EF = MethodDecl->param_end();
8760 IM != EM && IF != EF; ++IM, ++IF) {
8761 const ParmVarDecl *DeclVar = (*IF);
8762 const ParmVarDecl *ImplVar = (*IM);
8763 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8764 return false;
8765 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8766 return false;
8767 }
8768 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8769
8770}
Richard Smith053f6c62014-05-16 23:01:30 +00008771
8772// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8773// doesn't include ASTContext.h
8774template
8775clang::LazyGenerationalUpdatePtr<
8776 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8777clang::LazyGenerationalUpdatePtr<
8778 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8779 const clang::ASTContext &Ctx, Decl *Value);