blob: f679377b84526a91a710de0f3806a6efa82103b9 [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:
Charles Davis53c59df2010-08-16 03:33:14 +0000687 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000689 return CreateMicrosoftCXXABI(*this);
690 }
David Blaikie8a40f702012-01-17 06:56:22 +0000691 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000692}
693
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 const LangOptions &LOpts) {
696 if (LOpts.FakeAddressSpaceMap) {
697 // The fake address space map must have a distinct entry for each
698 // language-specific address space.
699 static const unsigned FakeAddrSpaceMap[] = {
700 1, // opencl_global
701 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000702 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000703 4, // opencl_generic
704 5, // cuda_device
705 6, // cuda_constant
706 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 }
712}
713
David Tweed31d09b02013-09-13 12:04:22 +0000714static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
715 const LangOptions &LangOpts) {
716 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000717 case LangOptions::ASMM_Target:
718 return TI.useAddressSpaceMapMangling();
719 case LangOptions::ASMM_On:
720 return true;
721 case LangOptions::ASMM_Off:
722 return false;
723 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000724 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000725}
726
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000727ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000728 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000729 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
731 DependentTemplateSpecializationTypes(this_()),
732 SubstTemplateTemplateParmPacks(this_()),
733 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
734 UInt128Decl(nullptr), Float128StubDecl(nullptr),
735 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
736 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
739 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
740 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000741 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
742 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000744 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
745 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
746 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
747 Comments(SM), CommentsLoaded(false),
748 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000749 TUDecl = TranslationUnitDecl::Create(*this);
750}
751
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000752ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000753 ReleaseParentMapEntries();
754
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000758
Manuel Klimeka7328992013-06-03 13:51:33 +0000759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
David Majnemere694f3e2015-08-14 14:43:50 +0000786 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
787 MaterializedTemporaryValues)
788 MTVPair.second->~APValue();
789
Reid Kleckner588c9372014-02-19 23:44:52 +0000790 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000791}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000792
Manuel Klimek95403e62014-05-21 13:28:59 +0000793void ASTContext::ReleaseParentMapEntries() {
794 if (!AllParents) return;
795 for (const auto &Entry : *AllParents) {
796 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
797 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
798 } else {
799 assert(Entry.second.is<ParentVector *>());
800 delete Entry.second.get<ParentVector *>();
801 }
802 }
803}
804
Douglas Gregor1a809332010-05-23 18:26:36 +0000805void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000806 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000807}
808
Mike Stump11289f42009-09-09 15:08:12 +0000809void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000810ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
811 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000812}
813
Chris Lattner4eb445d2007-01-26 01:27:23 +0000814void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000815 llvm::errs() << "\n*** AST Context Stats:\n";
816 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000817
Douglas Gregora30d0462009-05-26 14:40:08 +0000818 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000819#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000820#define ABSTRACT_TYPE(Name, Parent)
821#include "clang/AST/TypeNodes.def"
822 0 // Extra
823 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000824
Chris Lattner4eb445d2007-01-26 01:27:23 +0000825 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
826 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000827 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000828 }
829
Douglas Gregora30d0462009-05-26 14:40:08 +0000830 unsigned Idx = 0;
831 unsigned TotalBytes = 0;
832#define TYPE(Name, Parent) \
833 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000834 llvm::errs() << " " << counts[Idx] << " " << #Name \
835 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000836 TotalBytes += counts[Idx] * sizeof(Name##Type); \
837 ++Idx;
838#define ABSTRACT_TYPE(Name, Parent)
839#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000840
Chandler Carruth3c147a72011-07-04 05:32:14 +0000841 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
842
Douglas Gregor7454c562010-07-02 20:37:36 +0000843 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000844 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
845 << NumImplicitDefaultConstructors
846 << " implicit default constructors created\n";
847 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
848 << NumImplicitCopyConstructors
849 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000850 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000851 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
852 << NumImplicitMoveConstructors
853 << " implicit move constructors created\n";
854 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
855 << NumImplicitCopyAssignmentOperators
856 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000857 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000858 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
859 << NumImplicitMoveAssignmentOperators
860 << " implicit move assignment operators created\n";
861 llvm::errs() << NumImplicitDestructorsDeclared << "/"
862 << NumImplicitDestructors
863 << " implicit destructors created\n";
864
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000865 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000866 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000867 ExternalSource->PrintStats();
868 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000869
Douglas Gregor5b11d492010-07-25 17:53:33 +0000870 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000871}
872
Richard Smith42413142015-05-15 20:05:43 +0000873void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
874 bool NotifyListeners) {
875 if (NotifyListeners)
876 if (auto *Listener = getASTMutationListener())
877 Listener->RedefinedHiddenDefinition(ND, M);
878
879 if (getLangOpts().ModulesLocalVisibility)
880 MergedDefModules[ND].push_back(M);
881 else
882 ND->setHidden(false);
883}
884
885void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
886 auto It = MergedDefModules.find(ND);
887 if (It == MergedDefModules.end())
888 return;
889
890 auto &Merged = It->second;
891 llvm::DenseSet<Module*> Found;
892 for (Module *&M : Merged)
893 if (!Found.insert(M).second)
894 M = nullptr;
895 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
896}
897
Richard Smithf19e1272015-03-07 00:04:49 +0000898ExternCContextDecl *ASTContext::getExternCContextDecl() const {
899 if (!ExternCContext)
900 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
901
902 return ExternCContext;
903}
904
Alp Toker2dea15b2013-12-17 01:22:38 +0000905RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
906 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000907 SourceLocation Loc;
908 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000909 if (getLangOpts().CPlusPlus)
910 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
911 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000912 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000913 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
914 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000915 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000916 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
917 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000918 return NewDecl;
919}
920
921TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
922 StringRef Name) const {
923 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
924 TypedefDecl *NewDecl = TypedefDecl::Create(
925 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
926 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
927 NewDecl->setImplicit();
928 return NewDecl;
929}
930
Douglas Gregor801c99d2011-08-12 06:49:56 +0000931TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000932 if (!Int128Decl)
933 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000934 return Int128Decl;
935}
936
937TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000938 if (!UInt128Decl)
939 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000940 return UInt128Decl;
941}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000942
Nico Webere1687c52013-06-20 21:44:55 +0000943TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000944 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000945 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000946 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000947
Nico Webere1687c52013-06-20 21:44:55 +0000948 return Float128StubDecl;
949}
950
John McCall48f2d582009-10-23 23:03:21 +0000951void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000952 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000953 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000954 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000955}
956
Douglas Gregore8bbc122011-09-02 00:18:52 +0000957void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
958 assert((!this->Target || this->Target == &Target) &&
959 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000960 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000961
Douglas Gregore8bbc122011-09-02 00:18:52 +0000962 this->Target = &Target;
963
964 ABI.reset(createCXXABI(Target));
965 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000966 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000967
Chris Lattner970e54e2006-11-12 00:37:36 +0000968 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000969 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattner970e54e2006-11-12 00:37:36 +0000971 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000972 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000973 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000974 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000975 InitBuiltinType(CharTy, BuiltinType::Char_S);
976 else
977 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000978 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000979 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
980 InitBuiltinType(ShortTy, BuiltinType::Short);
981 InitBuiltinType(IntTy, BuiltinType::Int);
982 InitBuiltinType(LongTy, BuiltinType::Long);
983 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattner970e54e2006-11-12 00:37:36 +0000985 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000986 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
987 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
988 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
989 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
990 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Chris Lattner970e54e2006-11-12 00:37:36 +0000992 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000993 InitBuiltinType(FloatTy, BuiltinType::Float);
994 InitBuiltinType(DoubleTy, BuiltinType::Double);
995 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000996
Chris Lattnerf122cef2009-04-30 02:43:43 +0000997 // GNU extension, 128-bit integers.
998 InitBuiltinType(Int128Ty, BuiltinType::Int128);
999 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1000
Hans Wennborg0d81e012013-05-10 10:08:40 +00001001 // C++ 3.9.1p5
1002 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1003 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1004 else // -fshort-wchar makes wchar_t be unsigned.
1005 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1006 if (LangOpts.CPlusPlus && LangOpts.WChar)
1007 WideCharTy = WCharTy;
1008 else {
1009 // C99 (or C++ using -fno-wchar).
1010 WideCharTy = getFromTargetType(Target.getWCharType());
1011 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001012
James Molloy36365542012-05-04 10:55:22 +00001013 WIntTy = getFromTargetType(Target.getWIntType());
1014
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001015 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1016 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1017 else // C99
1018 Char16Ty = getFromTargetType(Target.getChar16Type());
1019
1020 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1021 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1022 else // C99
1023 Char32Ty = getFromTargetType(Target.getChar32Type());
1024
Douglas Gregor4619e432008-12-05 23:32:09 +00001025 // Placeholder type for type-dependent expressions whose type is
1026 // completely unknown. No code should ever check a type against
1027 // DependentTy and users should never see it; however, it is here to
1028 // help diagnose failures to properly check for type-dependent
1029 // expressions.
1030 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001031
John McCall36e7fe32010-10-12 00:20:44 +00001032 // Placeholder type for functions.
1033 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1034
John McCall0009fcc2011-04-26 20:42:42 +00001035 // Placeholder type for bound members.
1036 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1037
John McCall526ab472011-10-25 17:37:35 +00001038 // Placeholder type for pseudo-objects.
1039 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1040
John McCall31996342011-04-07 08:22:57 +00001041 // "any" type; useful for debugger-like clients.
1042 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1043
John McCall8a6b59a2011-10-17 18:09:15 +00001044 // Placeholder type for unbridged ARC casts.
1045 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1046
Eli Friedman34866c72012-08-31 00:14:07 +00001047 // Placeholder type for builtin functions.
1048 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1049
Chris Lattner970e54e2006-11-12 00:37:36 +00001050 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001051 FloatComplexTy = getComplexType(FloatTy);
1052 DoubleComplexTy = getComplexType(DoubleTy);
1053 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001054
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001055 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001056 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1057 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001058 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001059
1060 if (LangOpts.OpenCL) {
1061 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1062 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1063 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1064 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1065 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1066 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001067
Guy Benyei61054192013-02-07 10:55:47 +00001068 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001069 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001070 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001071
1072 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001073 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1074 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001075
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001076 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001077
1078 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001079
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001080 // void * type
1081 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001082
1083 // nullptr type (C++0x 2.14.7)
1084 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001085
1086 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1087 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001088
1089 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001090 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001091}
1092
David Blaikie9c902b52011-09-25 23:23:43 +00001093DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001094 return SourceMgr.getDiagnostics();
1095}
1096
Douglas Gregor561eceb2010-08-30 16:49:28 +00001097AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1098 AttrVec *&Result = DeclAttrs[D];
1099 if (!Result) {
1100 void *Mem = Allocate(sizeof(AttrVec));
1101 Result = new (Mem) AttrVec;
1102 }
1103
1104 return *Result;
1105}
1106
1107/// \brief Erase the attributes corresponding to the given declaration.
1108void ASTContext::eraseDeclAttrs(const Decl *D) {
1109 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1110 if (Pos != DeclAttrs.end()) {
1111 Pos->second->~AttrVec();
1112 DeclAttrs.erase(Pos);
1113 }
1114}
1115
Larisse Voufo39a1e502013-08-06 01:03:05 +00001116// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001117MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001118ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001119 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001120 return getTemplateOrSpecializationInfo(Var)
1121 .dyn_cast<MemberSpecializationInfo *>();
1122}
1123
1124ASTContext::TemplateOrSpecializationInfo
1125ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1126 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1127 TemplateOrInstantiation.find(Var);
1128 if (Pos == TemplateOrInstantiation.end())
1129 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001130
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001131 return Pos->second;
1132}
1133
Mike Stump11289f42009-09-09 15:08:12 +00001134void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001135ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001136 TemplateSpecializationKind TSK,
1137 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001138 assert(Inst->isStaticDataMember() && "Not a static data member");
1139 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001140 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1141 Tmpl, TSK, PointOfInstantiation));
1142}
1143
1144void
1145ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1146 TemplateOrSpecializationInfo TSI) {
1147 assert(!TemplateOrInstantiation[Inst] &&
1148 "Already noted what the variable was instantiated from");
1149 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001150}
1151
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001152FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1153 const FunctionDecl *FD){
1154 assert(FD && "Specialization is 0");
1155 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001156 = ClassScopeSpecializationPattern.find(FD);
1157 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001158 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001159
1160 return Pos->second;
1161}
1162
1163void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1164 FunctionDecl *Pattern) {
1165 assert(FD && "Specialization is 0");
1166 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001167 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001168}
1169
John McCalle61f2ba2009-11-18 02:36:19 +00001170NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001171ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001172 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001173 = InstantiatedFromUsingDecl.find(UUD);
1174 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001175 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001176
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001177 return Pos->second;
1178}
1179
1180void
John McCallb96ec562009-12-04 22:46:56 +00001181ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1182 assert((isa<UsingDecl>(Pattern) ||
1183 isa<UnresolvedUsingValueDecl>(Pattern) ||
1184 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1185 "pattern decl is not a using decl");
1186 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1187 InstantiatedFromUsingDecl[Inst] = Pattern;
1188}
1189
1190UsingShadowDecl *
1191ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1192 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1193 = InstantiatedFromUsingShadowDecl.find(Inst);
1194 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001195 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001196
1197 return Pos->second;
1198}
1199
1200void
1201ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1202 UsingShadowDecl *Pattern) {
1203 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1204 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001205}
1206
Anders Carlsson5da84842009-09-01 04:26:58 +00001207FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1208 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1209 = InstantiatedFromUnnamedFieldDecl.find(Field);
1210 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001211 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001212
Anders Carlsson5da84842009-09-01 04:26:58 +00001213 return Pos->second;
1214}
1215
1216void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1217 FieldDecl *Tmpl) {
1218 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1219 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1220 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1221 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001222
Anders Carlsson5da84842009-09-01 04:26:58 +00001223 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1224}
1225
Douglas Gregor832940b2010-03-02 23:58:15 +00001226ASTContext::overridden_cxx_method_iterator
1227ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1228 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001229 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001230 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001231 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001232
1233 return Pos->second.begin();
1234}
1235
1236ASTContext::overridden_cxx_method_iterator
1237ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1238 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001239 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001240 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001241 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001242
1243 return Pos->second.end();
1244}
1245
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001246unsigned
1247ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1248 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001249 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001250 if (Pos == OverriddenMethods.end())
1251 return 0;
1252
1253 return Pos->second.size();
1254}
1255
Douglas Gregor832940b2010-03-02 23:58:15 +00001256void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1257 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001258 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001259 OverriddenMethods[Method].push_back(Overridden);
1260}
1261
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001262void ASTContext::getOverriddenMethods(
1263 const NamedDecl *D,
1264 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001265 assert(D);
1266
1267 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001268 Overridden.append(overridden_methods_begin(CXXMethod),
1269 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001270 return;
1271 }
1272
1273 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1274 if (!Method)
1275 return;
1276
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001277 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1278 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001279 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001280}
1281
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001282void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1283 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1284 assert(!Import->isFromASTFile() && "Non-local import declaration");
1285 if (!FirstLocalImport) {
1286 FirstLocalImport = Import;
1287 LastLocalImport = Import;
1288 return;
1289 }
1290
1291 LastLocalImport->NextLocalImport = Import;
1292 LastLocalImport = Import;
1293}
1294
Chris Lattner53cfe802007-07-18 17:52:12 +00001295//===----------------------------------------------------------------------===//
1296// Type Sizing and Analysis
1297//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001298
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001299/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1300/// scalar floating point type.
1301const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001302 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001303 assert(BT && "Not a floating point type!");
1304 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001305 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001306 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001307 case BuiltinType::Float: return Target->getFloatFormat();
1308 case BuiltinType::Double: return Target->getDoubleFormat();
1309 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001310 }
1311}
1312
Rafael Espindola71eccb32013-08-08 19:53:46 +00001313CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001314 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001315
John McCall94268702010-10-08 18:24:19 +00001316 bool UseAlignAttrOnly = false;
1317 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1318 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001319
John McCall94268702010-10-08 18:24:19 +00001320 // __attribute__((aligned)) can increase or decrease alignment
1321 // *except* on a struct or struct member, where it only increases
1322 // alignment unless 'packed' is also specified.
1323 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001324 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001325 // ignore that possibility; Sema should diagnose it.
1326 if (isa<FieldDecl>(D)) {
1327 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1328 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1329 } else {
1330 UseAlignAttrOnly = true;
1331 }
1332 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001333 else if (isa<FieldDecl>(D))
1334 UseAlignAttrOnly =
1335 D->hasAttr<PackedAttr>() ||
1336 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001337
John McCall4e819612011-01-20 07:57:12 +00001338 // If we're using the align attribute only, just ignore everything
1339 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001340 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001341 // do nothing
1342
John McCall94268702010-10-08 18:24:19 +00001343 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001344 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001345 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001346 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001347 T = RT->getPointeeType();
1348 else
1349 T = getPointerType(RT->getPointeeType());
1350 }
Richard Smithf6d70302014-06-10 23:34:28 +00001351 QualType BaseT = getBaseElementType(T);
1352 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001353 // Adjust alignments of declarations with array type by the
1354 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001355 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001356 unsigned MinWidth = Target->getLargeArrayMinWidth();
1357 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001358 if (isa<VariableArrayType>(arrayType))
1359 Align = std::max(Align, Target->getLargeArrayAlign());
1360 else if (isa<ConstantArrayType>(arrayType) &&
1361 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1362 Align = std::max(Align, Target->getLargeArrayAlign());
1363 }
John McCall33ddac02011-01-19 10:06:00 +00001364 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001365 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001366 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001367 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001368 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1369 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001370 }
John McCall4e819612011-01-20 07:57:12 +00001371
1372 // Fields can be subject to extra alignment constraints, like if
1373 // the field is packed, the struct is packed, or the struct has a
1374 // a max-field-alignment constraint (#pragma pack). So calculate
1375 // the actual alignment of the field within the struct, and then
1376 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001377 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1378 const RecordDecl *Parent = Field->getParent();
1379 // We can only produce a sensible answer if the record is valid.
1380 if (!Parent->isInvalidDecl()) {
1381 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001382
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001383 // Start with the record's overall alignment.
1384 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001385
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001386 // Use the GCD of that and the offset within the record.
1387 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1388 if (Offset > 0) {
1389 // Alignment is always a power of 2, so the GCD will be a power of 2,
1390 // which means we get to do this crazy thing instead of Euclid's.
1391 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1392 if (LowBitOfOffset < FieldAlign)
1393 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1394 }
1395
1396 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001397 }
Charles Davis3fc51072010-02-23 04:52:00 +00001398 }
Chris Lattner68061312009-01-24 21:53:27 +00001399 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001400
Ken Dyckcc56c542011-01-15 18:38:59 +00001401 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001402}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001403
John McCallf1249922012-08-21 04:10:00 +00001404// getTypeInfoDataSizeInChars - Return the size of a type, in
1405// chars. If the type is a record, its data size is returned. This is
1406// the size of the memcpy that's performed when assigning this type
1407// using a trivial copy/move assignment operator.
1408std::pair<CharUnits, CharUnits>
1409ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1410 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1411
1412 // In C++, objects can sometimes be allocated into the tail padding
1413 // of a base-class subobject. We decide whether that's possible
1414 // during class layout, so here we can just trust the layout results.
1415 if (getLangOpts().CPlusPlus) {
1416 if (const RecordType *RT = T->getAs<RecordType>()) {
1417 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1418 sizeAndAlign.first = layout.getDataSize();
1419 }
1420 }
1421
1422 return sizeAndAlign;
1423}
1424
Richard Trieu04d2d942013-05-14 21:59:17 +00001425/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1426/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1427std::pair<CharUnits, CharUnits>
1428static getConstantArrayInfoInChars(const ASTContext &Context,
1429 const ConstantArrayType *CAT) {
1430 std::pair<CharUnits, CharUnits> EltInfo =
1431 Context.getTypeInfoInChars(CAT->getElementType());
1432 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001433 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1434 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001435 "Overflow in array type char size evaluation");
1436 uint64_t Width = EltInfo.first.getQuantity() * Size;
1437 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001438 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1439 Context.getTargetInfo().getPointerWidth(0) == 64)
1440 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001441 return std::make_pair(CharUnits::fromQuantity(Width),
1442 CharUnits::fromQuantity(Align));
1443}
1444
John McCall87fe5d52010-05-20 01:18:31 +00001445std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001446ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001447 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1448 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001449 TypeInfo Info = getTypeInfo(T);
1450 return std::make_pair(toCharUnitsFromBits(Info.Width),
1451 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001452}
1453
1454std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001455ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001456 return getTypeInfoInChars(T.getTypePtr());
1457}
1458
David Majnemer34b57492014-07-30 01:30:47 +00001459bool ASTContext::isAlignmentRequired(const Type *T) const {
1460 return getTypeInfo(T).AlignIsRequired;
1461}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001462
David Majnemer34b57492014-07-30 01:30:47 +00001463bool ASTContext::isAlignmentRequired(QualType T) const {
1464 return isAlignmentRequired(T.getTypePtr());
1465}
1466
1467TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001468 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1469 if (I != MemoizedTypeInfo.end())
1470 return I->second;
1471
1472 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1473 TypeInfo TI = getTypeInfoImpl(T);
1474 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001475 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001476}
1477
1478/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1479/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001480///
1481/// FIXME: Pointers into different addr spaces could have different sizes and
1482/// alignment requirements: getPointerInfo should take an AddrSpace, this
1483/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001484TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1485 uint64_t Width = 0;
1486 unsigned Align = 8;
1487 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001488 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001489#define TYPE(Class, Base)
1490#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001491#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001492#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001493#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1494 case Type::Class: \
1495 assert(!T->isDependentType() && "should not see dependent types here"); \
1496 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001497#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001498 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001499
Chris Lattner355332d2007-07-13 22:27:08 +00001500 case Type::FunctionNoProto:
1501 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001502 // GCC extension: alignof(function) = 32 bits
1503 Width = 0;
1504 Align = 32;
1505 break;
1506
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001507 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001508 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001509 Width = 0;
1510 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1511 break;
1512
Steve Naroff5c131802007-08-30 01:06:46 +00001513 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001514 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001515
David Majnemer34b57492014-07-30 01:30:47 +00001516 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001517 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001518 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001519 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001520 Width = EltInfo.Width * Size;
1521 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001522 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1523 getTargetInfo().getPointerWidth(0) == 64)
1524 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001525 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001526 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001527 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001528 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001529 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001530 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1531 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001532 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001533 // If the alignment is not a power of 2, round up to the next power of 2.
1534 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001535 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001536 Align = llvm::NextPowerOf2(Align);
1537 Width = llvm::RoundUpToAlignment(Width, Align);
1538 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001539 // Adjust the alignment based on the target max.
1540 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1541 if (TargetVectorAlign && TargetVectorAlign < Align)
1542 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001543 break;
1544 }
Chris Lattner647fb222007-07-18 18:26:58 +00001545
Chris Lattner7570e9c2008-03-08 08:52:55 +00001546 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001547 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001548 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001549 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001550 // GCC extension: alignof(void) = 8 bits.
1551 Width = 0;
1552 Align = 8;
1553 break;
1554
Chris Lattner6a4f7452007-12-19 19:23:28 +00001555 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 Width = Target->getBoolWidth();
1557 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001559 case BuiltinType::Char_S:
1560 case BuiltinType::Char_U:
1561 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001562 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001563 Width = Target->getCharWidth();
1564 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001565 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001566 case BuiltinType::WChar_S:
1567 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001568 Width = Target->getWCharWidth();
1569 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001570 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001571 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001572 Width = Target->getChar16Width();
1573 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001574 break;
1575 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001576 Width = Target->getChar32Width();
1577 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001578 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001579 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001580 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001581 Width = Target->getShortWidth();
1582 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001583 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001584 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001585 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001586 Width = Target->getIntWidth();
1587 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001588 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001589 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001590 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001591 Width = Target->getLongWidth();
1592 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001593 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001594 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001595 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001596 Width = Target->getLongLongWidth();
1597 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001598 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001599 case BuiltinType::Int128:
1600 case BuiltinType::UInt128:
1601 Width = 128;
1602 Align = 128; // int128_t is 128-bit aligned on all targets.
1603 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001604 case BuiltinType::Half:
1605 Width = Target->getHalfWidth();
1606 Align = Target->getHalfAlign();
1607 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001608 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getFloatWidth();
1610 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001611 break;
1612 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001613 Width = Target->getDoubleWidth();
1614 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001615 break;
1616 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001617 Width = Target->getLongDoubleWidth();
1618 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001619 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001620 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001621 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1622 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001623 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001624 case BuiltinType::ObjCId:
1625 case BuiltinType::ObjCClass:
1626 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001627 Width = Target->getPointerWidth(0);
1628 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001629 break;
Guy Benyei61054192013-02-07 10:55:47 +00001630 case BuiltinType::OCLSampler:
1631 // Samplers are modeled as integers.
1632 Width = Target->getIntWidth();
1633 Align = Target->getIntAlign();
1634 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001635 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001636 case BuiltinType::OCLImage1d:
1637 case BuiltinType::OCLImage1dArray:
1638 case BuiltinType::OCLImage1dBuffer:
1639 case BuiltinType::OCLImage2d:
1640 case BuiltinType::OCLImage2dArray:
1641 case BuiltinType::OCLImage3d:
1642 // Currently these types are pointers to opaque types.
1643 Width = Target->getPointerWidth(0);
1644 Align = Target->getPointerAlign(0);
1645 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001646 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001647 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001648 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001649 Width = Target->getPointerWidth(0);
1650 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001651 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001652 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001653 unsigned AS = getTargetAddressSpace(
1654 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001655 Width = Target->getPointerWidth(AS);
1656 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001657 break;
1658 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001659 case Type::LValueReference:
1660 case Type::RValueReference: {
1661 // alignof and sizeof should never enter this code path here, so we go
1662 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001663 unsigned AS = getTargetAddressSpace(
1664 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001665 Width = Target->getPointerWidth(AS);
1666 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001667 break;
1668 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001669 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001670 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001671 Width = Target->getPointerWidth(AS);
1672 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001673 break;
1674 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001675 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001676 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001677 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001678 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001679 }
Chris Lattner647fb222007-07-18 18:26:58 +00001680 case Type::Complex: {
1681 // Complex types have the same alignment as their elements, but twice the
1682 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001683 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1684 Width = EltInfo.Width * 2;
1685 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001686 break;
1687 }
John McCall8b07ec22010-05-15 11:32:37 +00001688 case Type::ObjCObject:
1689 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001690 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001691 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001692 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001693 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001694 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001695 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001696 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001697 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001698 break;
1699 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001700 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001701 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001702 const TagType *TT = cast<TagType>(T);
1703
1704 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001705 Width = 8;
1706 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001707 break;
1708 }
Mike Stump11289f42009-09-09 15:08:12 +00001709
David Majnemer475b25e2015-01-21 10:54:38 +00001710 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1711 const EnumDecl *ED = ET->getDecl();
1712 TypeInfo Info =
1713 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1714 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1715 Info.Align = AttrAlign;
1716 Info.AlignIsRequired = true;
1717 }
1718 return Info;
1719 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001720
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001721 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001722 const RecordDecl *RD = RT->getDecl();
1723 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001724 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001725 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001726 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001727 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001728 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001729
Chris Lattner63d2b362009-10-22 05:17:15 +00001730 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001731 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1732 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001733
Richard Smith30482bc2011-02-20 03:19:35 +00001734 case Type::Auto: {
1735 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001736 assert(!A->getDeducedType().isNull() &&
1737 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001738 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001739 }
1740
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001741 case Type::Paren:
1742 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1743
Douglas Gregoref462e62009-04-30 17:32:17 +00001744 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001745 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001746 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001747 // If the typedef has an aligned attribute on it, it overrides any computed
1748 // alignment we have. This violates the GCC documentation (which says that
1749 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001750 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001751 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001752 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001753 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001754 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001755 AlignIsRequired = Info.AlignIsRequired;
1756 }
David Majnemer34b57492014-07-30 01:30:47 +00001757 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001758 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001759 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001760
Abramo Bagnara6150c882010-05-11 21:36:43 +00001761 case Type::Elaborated:
1762 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001763
John McCall81904512011-01-06 01:58:22 +00001764 case Type::Attributed:
1765 return getTypeInfo(
1766 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1767
Eli Friedman0dfb8892011-10-06 23:00:33 +00001768 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001769 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001770 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1771 Width = Info.Width;
1772 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001773
1774 // If the size of the type doesn't exceed the platform's max
1775 // atomic promotion width, make the size and alignment more
1776 // favorable to atomic operations:
1777 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1778 // Round the size up to a power of 2.
1779 if (!llvm::isPowerOf2_64(Width))
1780 Width = llvm::NextPowerOf2(Width);
1781
1782 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001783 Align = static_cast<unsigned>(Width);
1784 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001785 }
1786
Douglas Gregoref462e62009-04-30 17:32:17 +00001787 }
Mike Stump11289f42009-09-09 15:08:12 +00001788
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001789 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001790 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001791}
1792
Alexey Bataev00396512015-07-02 03:40:19 +00001793unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1794 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1795 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1796 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1797 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1798 getTargetInfo().getABI() == "elfv1-qpx" &&
1799 T->isSpecificBuiltinType(BuiltinType::Double))
1800 SimdAlign = 256;
1801 return SimdAlign;
1802}
1803
Ken Dyckcc56c542011-01-15 18:38:59 +00001804/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1805CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1806 return CharUnits::fromQuantity(BitSize / getCharWidth());
1807}
1808
Ken Dyckb0fcc592011-02-11 01:54:29 +00001809/// toBits - Convert a size in characters to a size in characters.
1810int64_t ASTContext::toBits(CharUnits CharSize) const {
1811 return CharSize.getQuantity() * getCharWidth();
1812}
1813
Ken Dyck8c89d592009-12-22 14:23:30 +00001814/// getTypeSizeInChars - Return the size of the specified type, in characters.
1815/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001816CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001817 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001818}
Jay Foad39c79802011-01-12 09:06:06 +00001819CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001820 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001821}
1822
Ken Dycka6046ab2010-01-26 17:25:18 +00001823/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001824/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001825CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001826 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001827}
Jay Foad39c79802011-01-12 09:06:06 +00001828CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001829 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001830}
1831
Chris Lattnera3402cd2009-01-27 18:08:34 +00001832/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1833/// type for the current target in bits. This can be different than the ABI
1834/// alignment in cases where it is beneficial for performance to overalign
1835/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001836unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001837 TypeInfo TI = getTypeInfo(T);
1838 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001839
David Majnemere1544562015-04-24 01:25:05 +00001840 T = T->getBaseElementTypeUnsafe();
1841
1842 // The preferred alignment of member pointers is that of a pointer.
1843 if (T->isMemberPointerType())
1844 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1845
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001846 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1847 return ABIAlign; // Never overalign on XCore.
1848
Eli Friedman7ab09572009-05-25 21:27:19 +00001849 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001850 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001851 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001852 if (const EnumType *ET = T->getAs<EnumType>())
1853 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001854 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001855 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1856 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001857 // Don't increase the alignment if an alignment attribute was specified on a
1858 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001859 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001860 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001861
Chris Lattnera3402cd2009-01-27 18:08:34 +00001862 return ABIAlign;
1863}
1864
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001865/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1866/// for __attribute__((aligned)) on this target, to be used if no alignment
1867/// value is specified.
1868unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1869 return getTargetInfo().getDefaultAlignForAttributeAligned();
1870}
1871
Ulrich Weigandfa806422013-05-06 16:23:57 +00001872/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1873/// to a global variable of the specified type.
1874unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1875 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1876}
1877
1878/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1879/// should be given to a global variable of the specified type.
1880CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1881 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1882}
1883
David Majnemer08ef2ba2015-06-23 20:34:18 +00001884CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1885 CharUnits Offset = CharUnits::Zero();
1886 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1887 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1888 Offset += Layout->getBaseClassOffset(Base);
1889 Layout = &getASTRecordLayout(Base);
1890 }
1891 return Offset;
1892}
1893
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001894/// DeepCollectObjCIvars -
1895/// This routine first collects all declared, but not synthesized, ivars in
1896/// super class and then collects all ivars, including those synthesized for
1897/// current class. This routine is used for implementation of current class
1898/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001899///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001900void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1901 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001902 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001903 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1904 DeepCollectObjCIvars(SuperClass, false, Ivars);
1905 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001906 for (const auto *I : OI->ivars())
1907 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001908 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001909 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001910 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001911 Iv= Iv->getNextIvar())
1912 Ivars.push_back(Iv);
1913 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001914}
1915
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001916/// CollectInheritedProtocols - Collect all protocols in current class and
1917/// those inherited by it.
1918void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001919 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001920 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001921 // We can use protocol_iterator here instead of
1922 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001923 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001924 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001925 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001926
1927 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001928 for (const auto *Cat : OI->visible_categories())
1929 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001930
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001931 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1932 while (SD) {
1933 CollectInheritedProtocols(SD, Protocols);
1934 SD = SD->getSuperClass();
1935 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001936 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001937 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001938 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001939 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001940 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001941 // Insert the protocol.
1942 if (!Protocols.insert(
1943 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1944 return;
1945
1946 for (auto *Proto : OP->protocols())
1947 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001948 }
1949}
1950
Jay Foad39c79802011-01-12 09:06:06 +00001951unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001952 unsigned count = 0;
1953 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001954 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001955 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001956
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001957 // Count ivar defined in this class's implementation. This
1958 // includes synthesized ivars.
1959 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001960 count += ImplDecl->ivar_size();
1961
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001962 return count;
1963}
1964
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001965bool ASTContext::isSentinelNullExpr(const Expr *E) {
1966 if (!E)
1967 return false;
1968
1969 // nullptr_t is always treated as null.
1970 if (E->getType()->isNullPtrType()) return true;
1971
1972 if (E->getType()->isAnyPointerType() &&
1973 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1974 Expr::NPC_ValueDependentIsNull))
1975 return true;
1976
1977 // Unfortunately, __null has type 'int'.
1978 if (isa<GNUNullExpr>(E)) return true;
1979
1980 return false;
1981}
1982
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001983/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1984ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1985 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1986 I = ObjCImpls.find(D);
1987 if (I != ObjCImpls.end())
1988 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001989 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001990}
1991/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1992ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1993 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1994 I = ObjCImpls.find(D);
1995 if (I != ObjCImpls.end())
1996 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001997 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001998}
1999
2000/// \brief Set the implementation of ObjCInterfaceDecl.
2001void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2002 ObjCImplementationDecl *ImplD) {
2003 assert(IFaceD && ImplD && "Passed null params");
2004 ObjCImpls[IFaceD] = ImplD;
2005}
2006/// \brief Set the implementation of ObjCCategoryDecl.
2007void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2008 ObjCCategoryImplDecl *ImplD) {
2009 assert(CatD && ImplD && "Passed null params");
2010 ObjCImpls[CatD] = ImplD;
2011}
2012
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002013const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2014 const NamedDecl *ND) const {
2015 if (const ObjCInterfaceDecl *ID =
2016 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002017 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002018 if (const ObjCCategoryDecl *CD =
2019 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002020 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002021 if (const ObjCImplDecl *IMD =
2022 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002023 return IMD->getClassInterface();
2024
Craig Topper36250ad2014-05-12 05:36:57 +00002025 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002026}
2027
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002028/// \brief Get the copy initialization expression of VarDecl,or NULL if
2029/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002030Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002031 assert(VD && "Passed null params");
2032 assert(VD->hasAttr<BlocksAttr>() &&
2033 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002034 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002035 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002036 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002037}
2038
2039/// \brief Set the copy inialization expression of a block var decl.
2040void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2041 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002042 assert(VD->hasAttr<BlocksAttr>() &&
2043 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002044 BlockVarCopyInits[VD] = Init;
2045}
2046
John McCallbcd03502009-12-07 02:54:59 +00002047TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002048 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002049 if (!DataSize)
2050 DataSize = TypeLoc::getFullDataSizeForType(T);
2051 else
2052 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002053 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002054
John McCallbcd03502009-12-07 02:54:59 +00002055 TypeSourceInfo *TInfo =
2056 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2057 new (TInfo) TypeSourceInfo(T);
2058 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002059}
2060
John McCallbcd03502009-12-07 02:54:59 +00002061TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002062 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002063 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002064 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002065 return DI;
2066}
2067
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002068const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002069ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002070 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002071}
2072
2073const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002074ASTContext::getASTObjCImplementationLayout(
2075 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002076 return getObjCLayout(D->getClassInterface(), D);
2077}
2078
Chris Lattner983a8bb2007-07-13 22:13:22 +00002079//===----------------------------------------------------------------------===//
2080// Type creation/memoization methods
2081//===----------------------------------------------------------------------===//
2082
Jay Foad39c79802011-01-12 09:06:06 +00002083QualType
John McCall33ddac02011-01-19 10:06:00 +00002084ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2085 unsigned fastQuals = quals.getFastQualifiers();
2086 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002087
2088 // Check if we've already instantiated this type.
2089 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002090 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002091 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002092 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2093 assert(eq->getQualifiers() == quals);
2094 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002095 }
2096
John McCall33ddac02011-01-19 10:06:00 +00002097 // If the base type is not canonical, make the appropriate canonical type.
2098 QualType canon;
2099 if (!baseType->isCanonicalUnqualified()) {
2100 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002101 canonSplit.Quals.addConsistentQualifiers(quals);
2102 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002103
2104 // Re-find the insert position.
2105 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2106 }
2107
2108 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2109 ExtQualNodes.InsertNode(eq, insertPos);
2110 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002111}
2112
Jay Foad39c79802011-01-12 09:06:06 +00002113QualType
2114ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002115 QualType CanT = getCanonicalType(T);
2116 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002117 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002118
John McCall8ccfcb52009-09-24 19:53:00 +00002119 // If we are composing extended qualifiers together, merge together
2120 // into one ExtQuals node.
2121 QualifierCollector Quals;
2122 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002123
John McCall8ccfcb52009-09-24 19:53:00 +00002124 // If this type already has an address space specified, it cannot get
2125 // another one.
2126 assert(!Quals.hasAddressSpace() &&
2127 "Type cannot be in multiple addr spaces!");
2128 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002129
John McCall8ccfcb52009-09-24 19:53:00 +00002130 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002131}
2132
Chris Lattnerd60183d2009-02-18 22:53:11 +00002133QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002134 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002135 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002136 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002137 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002138
John McCall53fa7142010-12-24 02:08:15 +00002139 if (const PointerType *ptr = T->getAs<PointerType>()) {
2140 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002141 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002142 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2143 return getPointerType(ResultType);
2144 }
2145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
John McCall8ccfcb52009-09-24 19:53:00 +00002147 // If we are composing extended qualifiers together, merge together
2148 // into one ExtQuals node.
2149 QualifierCollector Quals;
2150 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002151
John McCall8ccfcb52009-09-24 19:53:00 +00002152 // If this type already has an ObjCGC specified, it cannot get
2153 // another one.
2154 assert(!Quals.hasObjCGCAttr() &&
2155 "Type cannot have multiple ObjCGCs!");
2156 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002157
John McCall8ccfcb52009-09-24 19:53:00 +00002158 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002159}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002160
John McCall4f5019e2010-12-19 02:44:49 +00002161const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2162 FunctionType::ExtInfo Info) {
2163 if (T->getExtInfo() == Info)
2164 return T;
2165
2166 QualType Result;
2167 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002168 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002169 } else {
2170 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2171 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2172 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002173 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002174 }
2175
2176 return cast<FunctionType>(Result.getTypePtr());
2177}
2178
Richard Smith2a7d4812013-05-04 07:00:32 +00002179void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2180 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002181 FD = FD->getMostRecentDecl();
2182 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002183 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2184 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002185 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002186 if (FunctionDecl *Next = FD->getPreviousDecl())
2187 FD = Next;
2188 else
2189 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002190 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002191 if (ASTMutationListener *L = getASTMutationListener())
2192 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002193}
2194
Richard Smith0b3a4622014-11-13 20:01:57 +00002195/// Get a function type and produce the equivalent function type with the
2196/// specified exception specification. Type sugar that can be present on a
2197/// declaration of a function with an exception specification is permitted
2198/// and preserved. Other type sugar (for instance, typedefs) is not.
2199static QualType getFunctionTypeWithExceptionSpec(
2200 ASTContext &Context, QualType Orig,
2201 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2202 // Might have some parens.
2203 if (auto *PT = dyn_cast<ParenType>(Orig))
2204 return Context.getParenType(
2205 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2206
2207 // Might have a calling-convention attribute.
2208 if (auto *AT = dyn_cast<AttributedType>(Orig))
2209 return Context.getAttributedType(
2210 AT->getAttrKind(),
2211 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2212 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2213 ESI));
2214
2215 // Anything else must be a function type. Rebuild it with the new exception
2216 // specification.
2217 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2218 return Context.getFunctionType(
2219 Proto->getReturnType(), Proto->getParamTypes(),
2220 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2221}
2222
2223void ASTContext::adjustExceptionSpec(
2224 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2225 bool AsWritten) {
2226 // Update the type.
2227 QualType Updated =
2228 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2229 FD->setType(Updated);
2230
2231 if (!AsWritten)
2232 return;
2233
2234 // Update the type in the type source information too.
2235 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2236 // If the type and the type-as-written differ, we may need to update
2237 // the type-as-written too.
2238 if (TSInfo->getType() != FD->getType())
2239 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2240
2241 // FIXME: When we get proper type location information for exceptions,
2242 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2243 // up the TypeSourceInfo;
2244 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2245 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2246 "TypeLoc size mismatch from updating exception specification");
2247 TSInfo->overrideType(Updated);
2248 }
2249}
2250
Chris Lattnerc6395932007-06-22 20:56:16 +00002251/// getComplexType - Return the uniqued reference to the type for a complex
2252/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002253QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002254 // Unique pointers, to guarantee there is only one pointer of a particular
2255 // structure.
2256 llvm::FoldingSetNodeID ID;
2257 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002258
Craig Topper36250ad2014-05-12 05:36:57 +00002259 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002260 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2261 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattnerc6395932007-06-22 20:56:16 +00002263 // If the pointee type isn't canonical, this won't be a canonical type either,
2264 // so fill in the canonical type field.
2265 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002266 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002267 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerc6395932007-06-22 20:56:16 +00002269 // Get the new insert position for the node we care about.
2270 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002271 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002272 }
John McCall90d1c2d2009-09-24 23:30:46 +00002273 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002274 Types.push_back(New);
2275 ComplexTypes.InsertNode(New, InsertPos);
2276 return QualType(New, 0);
2277}
2278
Chris Lattner970e54e2006-11-12 00:37:36 +00002279/// getPointerType - Return the uniqued reference to the type for a pointer to
2280/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002281QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002282 // Unique pointers, to guarantee there is only one pointer of a particular
2283 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002284 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002285 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002286
Craig Topper36250ad2014-05-12 05:36:57 +00002287 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002288 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002289 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002290
Chris Lattner7ccecb92006-11-12 08:50:50 +00002291 // If the pointee type isn't canonical, this won't be a canonical type either,
2292 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002293 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002294 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002295 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002296
Bob Wilsonc8541f22013-03-15 17:12:43 +00002297 // Get the new insert position for the node we care about.
2298 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002299 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002300 }
John McCall90d1c2d2009-09-24 23:30:46 +00002301 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002302 Types.push_back(New);
2303 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002304 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002305}
2306
Reid Kleckner0503a872013-12-05 01:23:43 +00002307QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2308 llvm::FoldingSetNodeID ID;
2309 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002310 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002311 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2312 if (AT)
2313 return QualType(AT, 0);
2314
2315 QualType Canonical = getCanonicalType(New);
2316
2317 // Get the new insert position for the node we care about.
2318 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002319 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002320
2321 AT = new (*this, TypeAlignment)
2322 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2323 Types.push_back(AT);
2324 AdjustedTypes.InsertNode(AT, InsertPos);
2325 return QualType(AT, 0);
2326}
2327
Reid Kleckner8a365022013-06-24 17:51:48 +00002328QualType ASTContext::getDecayedType(QualType T) const {
2329 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2330
Reid Kleckner8a365022013-06-24 17:51:48 +00002331 QualType Decayed;
2332
2333 // C99 6.7.5.3p7:
2334 // A declaration of a parameter as "array of type" shall be
2335 // adjusted to "qualified pointer to type", where the type
2336 // qualifiers (if any) are those specified within the [ and ] of
2337 // the array type derivation.
2338 if (T->isArrayType())
2339 Decayed = getArrayDecayedType(T);
2340
2341 // C99 6.7.5.3p8:
2342 // A declaration of a parameter as "function returning type"
2343 // shall be adjusted to "pointer to function returning type", as
2344 // in 6.3.2.1.
2345 if (T->isFunctionType())
2346 Decayed = getPointerType(T);
2347
Reid Kleckner0503a872013-12-05 01:23:43 +00002348 llvm::FoldingSetNodeID ID;
2349 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002350 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002351 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2352 if (AT)
2353 return QualType(AT, 0);
2354
Reid Kleckner8a365022013-06-24 17:51:48 +00002355 QualType Canonical = getCanonicalType(Decayed);
2356
2357 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002358 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002359 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002360
Reid Kleckner0503a872013-12-05 01:23:43 +00002361 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2362 Types.push_back(AT);
2363 AdjustedTypes.InsertNode(AT, InsertPos);
2364 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002365}
2366
Mike Stump11289f42009-09-09 15:08:12 +00002367/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002368/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002369QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002370 assert(T->isFunctionType() && "block of function types only");
2371 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002372 // structure.
2373 llvm::FoldingSetNodeID ID;
2374 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002375
Craig Topper36250ad2014-05-12 05:36:57 +00002376 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002377 if (BlockPointerType *PT =
2378 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2379 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002380
2381 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002382 // type either so fill in the canonical type field.
2383 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002384 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002385 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002386
Steve Naroffec33ed92008-08-27 16:04:49 +00002387 // Get the new insert position for the node we care about.
2388 BlockPointerType *NewIP =
2389 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002390 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002391 }
John McCall90d1c2d2009-09-24 23:30:46 +00002392 BlockPointerType *New
2393 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002394 Types.push_back(New);
2395 BlockPointerTypes.InsertNode(New, InsertPos);
2396 return QualType(New, 0);
2397}
2398
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002399/// getLValueReferenceType - Return the uniqued reference to the type for an
2400/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002401QualType
2402ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002403 assert(getCanonicalType(T) != OverloadTy &&
2404 "Unresolved overloaded function type");
2405
Bill Wendling3708c182007-05-27 10:15:43 +00002406 // Unique pointers, to guarantee there is only one pointer of a particular
2407 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002408 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002409 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002410
Craig Topper36250ad2014-05-12 05:36:57 +00002411 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002412 if (LValueReferenceType *RT =
2413 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002414 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002415
John McCallfc93cf92009-10-22 22:37:11 +00002416 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2417
Bill Wendling3708c182007-05-27 10:15:43 +00002418 // If the referencee type isn't canonical, this won't be a canonical type
2419 // either, so fill in the canonical type field.
2420 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002421 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2422 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2423 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002424
Bill Wendling3708c182007-05-27 10:15:43 +00002425 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002426 LValueReferenceType *NewIP =
2427 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002428 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002429 }
2430
John McCall90d1c2d2009-09-24 23:30:46 +00002431 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002432 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2433 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002434 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002435 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002436
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002437 return QualType(New, 0);
2438}
2439
2440/// getRValueReferenceType - Return the uniqued reference to the type for an
2441/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002442QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002443 // Unique pointers, to guarantee there is only one pointer of a particular
2444 // structure.
2445 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002446 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002447
Craig Topper36250ad2014-05-12 05:36:57 +00002448 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002449 if (RValueReferenceType *RT =
2450 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2451 return QualType(RT, 0);
2452
John McCallfc93cf92009-10-22 22:37:11 +00002453 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2454
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002455 // If the referencee type isn't canonical, this won't be a canonical type
2456 // either, so fill in the canonical type field.
2457 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002458 if (InnerRef || !T.isCanonical()) {
2459 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2460 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002461
2462 // Get the new insert position for the node we care about.
2463 RValueReferenceType *NewIP =
2464 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002465 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002466 }
2467
John McCall90d1c2d2009-09-24 23:30:46 +00002468 RValueReferenceType *New
2469 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002470 Types.push_back(New);
2471 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002472 return QualType(New, 0);
2473}
2474
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002475/// getMemberPointerType - Return the uniqued reference to the type for a
2476/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002477QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002478 // Unique pointers, to guarantee there is only one pointer of a particular
2479 // structure.
2480 llvm::FoldingSetNodeID ID;
2481 MemberPointerType::Profile(ID, T, Cls);
2482
Craig Topper36250ad2014-05-12 05:36:57 +00002483 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002484 if (MemberPointerType *PT =
2485 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2486 return QualType(PT, 0);
2487
2488 // If the pointee or class type isn't canonical, this won't be a canonical
2489 // type either, so fill in the canonical type field.
2490 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002491 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002492 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2493
2494 // Get the new insert position for the node we care about.
2495 MemberPointerType *NewIP =
2496 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002497 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002498 }
John McCall90d1c2d2009-09-24 23:30:46 +00002499 MemberPointerType *New
2500 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002501 Types.push_back(New);
2502 MemberPointerTypes.InsertNode(New, InsertPos);
2503 return QualType(New, 0);
2504}
2505
Mike Stump11289f42009-09-09 15:08:12 +00002506/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002507/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002508QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002509 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002510 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002511 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002512 assert((EltTy->isDependentType() ||
2513 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002514 "Constant array of VLAs is illegal!");
2515
Chris Lattnere2df3f92009-05-13 04:12:56 +00002516 // Convert the array size into a canonical width matching the pointer size for
2517 // the target.
2518 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002519 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002520 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002521
Chris Lattner23b7eb62007-06-15 23:05:46 +00002522 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002523 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002524
Craig Topper36250ad2014-05-12 05:36:57 +00002525 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002526 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002527 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002528 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002529
John McCall33ddac02011-01-19 10:06:00 +00002530 // If the element type isn't canonical or has qualifiers, this won't
2531 // be a canonical type either, so fill in the canonical type field.
2532 QualType Canon;
2533 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2534 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002535 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002536 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002537 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002538
Chris Lattner36f8e652007-01-27 08:31:04 +00002539 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002540 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002541 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002542 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002543 }
Mike Stump11289f42009-09-09 15:08:12 +00002544
John McCall90d1c2d2009-09-24 23:30:46 +00002545 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002546 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002547 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002548 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002549 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002550}
2551
John McCall06549462011-01-18 08:40:38 +00002552/// getVariableArrayDecayedType - Turns the given type, which may be
2553/// variably-modified, into the corresponding type with all the known
2554/// sizes replaced with [*].
2555QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2556 // Vastly most common case.
2557 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002558
John McCall06549462011-01-18 08:40:38 +00002559 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002560
John McCall06549462011-01-18 08:40:38 +00002561 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002562 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002563 switch (ty->getTypeClass()) {
2564#define TYPE(Class, Base)
2565#define ABSTRACT_TYPE(Class, Base)
2566#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2567#include "clang/AST/TypeNodes.def"
2568 llvm_unreachable("didn't desugar past all non-canonical types?");
2569
2570 // These types should never be variably-modified.
2571 case Type::Builtin:
2572 case Type::Complex:
2573 case Type::Vector:
2574 case Type::ExtVector:
2575 case Type::DependentSizedExtVector:
2576 case Type::ObjCObject:
2577 case Type::ObjCInterface:
2578 case Type::ObjCObjectPointer:
2579 case Type::Record:
2580 case Type::Enum:
2581 case Type::UnresolvedUsing:
2582 case Type::TypeOfExpr:
2583 case Type::TypeOf:
2584 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002585 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002586 case Type::DependentName:
2587 case Type::InjectedClassName:
2588 case Type::TemplateSpecialization:
2589 case Type::DependentTemplateSpecialization:
2590 case Type::TemplateTypeParm:
2591 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002592 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002593 case Type::PackExpansion:
2594 llvm_unreachable("type should never be variably-modified");
2595
2596 // These types can be variably-modified but should never need to
2597 // further decay.
2598 case Type::FunctionNoProto:
2599 case Type::FunctionProto:
2600 case Type::BlockPointer:
2601 case Type::MemberPointer:
2602 return type;
2603
2604 // These types can be variably-modified. All these modifications
2605 // preserve structure except as noted by comments.
2606 // TODO: if we ever care about optimizing VLAs, there are no-op
2607 // optimizations available here.
2608 case Type::Pointer:
2609 result = getPointerType(getVariableArrayDecayedType(
2610 cast<PointerType>(ty)->getPointeeType()));
2611 break;
2612
2613 case Type::LValueReference: {
2614 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2615 result = getLValueReferenceType(
2616 getVariableArrayDecayedType(lv->getPointeeType()),
2617 lv->isSpelledAsLValue());
2618 break;
2619 }
2620
2621 case Type::RValueReference: {
2622 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2623 result = getRValueReferenceType(
2624 getVariableArrayDecayedType(lv->getPointeeType()));
2625 break;
2626 }
2627
Eli Friedman0dfb8892011-10-06 23:00:33 +00002628 case Type::Atomic: {
2629 const AtomicType *at = cast<AtomicType>(ty);
2630 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2631 break;
2632 }
2633
John McCall06549462011-01-18 08:40:38 +00002634 case Type::ConstantArray: {
2635 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2636 result = getConstantArrayType(
2637 getVariableArrayDecayedType(cat->getElementType()),
2638 cat->getSize(),
2639 cat->getSizeModifier(),
2640 cat->getIndexTypeCVRQualifiers());
2641 break;
2642 }
2643
2644 case Type::DependentSizedArray: {
2645 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2646 result = getDependentSizedArrayType(
2647 getVariableArrayDecayedType(dat->getElementType()),
2648 dat->getSizeExpr(),
2649 dat->getSizeModifier(),
2650 dat->getIndexTypeCVRQualifiers(),
2651 dat->getBracketsRange());
2652 break;
2653 }
2654
2655 // Turn incomplete types into [*] types.
2656 case Type::IncompleteArray: {
2657 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2658 result = getVariableArrayType(
2659 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002660 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002661 ArrayType::Normal,
2662 iat->getIndexTypeCVRQualifiers(),
2663 SourceRange());
2664 break;
2665 }
2666
2667 // Turn VLA types into [*] types.
2668 case Type::VariableArray: {
2669 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2670 result = getVariableArrayType(
2671 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002672 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002673 ArrayType::Star,
2674 vat->getIndexTypeCVRQualifiers(),
2675 vat->getBracketsRange());
2676 break;
2677 }
2678 }
2679
2680 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002681 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002682}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002683
Steve Naroffcadebd02007-08-30 18:14:25 +00002684/// getVariableArrayType - Returns a non-unique reference to the type for a
2685/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002686QualType ASTContext::getVariableArrayType(QualType EltTy,
2687 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002688 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002689 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002690 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002691 // Since we don't unique expressions, it isn't possible to unique VLA's
2692 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002693 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002694
John McCall33ddac02011-01-19 10:06:00 +00002695 // Be sure to pull qualifiers off the element type.
2696 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2697 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002698 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002699 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002700 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002701 }
2702
John McCall90d1c2d2009-09-24 23:30:46 +00002703 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002704 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002705
2706 VariableArrayTypes.push_back(New);
2707 Types.push_back(New);
2708 return QualType(New, 0);
2709}
2710
Douglas Gregor4619e432008-12-05 23:32:09 +00002711/// getDependentSizedArrayType - Returns a non-unique reference to
2712/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002713/// type.
John McCall33ddac02011-01-19 10:06:00 +00002714QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2715 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002716 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002717 unsigned elementTypeQuals,
2718 SourceRange brackets) const {
2719 assert((!numElements || numElements->isTypeDependent() ||
2720 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002721 "Size must be type- or value-dependent!");
2722
John McCall33ddac02011-01-19 10:06:00 +00002723 // Dependently-sized array types that do not have a specified number
2724 // of elements will have their sizes deduced from a dependent
2725 // initializer. We do no canonicalization here at all, which is okay
2726 // because they can't be used in most locations.
2727 if (!numElements) {
2728 DependentSizedArrayType *newType
2729 = new (*this, TypeAlignment)
2730 DependentSizedArrayType(*this, elementType, QualType(),
2731 numElements, ASM, elementTypeQuals,
2732 brackets);
2733 Types.push_back(newType);
2734 return QualType(newType, 0);
2735 }
2736
2737 // Otherwise, we actually build a new type every time, but we
2738 // also build a canonical type.
2739
2740 SplitQualType canonElementType = getCanonicalType(elementType).split();
2741
Craig Topper36250ad2014-05-12 05:36:57 +00002742 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002743 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002744 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002745 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002746 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002747
John McCall33ddac02011-01-19 10:06:00 +00002748 // Look for an existing type with these properties.
2749 DependentSizedArrayType *canonTy =
2750 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002751
John McCall33ddac02011-01-19 10:06:00 +00002752 // If we don't have one, build one.
2753 if (!canonTy) {
2754 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002755 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002756 QualType(), numElements, ASM, elementTypeQuals,
2757 brackets);
2758 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2759 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002760 }
2761
John McCall33ddac02011-01-19 10:06:00 +00002762 // Apply qualifiers from the element type to the array.
2763 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002764 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002765
David Majnemer16a74702015-07-24 05:54:19 +00002766 // If we didn't need extra canonicalization for the element type or the size
2767 // expression, then just use that as our result.
2768 if (QualType(canonElementType.Ty, 0) == elementType &&
2769 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002770 return canon;
2771
2772 // Otherwise, we need to build a type which follows the spelling
2773 // of the element type.
2774 DependentSizedArrayType *sugaredType
2775 = new (*this, TypeAlignment)
2776 DependentSizedArrayType(*this, elementType, canon, numElements,
2777 ASM, elementTypeQuals, brackets);
2778 Types.push_back(sugaredType);
2779 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002780}
2781
John McCall33ddac02011-01-19 10:06:00 +00002782QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002783 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002784 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002785 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002786 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002787
Craig Topper36250ad2014-05-12 05:36:57 +00002788 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002789 if (IncompleteArrayType *iat =
2790 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2791 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002792
2793 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002794 // either, so fill in the canonical type field. We also have to pull
2795 // qualifiers off the element type.
2796 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002797
John McCall33ddac02011-01-19 10:06:00 +00002798 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2799 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002800 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002801 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002802 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002803
2804 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002805 IncompleteArrayType *existing =
2806 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2807 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002808 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002809
John McCall33ddac02011-01-19 10:06:00 +00002810 IncompleteArrayType *newType = new (*this, TypeAlignment)
2811 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002812
John McCall33ddac02011-01-19 10:06:00 +00002813 IncompleteArrayTypes.InsertNode(newType, insertPos);
2814 Types.push_back(newType);
2815 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002816}
2817
Steve Naroff91fcddb2007-07-18 18:00:27 +00002818/// getVectorType - Return the unique reference to a vector type of
2819/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002820QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002821 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002822 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002823
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002824 // Check if we've already instantiated a vector of this type.
2825 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002826 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002827
Craig Topper36250ad2014-05-12 05:36:57 +00002828 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002829 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2830 return QualType(VTP, 0);
2831
2832 // If the element type isn't canonical, this won't be a canonical type either,
2833 // so fill in the canonical type field.
2834 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002835 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002836 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002837
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002838 // Get the new insert position for the node we care about.
2839 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002840 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002841 }
John McCall90d1c2d2009-09-24 23:30:46 +00002842 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002843 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002844 VectorTypes.InsertNode(New, InsertPos);
2845 Types.push_back(New);
2846 return QualType(New, 0);
2847}
2848
Nate Begemance4d7fc2008-04-18 23:10:10 +00002849/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002850/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002851QualType
2852ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002853 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002854
Steve Naroff91fcddb2007-07-18 18:00:27 +00002855 // Check if we've already instantiated a vector of this type.
2856 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002857 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002858 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002859 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002860 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2861 return QualType(VTP, 0);
2862
2863 // If the element type isn't canonical, this won't be a canonical type either,
2864 // so fill in the canonical type field.
2865 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002866 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002867 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002868
Steve Naroff91fcddb2007-07-18 18:00:27 +00002869 // Get the new insert position for the node we care about.
2870 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002871 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002872 }
John McCall90d1c2d2009-09-24 23:30:46 +00002873 ExtVectorType *New = new (*this, TypeAlignment)
2874 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002875 VectorTypes.InsertNode(New, InsertPos);
2876 Types.push_back(New);
2877 return QualType(New, 0);
2878}
2879
Jay Foad39c79802011-01-12 09:06:06 +00002880QualType
2881ASTContext::getDependentSizedExtVectorType(QualType vecType,
2882 Expr *SizeExpr,
2883 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002884 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002885 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002886 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002887
Craig Topper36250ad2014-05-12 05:36:57 +00002888 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002889 DependentSizedExtVectorType *Canon
2890 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2891 DependentSizedExtVectorType *New;
2892 if (Canon) {
2893 // We already have a canonical version of this array type; use it as
2894 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002895 New = new (*this, TypeAlignment)
2896 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2897 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002898 } else {
2899 QualType CanonVecTy = getCanonicalType(vecType);
2900 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002901 New = new (*this, TypeAlignment)
2902 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2903 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002904
2905 DependentSizedExtVectorType *CanonCheck
2906 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2907 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2908 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002909 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2910 } else {
2911 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2912 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002913 New = new (*this, TypeAlignment)
2914 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002915 }
2916 }
Mike Stump11289f42009-09-09 15:08:12 +00002917
Douglas Gregor758a8692009-06-17 21:51:59 +00002918 Types.push_back(New);
2919 return QualType(New, 0);
2920}
2921
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002922/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002923///
Jay Foad39c79802011-01-12 09:06:06 +00002924QualType
2925ASTContext::getFunctionNoProtoType(QualType ResultTy,
2926 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002927 const CallingConv CallConv = Info.getCC();
2928
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002929 // Unique functions, to guarantee there is only one function of a particular
2930 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002931 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002932 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002933
Craig Topper36250ad2014-05-12 05:36:57 +00002934 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002935 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002936 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002937 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002938
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002939 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002940 if (!ResultTy.isCanonical()) {
2941 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002942
Chris Lattner47955de2007-01-27 08:37:20 +00002943 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002944 FunctionNoProtoType *NewIP =
2945 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002946 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002947 }
Mike Stump11289f42009-09-09 15:08:12 +00002948
Roman Divacky65b88cd2011-03-01 17:40:53 +00002949 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002950 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002951 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002952 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002953 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002954 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002955}
2956
Douglas Gregorcd780372013-01-17 23:36:45 +00002957/// \brief Determine whether \p T is canonical as the result type of a function.
2958static bool isCanonicalResultType(QualType T) {
2959 return T.isCanonical() &&
2960 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2961 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2962}
2963
Jay Foad39c79802011-01-12 09:06:06 +00002964QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002965ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002966 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002967 size_t NumArgs = ArgArray.size();
2968
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002969 // Unique functions, to guarantee there is only one function of a particular
2970 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002971 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002972 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2973 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002974
Craig Topper36250ad2014-05-12 05:36:57 +00002975 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002976 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002977 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002978 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002979
2980 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002981 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002982 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002983 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002984 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002985 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002986 isCanonical = false;
2987
2988 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002989 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002990 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002991 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002992 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002993 CanonicalArgs.reserve(NumArgs);
2994 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002995 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002996
John McCalldb40c7f2010-12-14 08:05:40 +00002997 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002998 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002999 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003000
Douglas Gregorcd780372013-01-17 23:36:45 +00003001 // Result types do not have ARC lifetime qualifiers.
3002 QualType CanResultTy = getCanonicalType(ResultTy);
3003 if (ResultTy.getQualifiers().hasObjCLifetime()) {
3004 Qualifiers Qs = CanResultTy.getQualifiers();
3005 Qs.removeObjCLifetime();
3006 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
3007 }
3008
Jordan Rose5c382722013-03-08 21:51:21 +00003009 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003010
Chris Lattnerfd4de792007-01-27 01:15:32 +00003011 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003012 FunctionProtoType *NewIP =
3013 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003014 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003015 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003016
John McCall31168b02011-06-15 23:02:42 +00003017 // FunctionProtoType objects are allocated with extra bytes after
3018 // them for three variable size arrays at the end:
3019 // - parameter types
3020 // - exception types
3021 // - consumed-arguments flags
3022 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003023 // expression, or information used to resolve the exception
3024 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003025 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003026 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003027 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3028 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3029 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003030 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003031 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003032 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003033 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003034 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003035 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003036 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003037 Size += NumArgs * sizeof(bool);
3038
John McCalldb40c7f2010-12-14 08:05:40 +00003039 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003040 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003041 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003042 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003043 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003044 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003045}
Chris Lattneref51c202006-11-10 07:17:23 +00003046
John McCalle78aac42010-03-10 03:28:59 +00003047#ifndef NDEBUG
3048static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3049 if (!isa<CXXRecordDecl>(D)) return false;
3050 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3051 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3052 return true;
3053 if (RD->getDescribedClassTemplate() &&
3054 !isa<ClassTemplateSpecializationDecl>(RD))
3055 return true;
3056 return false;
3057}
3058#endif
3059
3060/// getInjectedClassNameType - Return the unique reference to the
3061/// injected class name type for the specified templated declaration.
3062QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003063 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003064 assert(NeedsInjectedClassNameType(Decl));
3065 if (Decl->TypeForDecl) {
3066 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003067 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003068 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3069 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3070 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3071 } else {
John McCall424cec92011-01-19 06:33:43 +00003072 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003073 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003074 Decl->TypeForDecl = newType;
3075 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003076 }
3077 return QualType(Decl->TypeForDecl, 0);
3078}
3079
Douglas Gregor83a586e2008-04-13 21:07:44 +00003080/// getTypeDeclType - Return the unique reference to the type for the
3081/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003082QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003083 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003084 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003085
Richard Smithdda56e42011-04-15 14:24:37 +00003086 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003087 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003088
John McCall96f0b5f2010-03-10 06:48:02 +00003089 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3090 "Template type parameter types are always available.");
3091
John McCall81e38502010-02-16 03:57:14 +00003092 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003093 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003094 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003095 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003096 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003097 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003098 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003099 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003100 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003101 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3102 Decl->TypeForDecl = newType;
3103 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003104 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003105 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003106
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003107 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003108}
3109
Chris Lattner32d920b2007-01-26 02:01:53 +00003110/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003111/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003112QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003113ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3114 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003115 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003116
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003117 if (Canonical.isNull())
3118 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003119 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003120 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003121 Decl->TypeForDecl = newType;
3122 Types.push_back(newType);
3123 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003124}
3125
Jay Foad39c79802011-01-12 09:06:06 +00003126QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003127 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3128
Douglas Gregorec9fd132012-01-14 16:38:05 +00003129 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003130 if (PrevDecl->TypeForDecl)
3131 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3132
John McCall424cec92011-01-19 06:33:43 +00003133 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3134 Decl->TypeForDecl = newType;
3135 Types.push_back(newType);
3136 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003137}
3138
Jay Foad39c79802011-01-12 09:06:06 +00003139QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003140 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3141
Douglas Gregorec9fd132012-01-14 16:38:05 +00003142 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003143 if (PrevDecl->TypeForDecl)
3144 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3145
John McCall424cec92011-01-19 06:33:43 +00003146 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3147 Decl->TypeForDecl = newType;
3148 Types.push_back(newType);
3149 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003150}
3151
John McCall81904512011-01-06 01:58:22 +00003152QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3153 QualType modifiedType,
3154 QualType equivalentType) {
3155 llvm::FoldingSetNodeID id;
3156 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3157
Craig Topper36250ad2014-05-12 05:36:57 +00003158 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003159 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3160 if (type) return QualType(type, 0);
3161
3162 QualType canon = getCanonicalType(equivalentType);
3163 type = new (*this, TypeAlignment)
3164 AttributedType(canon, attrKind, modifiedType, equivalentType);
3165
3166 Types.push_back(type);
3167 AttributedTypes.InsertNode(type, insertPos);
3168
3169 return QualType(type, 0);
3170}
3171
3172
John McCallcebee162009-10-18 09:09:24 +00003173/// \brief Retrieve a substitution-result type.
3174QualType
3175ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003176 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003177 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003178 && "replacement types must always be canonical");
3179
3180 llvm::FoldingSetNodeID ID;
3181 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003182 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003183 SubstTemplateTypeParmType *SubstParm
3184 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3185
3186 if (!SubstParm) {
3187 SubstParm = new (*this, TypeAlignment)
3188 SubstTemplateTypeParmType(Parm, Replacement);
3189 Types.push_back(SubstParm);
3190 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3191 }
3192
3193 return QualType(SubstParm, 0);
3194}
3195
Douglas Gregorada4b792011-01-14 02:55:32 +00003196/// \brief Retrieve a
3197QualType ASTContext::getSubstTemplateTypeParmPackType(
3198 const TemplateTypeParmType *Parm,
3199 const TemplateArgument &ArgPack) {
3200#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003201 for (const auto &P : ArgPack.pack_elements()) {
3202 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3203 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003204 }
3205#endif
3206
3207 llvm::FoldingSetNodeID ID;
3208 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003209 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003210 if (SubstTemplateTypeParmPackType *SubstParm
3211 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3212 return QualType(SubstParm, 0);
3213
3214 QualType Canon;
3215 if (!Parm->isCanonicalUnqualified()) {
3216 Canon = getCanonicalType(QualType(Parm, 0));
3217 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3218 ArgPack);
3219 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3220 }
3221
3222 SubstTemplateTypeParmPackType *SubstParm
3223 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3224 ArgPack);
3225 Types.push_back(SubstParm);
3226 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3227 return QualType(SubstParm, 0);
3228}
3229
Douglas Gregoreff93e02009-02-05 23:33:38 +00003230/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003231/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003232/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003233QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003234 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003235 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003236 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003237 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003238 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003239 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003240 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3241
3242 if (TypeParm)
3243 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003244
Chandler Carruth08836322011-05-01 00:51:33 +00003245 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003246 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003247 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003248
3249 TemplateTypeParmType *TypeCheck
3250 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3251 assert(!TypeCheck && "Template type parameter canonical type broken");
3252 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003253 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003254 TypeParm = new (*this, TypeAlignment)
3255 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003256
3257 Types.push_back(TypeParm);
3258 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3259
3260 return QualType(TypeParm, 0);
3261}
3262
John McCalle78aac42010-03-10 03:28:59 +00003263TypeSourceInfo *
3264ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3265 SourceLocation NameLoc,
3266 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003267 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003268 assert(!Name.getAsDependentTemplateName() &&
3269 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003270 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003271
3272 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003273 TemplateSpecializationTypeLoc TL =
3274 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003275 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003276 TL.setTemplateNameLoc(NameLoc);
3277 TL.setLAngleLoc(Args.getLAngleLoc());
3278 TL.setRAngleLoc(Args.getRAngleLoc());
3279 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3280 TL.setArgLocInfo(i, Args[i].getLocInfo());
3281 return DI;
3282}
3283
Mike Stump11289f42009-09-09 15:08:12 +00003284QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003285ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003286 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003287 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003288 assert(!Template.getAsDependentTemplateName() &&
3289 "No dependent template names here!");
3290
John McCall6b51f282009-11-23 01:53:49 +00003291 unsigned NumArgs = Args.size();
3292
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003293 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003294 ArgVec.reserve(NumArgs);
3295 for (unsigned i = 0; i != NumArgs; ++i)
3296 ArgVec.push_back(Args[i].getArgument());
3297
John McCall2408e322010-04-27 00:57:59 +00003298 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003299 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003300}
3301
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003302#ifndef NDEBUG
3303static bool hasAnyPackExpansions(const TemplateArgument *Args,
3304 unsigned NumArgs) {
3305 for (unsigned I = 0; I != NumArgs; ++I)
3306 if (Args[I].isPackExpansion())
3307 return true;
3308
3309 return true;
3310}
3311#endif
3312
John McCall0ad16662009-10-29 08:12:44 +00003313QualType
3314ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003315 const TemplateArgument *Args,
3316 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003317 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003318 assert(!Template.getAsDependentTemplateName() &&
3319 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003320 // Look through qualified template names.
3321 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3322 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003323
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003324 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003325 Template.getAsTemplateDecl() &&
3326 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003327 QualType CanonType;
3328 if (!Underlying.isNull())
3329 CanonType = getCanonicalType(Underlying);
3330 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003331 // We can get here with an alias template when the specialization contains
3332 // a pack expansion that does not match up with a parameter pack.
3333 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3334 "Caller must compute aliased type");
3335 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003336 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3337 NumArgs);
3338 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003339
Douglas Gregora8e02e72009-07-28 23:00:59 +00003340 // Allocate the (non-canonical) template specialization type, but don't
3341 // try to unique it: these types typically have location information that
3342 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003343 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3344 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003345 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003346 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003347 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003348 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3349 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003350
Douglas Gregor8bf42052009-02-09 18:46:07 +00003351 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003352 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003353}
3354
Mike Stump11289f42009-09-09 15:08:12 +00003355QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003356ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3357 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003358 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003359 assert(!Template.getAsDependentTemplateName() &&
3360 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003361
Douglas Gregore29139c2011-03-03 17:04:51 +00003362 // Look through qualified template names.
3363 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3364 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003365
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003366 // Build the canonical template specialization type.
3367 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003368 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003369 CanonArgs.reserve(NumArgs);
3370 for (unsigned I = 0; I != NumArgs; ++I)
3371 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3372
3373 // Determine whether this canonical template specialization type already
3374 // exists.
3375 llvm::FoldingSetNodeID ID;
3376 TemplateSpecializationType::Profile(ID, CanonTemplate,
3377 CanonArgs.data(), NumArgs, *this);
3378
Craig Topper36250ad2014-05-12 05:36:57 +00003379 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003380 TemplateSpecializationType *Spec
3381 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3382
3383 if (!Spec) {
3384 // Allocate a new canonical template specialization type.
3385 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3386 sizeof(TemplateArgument) * NumArgs),
3387 TypeAlignment);
3388 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3389 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003390 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003391 Types.push_back(Spec);
3392 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3393 }
3394
3395 assert(Spec->isDependentType() &&
3396 "Non-dependent template-id type must have a canonical type");
3397 return QualType(Spec, 0);
3398}
3399
3400QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003401ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3402 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003403 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003404 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003405 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003406
Craig Topper36250ad2014-05-12 05:36:57 +00003407 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003408 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003409 if (T)
3410 return QualType(T, 0);
3411
Douglas Gregorc42075a2010-02-04 18:10:26 +00003412 QualType Canon = NamedType;
3413 if (!Canon.isCanonical()) {
3414 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003415 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3416 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003417 (void)CheckT;
3418 }
3419
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003420 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003421 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003422 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003423 return QualType(T, 0);
3424}
3425
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003426QualType
Jay Foad39c79802011-01-12 09:06:06 +00003427ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003428 llvm::FoldingSetNodeID ID;
3429 ParenType::Profile(ID, InnerType);
3430
Craig Topper36250ad2014-05-12 05:36:57 +00003431 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003432 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3433 if (T)
3434 return QualType(T, 0);
3435
3436 QualType Canon = InnerType;
3437 if (!Canon.isCanonical()) {
3438 Canon = getCanonicalType(InnerType);
3439 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3440 assert(!CheckT && "Paren canonical type broken");
3441 (void)CheckT;
3442 }
3443
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003444 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003445 Types.push_back(T);
3446 ParenTypes.InsertNode(T, InsertPos);
3447 return QualType(T, 0);
3448}
3449
Douglas Gregor02085352010-03-31 20:19:30 +00003450QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3451 NestedNameSpecifier *NNS,
3452 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003453 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003454 if (Canon.isNull()) {
3455 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003456 ElaboratedTypeKeyword CanonKeyword = Keyword;
3457 if (Keyword == ETK_None)
3458 CanonKeyword = ETK_Typename;
3459
3460 if (CanonNNS != NNS || CanonKeyword != Keyword)
3461 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003462 }
3463
3464 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003465 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003466
Craig Topper36250ad2014-05-12 05:36:57 +00003467 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003468 DependentNameType *T
3469 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003470 if (T)
3471 return QualType(T, 0);
3472
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003473 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003474 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003475 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003476 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003477}
3478
Mike Stump11289f42009-09-09 15:08:12 +00003479QualType
John McCallc392f372010-06-11 00:33:02 +00003480ASTContext::getDependentTemplateSpecializationType(
3481 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003482 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003483 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003484 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003485 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003486 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003487 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3488 ArgCopy.push_back(Args[I].getArgument());
3489 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3490 ArgCopy.size(),
3491 ArgCopy.data());
3492}
3493
3494QualType
3495ASTContext::getDependentTemplateSpecializationType(
3496 ElaboratedTypeKeyword Keyword,
3497 NestedNameSpecifier *NNS,
3498 const IdentifierInfo *Name,
3499 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003500 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003501 assert((!NNS || NNS->isDependent()) &&
3502 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003503
Douglas Gregorc42075a2010-02-04 18:10:26 +00003504 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003505 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3506 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003507
Craig Topper36250ad2014-05-12 05:36:57 +00003508 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003509 DependentTemplateSpecializationType *T
3510 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003511 if (T)
3512 return QualType(T, 0);
3513
John McCallc392f372010-06-11 00:33:02 +00003514 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003515
John McCallc392f372010-06-11 00:33:02 +00003516 ElaboratedTypeKeyword CanonKeyword = Keyword;
3517 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3518
3519 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003520 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003521 for (unsigned I = 0; I != NumArgs; ++I) {
3522 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3523 if (!CanonArgs[I].structurallyEquals(Args[I]))
3524 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003525 }
3526
John McCallc392f372010-06-11 00:33:02 +00003527 QualType Canon;
3528 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3529 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3530 Name, NumArgs,
3531 CanonArgs.data());
3532
3533 // Find the insert position again.
3534 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3535 }
3536
3537 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3538 sizeof(TemplateArgument) * NumArgs),
3539 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003540 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003541 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003542 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003543 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003544 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003545}
3546
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003547QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003548 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003549 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003550 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003551
3552 assert(Pattern->containsUnexpandedParameterPack() &&
3553 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003554 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003555 PackExpansionType *T
3556 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3557 if (T)
3558 return QualType(T, 0);
3559
3560 QualType Canon;
3561 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003562 Canon = getCanonicalType(Pattern);
3563 // The canonical type might not contain an unexpanded parameter pack, if it
3564 // contains an alias template specialization which ignores one of its
3565 // parameters.
3566 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003567 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003568
Richard Smith68eea502012-07-16 00:20:35 +00003569 // Find the insert position again, in case we inserted an element into
3570 // PackExpansionTypes and invalidated our insert position.
3571 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3572 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003573 }
3574
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003575 T = new (*this, TypeAlignment)
3576 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003577 Types.push_back(T);
3578 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003579 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003580}
3581
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003582/// CmpProtocolNames - Comparison predicate for sorting protocols
3583/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003584static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3585 ObjCProtocolDecl *const *RHS) {
3586 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003587}
3588
John McCall8b07ec22010-05-15 11:32:37 +00003589static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003590 unsigned NumProtocols) {
3591 if (NumProtocols == 0) return true;
3592
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003593 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3594 return false;
3595
John McCallfc93cf92009-10-22 22:37:11 +00003596 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003597 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003598 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003599 return false;
3600 return true;
3601}
3602
3603static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003604 unsigned &NumProtocols) {
3605 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003606
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003607 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003608 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003609
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003610 // Canonicalize.
3611 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3612 Protocols[I] = Protocols[I]->getCanonicalDecl();
3613
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003614 // Remove duplicates.
3615 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3616 NumProtocols = ProtocolsEnd-Protocols;
3617}
3618
John McCall8b07ec22010-05-15 11:32:37 +00003619QualType ASTContext::getObjCObjectType(QualType BaseType,
3620 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003621 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003622 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003623 llvm::makeArrayRef(Protocols, NumProtocols),
3624 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003625}
3626
3627QualType ASTContext::getObjCObjectType(
3628 QualType baseType,
3629 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003630 ArrayRef<ObjCProtocolDecl *> protocols,
3631 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003632 // If the base type is an interface and there aren't any protocols or
3633 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003634 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3635 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003636 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003637
3638 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003639 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003640 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003641 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003642 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3643 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003644
Douglas Gregore9d95f12015-07-07 03:57:35 +00003645 // Determine the type arguments to be used for canonicalization,
3646 // which may be explicitly specified here or written on the base
3647 // type.
3648 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3649 if (effectiveTypeArgs.empty()) {
3650 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3651 effectiveTypeArgs = baseObject->getTypeArgs();
3652 }
John McCallfc93cf92009-10-22 22:37:11 +00003653
Douglas Gregore9d95f12015-07-07 03:57:35 +00003654 // Build the canonical type, which has the canonical base type and a
3655 // sorted-and-uniqued list of protocols and the type arguments
3656 // canonicalized.
3657 QualType canonical;
3658 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3659 effectiveTypeArgs.end(),
3660 [&](QualType type) {
3661 return type.isCanonical();
3662 });
3663 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3664 protocols.size());
3665 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3666 // Determine the canonical type arguments.
3667 ArrayRef<QualType> canonTypeArgs;
3668 SmallVector<QualType, 4> canonTypeArgsVec;
3669 if (!typeArgsAreCanonical) {
3670 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3671 for (auto typeArg : effectiveTypeArgs)
3672 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3673 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003674 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003675 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003676 }
3677
Douglas Gregore9d95f12015-07-07 03:57:35 +00003678 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3679 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3680 if (!protocolsSorted) {
3681 canonProtocolsVec.insert(canonProtocolsVec.begin(),
3682 protocols.begin(),
3683 protocols.end());
3684 unsigned uniqueCount = protocols.size();
3685 SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3686 canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3687 } else {
3688 canonProtocols = protocols;
3689 }
3690
3691 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003692 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003693
John McCallfc93cf92009-10-22 22:37:11 +00003694 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003695 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3696 }
3697
Douglas Gregore9d95f12015-07-07 03:57:35 +00003698 unsigned size = sizeof(ObjCObjectTypeImpl);
3699 size += typeArgs.size() * sizeof(QualType);
3700 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3701 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003702 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003703 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3704 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003705
3706 Types.push_back(T);
3707 ObjCObjectTypes.InsertNode(T, InsertPos);
3708 return QualType(T, 0);
3709}
3710
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003711/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3712/// protocol list adopt all protocols in QT's qualified-id protocol
3713/// list.
3714bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3715 ObjCInterfaceDecl *IC) {
3716 if (!QT->isObjCQualifiedIdType())
3717 return false;
3718
3719 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3720 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003721 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003722 if (!IC->ClassImplementsProtocol(Proto, false))
3723 return false;
3724 }
3725 return true;
3726 }
3727 return false;
3728}
3729
3730/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3731/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3732/// of protocols.
3733bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3734 ObjCInterfaceDecl *IDecl) {
3735 if (!QT->isObjCQualifiedIdType())
3736 return false;
3737 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3738 if (!OPT)
3739 return false;
3740 if (!IDecl->hasDefinition())
3741 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003742 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3743 CollectInheritedProtocols(IDecl, InheritedProtocols);
3744 if (InheritedProtocols.empty())
3745 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003746 // Check that if every protocol in list of id<plist> conforms to a protcol
3747 // of IDecl's, then bridge casting is ok.
3748 bool Conforms = false;
3749 for (auto *Proto : OPT->quals()) {
3750 Conforms = false;
3751 for (auto *PI : InheritedProtocols) {
3752 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3753 Conforms = true;
3754 break;
3755 }
3756 }
3757 if (!Conforms)
3758 break;
3759 }
3760 if (Conforms)
3761 return true;
3762
Aaron Ballman83731462014-03-17 16:14:00 +00003763 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003764 // If both the right and left sides have qualifiers.
3765 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003766 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003767 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003768 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003769 break;
3770 }
3771 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003772 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003773 }
3774 return true;
3775}
3776
John McCall8b07ec22010-05-15 11:32:37 +00003777/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3778/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003779QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003780 llvm::FoldingSetNodeID ID;
3781 ObjCObjectPointerType::Profile(ID, ObjectT);
3782
Craig Topper36250ad2014-05-12 05:36:57 +00003783 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003784 if (ObjCObjectPointerType *QT =
3785 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3786 return QualType(QT, 0);
3787
3788 // Find the canonical object type.
3789 QualType Canonical;
3790 if (!ObjectT.isCanonical()) {
3791 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3792
3793 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003794 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3795 }
3796
Douglas Gregorf85bee62010-02-08 22:59:26 +00003797 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003798 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3799 ObjCObjectPointerType *QType =
3800 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003801
Steve Narofffb4330f2009-06-17 22:40:22 +00003802 Types.push_back(QType);
3803 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003804 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003805}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003806
Douglas Gregor1c283312010-08-11 12:19:30 +00003807/// getObjCInterfaceType - Return the unique reference to the type for the
3808/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003809QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3810 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003811 if (Decl->TypeForDecl)
3812 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003813
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003814 if (PrevDecl) {
3815 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3816 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3817 return QualType(PrevDecl->TypeForDecl, 0);
3818 }
3819
Douglas Gregor7671e532011-12-16 16:34:57 +00003820 // Prefer the definition, if there is one.
3821 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3822 Decl = Def;
3823
Douglas Gregor1c283312010-08-11 12:19:30 +00003824 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3825 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3826 Decl->TypeForDecl = T;
3827 Types.push_back(T);
3828 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003829}
3830
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003831/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3832/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003833/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003834/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003835/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003836QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003837 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003838 if (tofExpr->isTypeDependent()) {
3839 llvm::FoldingSetNodeID ID;
3840 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003841
Craig Topper36250ad2014-05-12 05:36:57 +00003842 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003843 DependentTypeOfExprType *Canon
3844 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3845 if (Canon) {
3846 // We already have a "canonical" version of an identical, dependent
3847 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003848 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003849 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003850 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003851 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003852 Canon
3853 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003854 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3855 toe = Canon;
3856 }
3857 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003858 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003859 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003860 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003861 Types.push_back(toe);
3862 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003863}
3864
Steve Naroffa773cd52007-08-01 18:02:17 +00003865/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003866/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003867/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003868/// an issue. This doesn't affect the type checker, since it operates
3869/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003870QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003871 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003872 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003873 Types.push_back(tot);
3874 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003875}
3876
Anders Carlssonad6bd352009-06-24 21:24:56 +00003877
Richard Smith8eb1d322014-06-05 20:13:13 +00003878/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3879/// nodes. This would never be helpful, since each such type has its own
3880/// expression, and would not give a significant memory saving, since there
3881/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003882QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003883 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003884
3885 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003886 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003887 // unique dependent type. Two such decltype-specifiers refer to the same
3888 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003889 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003890 llvm::FoldingSetNodeID ID;
3891 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003892
Craig Topper36250ad2014-05-12 05:36:57 +00003893 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003894 DependentDecltypeType *Canon
3895 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003896 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003897 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003898 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003899 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003900 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003901 dt = new (*this, TypeAlignment)
3902 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003903 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003904 dt = new (*this, TypeAlignment)
3905 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003906 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003907 Types.push_back(dt);
3908 return QualType(dt, 0);
3909}
3910
Alexis Hunte852b102011-05-24 22:41:36 +00003911/// getUnaryTransformationType - We don't unique these, since the memory
3912/// savings are minimal and these are rare.
3913QualType ASTContext::getUnaryTransformType(QualType BaseType,
3914 QualType UnderlyingType,
3915 UnaryTransformType::UTTKind Kind)
3916 const {
3917 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003918 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3919 Kind,
3920 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003921 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003922 Types.push_back(Ty);
3923 return QualType(Ty, 0);
3924}
3925
Richard Smith2a7d4812013-05-04 07:00:32 +00003926/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3927/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3928/// canonical deduced-but-dependent 'auto' type.
3929QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003930 bool IsDependent) const {
3931 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003932 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003933
Richard Smith2a7d4812013-05-04 07:00:32 +00003934 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003935 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003936 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003937 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003938 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3939 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003940
Richard Smith74aeef52013-04-26 16:15:35 +00003941 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003942 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003943 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003944 Types.push_back(AT);
3945 if (InsertPos)
3946 AutoTypes.InsertNode(AT, InsertPos);
3947 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003948}
3949
Eli Friedman0dfb8892011-10-06 23:00:33 +00003950/// getAtomicType - Return the uniqued reference to the atomic type for
3951/// the given value type.
3952QualType ASTContext::getAtomicType(QualType T) const {
3953 // Unique pointers, to guarantee there is only one pointer of a particular
3954 // structure.
3955 llvm::FoldingSetNodeID ID;
3956 AtomicType::Profile(ID, T);
3957
Craig Topper36250ad2014-05-12 05:36:57 +00003958 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003959 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3960 return QualType(AT, 0);
3961
3962 // If the atomic value type isn't canonical, this won't be a canonical type
3963 // either, so fill in the canonical type field.
3964 QualType Canonical;
3965 if (!T.isCanonical()) {
3966 Canonical = getAtomicType(getCanonicalType(T));
3967
3968 // Get the new insert position for the node we care about.
3969 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003970 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003971 }
3972 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3973 Types.push_back(New);
3974 AtomicTypes.InsertNode(New, InsertPos);
3975 return QualType(New, 0);
3976}
3977
Richard Smith02e85f32011-04-14 22:09:26 +00003978/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3979QualType ASTContext::getAutoDeductType() const {
3980 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003981 AutoDeductTy = QualType(
3982 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003983 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003984 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003985 return AutoDeductTy;
3986}
3987
3988/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3989QualType ASTContext::getAutoRRefDeductType() const {
3990 if (AutoRRefDeductTy.isNull())
3991 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3992 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3993 return AutoRRefDeductTy;
3994}
3995
Chris Lattnerfb072462007-01-23 05:45:31 +00003996/// getTagDeclType - Return the unique reference to the type for the
3997/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003998QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003999 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004000 // FIXME: What is the design on getTagDeclType when it requires casting
4001 // away const? mutable?
4002 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004003}
4004
Mike Stump11289f42009-09-09 15:08:12 +00004005/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4006/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4007/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004008CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004009 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004010}
Chris Lattnerfb072462007-01-23 05:45:31 +00004011
Hans Wennborg27541db2011-10-27 08:29:09 +00004012/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4013CanQualType ASTContext::getIntMaxType() const {
4014 return getFromTargetType(Target->getIntMaxType());
4015}
4016
4017/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4018CanQualType ASTContext::getUIntMaxType() const {
4019 return getFromTargetType(Target->getUIntMaxType());
4020}
4021
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004022/// getSignedWCharType - Return the type of "signed wchar_t".
4023/// Used when in C++, as a GCC extension.
4024QualType ASTContext::getSignedWCharType() const {
4025 // FIXME: derive from "Target" ?
4026 return WCharTy;
4027}
4028
4029/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4030/// Used when in C++, as a GCC extension.
4031QualType ASTContext::getUnsignedWCharType() const {
4032 // FIXME: derive from "Target" ?
4033 return UnsignedIntTy;
4034}
4035
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004036QualType ASTContext::getIntPtrType() const {
4037 return getFromTargetType(Target->getIntPtrType());
4038}
4039
4040QualType ASTContext::getUIntPtrType() const {
4041 return getCorrespondingUnsignedType(getIntPtrType());
4042}
4043
Hans Wennborg27541db2011-10-27 08:29:09 +00004044/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004045/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4046QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004047 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004048}
4049
Eli Friedman4e91899e2012-11-27 02:58:24 +00004050/// \brief Return the unique type for "pid_t" defined in
4051/// <sys/types.h>. We need this to compute the correct type for vfork().
4052QualType ASTContext::getProcessIDType() const {
4053 return getFromTargetType(Target->getProcessIDType());
4054}
4055
Chris Lattnera21ad802008-04-02 05:18:44 +00004056//===----------------------------------------------------------------------===//
4057// Type Operators
4058//===----------------------------------------------------------------------===//
4059
Jay Foad39c79802011-01-12 09:06:06 +00004060CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004061 // Push qualifiers into arrays, and then discard any remaining
4062 // qualifiers.
4063 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004064 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004065 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004066 QualType Result;
4067 if (isa<ArrayType>(Ty)) {
4068 Result = getArrayDecayedType(QualType(Ty,0));
4069 } else if (isa<FunctionType>(Ty)) {
4070 Result = getPointerType(QualType(Ty, 0));
4071 } else {
4072 Result = QualType(Ty, 0);
4073 }
4074
4075 return CanQualType::CreateUnsafe(Result);
4076}
4077
John McCall6c9dd522011-01-18 07:41:22 +00004078QualType ASTContext::getUnqualifiedArrayType(QualType type,
4079 Qualifiers &quals) {
4080 SplitQualType splitType = type.getSplitUnqualifiedType();
4081
4082 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4083 // the unqualified desugared type and then drops it on the floor.
4084 // We then have to strip that sugar back off with
4085 // getUnqualifiedDesugaredType(), which is silly.
4086 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004087 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004088
4089 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004090 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004091 quals = splitType.Quals;
4092 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004093 }
4094
John McCall6c9dd522011-01-18 07:41:22 +00004095 // Otherwise, recurse on the array's element type.
4096 QualType elementType = AT->getElementType();
4097 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4098
4099 // If that didn't change the element type, AT has no qualifiers, so we
4100 // can just use the results in splitType.
4101 if (elementType == unqualElementType) {
4102 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004103 quals = splitType.Quals;
4104 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004105 }
4106
4107 // Otherwise, add in the qualifiers from the outermost type, then
4108 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004109 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004110
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004111 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004112 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004113 CAT->getSizeModifier(), 0);
4114 }
4115
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004116 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004117 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004118 }
4119
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004120 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004121 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004122 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004123 VAT->getSizeModifier(),
4124 VAT->getIndexTypeCVRQualifiers(),
4125 VAT->getBracketsRange());
4126 }
4127
4128 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004129 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004130 DSAT->getSizeModifier(), 0,
4131 SourceRange());
4132}
4133
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004134/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4135/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4136/// they point to and return true. If T1 and T2 aren't pointer types
4137/// or pointer-to-member types, or if they are not similar at this
4138/// level, returns false and leaves T1 and T2 unchanged. Top-level
4139/// qualifiers on T1 and T2 are ignored. This function will typically
4140/// be called in a loop that successively "unwraps" pointer and
4141/// pointer-to-member types to compare them at each level.
4142bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4143 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4144 *T2PtrType = T2->getAs<PointerType>();
4145 if (T1PtrType && T2PtrType) {
4146 T1 = T1PtrType->getPointeeType();
4147 T2 = T2PtrType->getPointeeType();
4148 return true;
4149 }
4150
4151 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4152 *T2MPType = T2->getAs<MemberPointerType>();
4153 if (T1MPType && T2MPType &&
4154 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4155 QualType(T2MPType->getClass(), 0))) {
4156 T1 = T1MPType->getPointeeType();
4157 T2 = T2MPType->getPointeeType();
4158 return true;
4159 }
4160
David Blaikiebbafb8a2012-03-11 07:00:24 +00004161 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004162 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4163 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4164 if (T1OPType && T2OPType) {
4165 T1 = T1OPType->getPointeeType();
4166 T2 = T2OPType->getPointeeType();
4167 return true;
4168 }
4169 }
4170
4171 // FIXME: Block pointers, too?
4172
4173 return false;
4174}
4175
Jay Foad39c79802011-01-12 09:06:06 +00004176DeclarationNameInfo
4177ASTContext::getNameForTemplate(TemplateName Name,
4178 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004179 switch (Name.getKind()) {
4180 case TemplateName::QualifiedTemplate:
4181 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004182 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004183 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4184 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004185
John McCalld9dfe3a2011-06-30 08:33:18 +00004186 case TemplateName::OverloadedTemplate: {
4187 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4188 // DNInfo work in progress: CHECKME: what about DNLoc?
4189 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4190 }
4191
4192 case TemplateName::DependentTemplate: {
4193 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004194 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004195 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004196 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4197 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004198 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004199 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4200 // DNInfo work in progress: FIXME: source locations?
4201 DeclarationNameLoc DNLoc;
4202 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4203 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4204 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004205 }
4206 }
4207
John McCalld9dfe3a2011-06-30 08:33:18 +00004208 case TemplateName::SubstTemplateTemplateParm: {
4209 SubstTemplateTemplateParmStorage *subst
4210 = Name.getAsSubstTemplateTemplateParm();
4211 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4212 NameLoc);
4213 }
4214
4215 case TemplateName::SubstTemplateTemplateParmPack: {
4216 SubstTemplateTemplateParmPackStorage *subst
4217 = Name.getAsSubstTemplateTemplateParmPack();
4218 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4219 NameLoc);
4220 }
4221 }
4222
4223 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004224}
4225
Jay Foad39c79802011-01-12 09:06:06 +00004226TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004227 switch (Name.getKind()) {
4228 case TemplateName::QualifiedTemplate:
4229 case TemplateName::Template: {
4230 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004231 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004232 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004233 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4234
4235 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004236 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004237 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004238
John McCalld9dfe3a2011-06-30 08:33:18 +00004239 case TemplateName::OverloadedTemplate:
4240 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004241
John McCalld9dfe3a2011-06-30 08:33:18 +00004242 case TemplateName::DependentTemplate: {
4243 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4244 assert(DTN && "Non-dependent template names must refer to template decls.");
4245 return DTN->CanonicalTemplateName;
4246 }
4247
4248 case TemplateName::SubstTemplateTemplateParm: {
4249 SubstTemplateTemplateParmStorage *subst
4250 = Name.getAsSubstTemplateTemplateParm();
4251 return getCanonicalTemplateName(subst->getReplacement());
4252 }
4253
4254 case TemplateName::SubstTemplateTemplateParmPack: {
4255 SubstTemplateTemplateParmPackStorage *subst
4256 = Name.getAsSubstTemplateTemplateParmPack();
4257 TemplateTemplateParmDecl *canonParameter
4258 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4259 TemplateArgument canonArgPack
4260 = getCanonicalTemplateArgument(subst->getArgumentPack());
4261 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4262 }
4263 }
4264
4265 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004266}
4267
Douglas Gregoradee3e32009-11-11 23:06:43 +00004268bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4269 X = getCanonicalTemplateName(X);
4270 Y = getCanonicalTemplateName(Y);
4271 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4272}
4273
Mike Stump11289f42009-09-09 15:08:12 +00004274TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004275ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004276 switch (Arg.getKind()) {
4277 case TemplateArgument::Null:
4278 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004279
Douglas Gregora8e02e72009-07-28 23:00:59 +00004280 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004281 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004282
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004283 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004284 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004285 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
Eli Friedmanb826a002012-09-26 02:36:12 +00004288 case TemplateArgument::NullPtr:
4289 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4290 /*isNullPtr*/true);
4291
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004292 case TemplateArgument::Template:
4293 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004294
4295 case TemplateArgument::TemplateExpansion:
4296 return TemplateArgument(getCanonicalTemplateName(
4297 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004298 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004299
Douglas Gregora8e02e72009-07-28 23:00:59 +00004300 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004301 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004302
Douglas Gregora8e02e72009-07-28 23:00:59 +00004303 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004304 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004305
Douglas Gregora8e02e72009-07-28 23:00:59 +00004306 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004307 if (Arg.pack_size() == 0)
4308 return Arg;
4309
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004310 TemplateArgument *CanonArgs
4311 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004312 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004313 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004314 AEnd = Arg.pack_end();
4315 A != AEnd; (void)++A, ++Idx)
4316 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004317
Benjamin Kramercce63472015-08-05 09:40:22 +00004318 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004319 }
4320 }
4321
4322 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004323 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004324}
4325
Douglas Gregor333489b2009-03-27 23:10:48 +00004326NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004327ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004328 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004329 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004330
4331 switch (NNS->getKind()) {
4332 case NestedNameSpecifier::Identifier:
4333 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004334 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004335 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4336 NNS->getAsIdentifier());
4337
4338 case NestedNameSpecifier::Namespace:
4339 // A namespace is canonical; build a nested-name-specifier with
4340 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004341 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004342 NNS->getAsNamespace()->getOriginalNamespace());
4343
4344 case NestedNameSpecifier::NamespaceAlias:
4345 // A namespace is canonical; build a nested-name-specifier with
4346 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004347 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004348 NNS->getAsNamespaceAlias()->getNamespace()
4349 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004350
4351 case NestedNameSpecifier::TypeSpec:
4352 case NestedNameSpecifier::TypeSpecWithTemplate: {
4353 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004354
4355 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4356 // break it apart into its prefix and identifier, then reconsititute those
4357 // as the canonical nested-name-specifier. This is required to canonicalize
4358 // a dependent nested-name-specifier involving typedefs of dependent-name
4359 // types, e.g.,
4360 // typedef typename T::type T1;
4361 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004362 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4363 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004364 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004365
Eli Friedman5358a0a2012-03-03 04:09:56 +00004366 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4367 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4368 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004369 return NestedNameSpecifier::Create(*this, nullptr, false,
4370 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004371 }
4372
4373 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004374 case NestedNameSpecifier::Super:
4375 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004376 return NNS;
4377 }
4378
David Blaikie8a40f702012-01-17 06:56:22 +00004379 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004380}
4381
Chris Lattner7adf0762008-08-04 07:31:14 +00004382
Jay Foad39c79802011-01-12 09:06:06 +00004383const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004384 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004385 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004386 // Handle the common positive case fast.
4387 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4388 return AT;
4389 }
Mike Stump11289f42009-09-09 15:08:12 +00004390
John McCall8ccfcb52009-09-24 19:53:00 +00004391 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004392 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004393 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004394
John McCall8ccfcb52009-09-24 19:53:00 +00004395 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004396 // implements C99 6.7.3p8: "If the specification of an array type includes
4397 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004398
Chris Lattner7adf0762008-08-04 07:31:14 +00004399 // If we get here, we either have type qualifiers on the type, or we have
4400 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004401 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004402
John McCall33ddac02011-01-19 10:06:00 +00004403 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004404 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004405
Chris Lattner7adf0762008-08-04 07:31:14 +00004406 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004407 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004408 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004409 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004410
Chris Lattner7adf0762008-08-04 07:31:14 +00004411 // Otherwise, we have an array and we have qualifiers on it. Push the
4412 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004413 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004414
Chris Lattner7adf0762008-08-04 07:31:14 +00004415 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4416 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4417 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004418 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004419 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4420 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4421 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004422 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004423
Mike Stump11289f42009-09-09 15:08:12 +00004424 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004425 = dyn_cast<DependentSizedArrayType>(ATy))
4426 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004427 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004428 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004429 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004430 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004431 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004432
Chris Lattner7adf0762008-08-04 07:31:14 +00004433 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004434 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004435 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004436 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004437 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004438 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004439}
4440
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004441QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004442 if (T->isArrayType() || T->isFunctionType())
4443 return getDecayedType(T);
4444 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004445}
4446
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004447QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004448 T = getVariableArrayDecayedType(T);
4449 T = getAdjustedParameterType(T);
4450 return T.getUnqualifiedType();
4451}
4452
David Majnemerd09a51c2015-03-03 01:50:05 +00004453QualType ASTContext::getExceptionObjectType(QualType T) const {
4454 // C++ [except.throw]p3:
4455 // A throw-expression initializes a temporary object, called the exception
4456 // object, the type of which is determined by removing any top-level
4457 // cv-qualifiers from the static type of the operand of throw and adjusting
4458 // the type from "array of T" or "function returning T" to "pointer to T"
4459 // or "pointer to function returning T", [...]
4460 T = getVariableArrayDecayedType(T);
4461 if (T->isArrayType() || T->isFunctionType())
4462 T = getDecayedType(T);
4463 return T.getUnqualifiedType();
4464}
4465
Chris Lattnera21ad802008-04-02 05:18:44 +00004466/// getArrayDecayedType - Return the properly qualified result of decaying the
4467/// specified array type to a pointer. This operation is non-trivial when
4468/// handling typedefs etc. The canonical type of "T" must be an array type,
4469/// this returns a pointer to a properly qualified element of the array.
4470///
4471/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004472QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004473 // Get the element type with 'getAsArrayType' so that we don't lose any
4474 // typedefs in the element type of the array. This also handles propagation
4475 // of type qualifiers from the array type into the element type if present
4476 // (C99 6.7.3p8).
4477 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4478 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004479
Chris Lattner7adf0762008-08-04 07:31:14 +00004480 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004481
4482 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004483 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004484}
4485
John McCall33ddac02011-01-19 10:06:00 +00004486QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4487 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004488}
4489
John McCall33ddac02011-01-19 10:06:00 +00004490QualType ASTContext::getBaseElementType(QualType type) const {
4491 Qualifiers qs;
4492 while (true) {
4493 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004494 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004495 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004496
John McCall33ddac02011-01-19 10:06:00 +00004497 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004498 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004499 }
Mike Stump11289f42009-09-09 15:08:12 +00004500
John McCall33ddac02011-01-19 10:06:00 +00004501 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004502}
4503
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004504/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004505uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004506ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4507 uint64_t ElementCount = 1;
4508 do {
4509 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004510 CA = dyn_cast_or_null<ConstantArrayType>(
4511 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004512 } while (CA);
4513 return ElementCount;
4514}
4515
Steve Naroff0af91202007-04-27 21:51:21 +00004516/// getFloatingRank - Return a relative rank for floating point types.
4517/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004518static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004519 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004520 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004521
John McCall9dd450b2009-09-21 23:43:11 +00004522 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4523 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004524 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004525 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004526 case BuiltinType::Float: return FloatRank;
4527 case BuiltinType::Double: return DoubleRank;
4528 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004529 }
4530}
4531
Mike Stump11289f42009-09-09 15:08:12 +00004532/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4533/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004534/// 'typeDomain' is a real floating point or complex type.
4535/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004536QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4537 QualType Domain) const {
4538 FloatingRank EltRank = getFloatingRank(Size);
4539 if (Domain->isComplexType()) {
4540 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004541 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004542 case FloatRank: return FloatComplexTy;
4543 case DoubleRank: return DoubleComplexTy;
4544 case LongDoubleRank: return LongDoubleComplexTy;
4545 }
Steve Naroff0af91202007-04-27 21:51:21 +00004546 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004547
4548 assert(Domain->isRealFloatingType() && "Unknown domain!");
4549 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004550 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004551 case FloatRank: return FloatTy;
4552 case DoubleRank: return DoubleTy;
4553 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004554 }
David Blaikief47fa302012-01-17 02:30:50 +00004555 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004556}
4557
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004558/// getFloatingTypeOrder - Compare the rank of the two specified floating
4559/// point types, ignoring the domain of the type (i.e. 'double' ==
4560/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004561/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004562int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004563 FloatingRank LHSR = getFloatingRank(LHS);
4564 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004565
Chris Lattnerb90739d2008-04-06 23:38:49 +00004566 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004567 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004568 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004569 return 1;
4570 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004571}
4572
Chris Lattner76a00cf2008-04-06 22:59:24 +00004573/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4574/// routine will assert if passed a built-in type that isn't an integer or enum,
4575/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004576unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004577 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004578
Chris Lattner76a00cf2008-04-06 22:59:24 +00004579 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004580 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004581 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004582 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004583 case BuiltinType::Char_S:
4584 case BuiltinType::Char_U:
4585 case BuiltinType::SChar:
4586 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004587 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004588 case BuiltinType::Short:
4589 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004590 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004591 case BuiltinType::Int:
4592 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004593 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004594 case BuiltinType::Long:
4595 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004596 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004597 case BuiltinType::LongLong:
4598 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004599 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004600 case BuiltinType::Int128:
4601 case BuiltinType::UInt128:
4602 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004603 }
4604}
4605
Eli Friedman629ffb92009-08-20 04:21:42 +00004606/// \brief Whether this is a promotable bitfield reference according
4607/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4608///
4609/// \returns the type this bit-field will promote to, or NULL if no
4610/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004611QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004612 if (E->isTypeDependent() || E->isValueDependent())
4613 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004614
4615 // FIXME: We should not do this unless E->refersToBitField() is true. This
4616 // matters in C where getSourceBitField() will find bit-fields for various
4617 // cases where the source expression is not a bit-field designator.
4618
John McCalld25db7e2013-05-06 21:39:12 +00004619 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004620 if (!Field)
4621 return QualType();
4622
4623 QualType FT = Field->getType();
4624
Richard Smithcaf33902011-10-10 18:28:20 +00004625 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004626 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004627 // C++ [conv.prom]p5:
4628 // A prvalue for an integral bit-field can be converted to a prvalue of type
4629 // int if int can represent all the values of the bit-field; otherwise, it
4630 // can be converted to unsigned int if unsigned int can represent all the
4631 // values of the bit-field. If the bit-field is larger yet, no integral
4632 // promotion applies to it.
4633 // C11 6.3.1.1/2:
4634 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4635 // If an int can represent all values of the original type (as restricted by
4636 // the width, for a bit-field), the value is converted to an int; otherwise,
4637 // it is converted to an unsigned int.
4638 //
4639 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4640 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004641 if (BitWidth < IntSize)
4642 return IntTy;
4643
4644 if (BitWidth == IntSize)
4645 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4646
4647 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004648 // like the base type. GCC has some weird bugs in this area that we
4649 // deliberately do not follow (GCC follows a pre-standard resolution to
4650 // C's DR315 which treats bit-width as being part of the type, and this leaks
4651 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004652 return QualType();
4653}
4654
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004655/// getPromotedIntegerType - Returns the type that Promotable will
4656/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4657/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004658QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004659 assert(!Promotable.isNull());
4660 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004661 if (const EnumType *ET = Promotable->getAs<EnumType>())
4662 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004663
4664 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4665 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4666 // (3.9.1) can be converted to a prvalue of the first of the following
4667 // types that can represent all the values of its underlying type:
4668 // int, unsigned int, long int, unsigned long int, long long int, or
4669 // unsigned long long int [...]
4670 // FIXME: Is there some better way to compute this?
4671 if (BT->getKind() == BuiltinType::WChar_S ||
4672 BT->getKind() == BuiltinType::WChar_U ||
4673 BT->getKind() == BuiltinType::Char16 ||
4674 BT->getKind() == BuiltinType::Char32) {
4675 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4676 uint64_t FromSize = getTypeSize(BT);
4677 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4678 LongLongTy, UnsignedLongLongTy };
4679 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4680 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4681 if (FromSize < ToSize ||
4682 (FromSize == ToSize &&
4683 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4684 return PromoteTypes[Idx];
4685 }
4686 llvm_unreachable("char type should fit into long long");
4687 }
4688 }
4689
4690 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004691 if (Promotable->isSignedIntegerType())
4692 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004693 uint64_t PromotableSize = getIntWidth(Promotable);
4694 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004695 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4696 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4697}
4698
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004699/// \brief Recurses in pointer/array types until it finds an objc retainable
4700/// type and returns its ownership.
4701Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4702 while (!T.isNull()) {
4703 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4704 return T.getObjCLifetime();
4705 if (T->isArrayType())
4706 T = getBaseElementType(T);
4707 else if (const PointerType *PT = T->getAs<PointerType>())
4708 T = PT->getPointeeType();
4709 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004710 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004711 else
4712 break;
4713 }
4714
4715 return Qualifiers::OCL_None;
4716}
4717
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004718static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4719 // Incomplete enum types are not treated as integer types.
4720 // FIXME: In C++, enum types are never integer types.
4721 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4722 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004723 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004724}
4725
Mike Stump11289f42009-09-09 15:08:12 +00004726/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004727/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004728/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004729int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004730 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4731 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004732
4733 // Unwrap enums to their underlying type.
4734 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4735 LHSC = getIntegerTypeForEnum(ET);
4736 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4737 RHSC = getIntegerTypeForEnum(ET);
4738
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004739 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004740
Chris Lattner76a00cf2008-04-06 22:59:24 +00004741 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4742 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004743
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004744 unsigned LHSRank = getIntegerRank(LHSC);
4745 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004746
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004747 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4748 if (LHSRank == RHSRank) return 0;
4749 return LHSRank > RHSRank ? 1 : -1;
4750 }
Mike Stump11289f42009-09-09 15:08:12 +00004751
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004752 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4753 if (LHSUnsigned) {
4754 // If the unsigned [LHS] type is larger, return it.
4755 if (LHSRank >= RHSRank)
4756 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004757
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004758 // If the signed type can represent all values of the unsigned type, it
4759 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004760 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004761 return -1;
4762 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004763
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004764 // If the unsigned [RHS] type is larger, return it.
4765 if (RHSRank >= LHSRank)
4766 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004767
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004768 // If the signed type can represent all values of the unsigned type, it
4769 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004770 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004771 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004772}
Anders Carlsson98f07902007-08-17 05:31:46 +00004773
Mike Stump11289f42009-09-09 15:08:12 +00004774// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004775QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004776 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004777 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004778 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004779
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004780 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004781
Anders Carlsson98f07902007-08-17 05:31:46 +00004782 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004783 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004784 // int flags;
4785 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004786 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004787 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004788 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004789 FieldTypes[3] = LongTy;
4790
Anders Carlsson98f07902007-08-17 05:31:46 +00004791 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004792 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004793 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004794 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004795 SourceLocation(), nullptr,
4796 FieldTypes[i], /*TInfo=*/nullptr,
4797 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004798 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004799 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004800 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004801 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004802 }
4803
Douglas Gregord5058122010-02-11 01:19:42 +00004804 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004805 }
Mike Stump11289f42009-09-09 15:08:12 +00004806
Anders Carlsson98f07902007-08-17 05:31:46 +00004807 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004808}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004809
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004810QualType ASTContext::getObjCSuperType() const {
4811 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004812 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004813 TUDecl->addDecl(ObjCSuperTypeDecl);
4814 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4815 }
4816 return ObjCSuperType;
4817}
4818
Douglas Gregor512b0772009-04-23 22:29:11 +00004819void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004820 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004821 assert(Rec && "Invalid CFConstantStringType");
4822 CFConstantStringTypeDecl = Rec->getDecl();
4823}
4824
Jay Foad39c79802011-01-12 09:06:06 +00004825QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004826 if (BlockDescriptorType)
4827 return getTagDeclType(BlockDescriptorType);
4828
Alp Toker2dea15b2013-12-17 01:22:38 +00004829 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004830 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004831 RD = buildImplicitRecord("__block_descriptor");
4832 RD->startDefinition();
4833
Mike Stumpd0153282009-10-20 02:12:22 +00004834 QualType FieldTypes[] = {
4835 UnsignedLongTy,
4836 UnsignedLongTy,
4837 };
4838
Craig Topperd6d31ac2013-07-15 08:24:27 +00004839 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004840 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004841 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004842 };
4843
4844 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004845 FieldDecl *Field = FieldDecl::Create(
4846 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004847 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4848 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004849 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004850 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004851 }
4852
Alp Toker2dea15b2013-12-17 01:22:38 +00004853 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004854
Alp Toker2dea15b2013-12-17 01:22:38 +00004855 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004856
4857 return getTagDeclType(BlockDescriptorType);
4858}
4859
Jay Foad39c79802011-01-12 09:06:06 +00004860QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004861 if (BlockDescriptorExtendedType)
4862 return getTagDeclType(BlockDescriptorExtendedType);
4863
Alp Toker2dea15b2013-12-17 01:22:38 +00004864 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004865 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004866 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4867 RD->startDefinition();
4868
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004869 QualType FieldTypes[] = {
4870 UnsignedLongTy,
4871 UnsignedLongTy,
4872 getPointerType(VoidPtrTy),
4873 getPointerType(VoidPtrTy)
4874 };
4875
Craig Topperd6d31ac2013-07-15 08:24:27 +00004876 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004877 "reserved",
4878 "Size",
4879 "CopyFuncPtr",
4880 "DestroyFuncPtr"
4881 };
4882
4883 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004884 FieldDecl *Field = FieldDecl::Create(
4885 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004886 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4887 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004888 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004889 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004890 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004891 }
4892
Alp Toker2dea15b2013-12-17 01:22:38 +00004893 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004894
Alp Toker2dea15b2013-12-17 01:22:38 +00004895 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004896 return getTagDeclType(BlockDescriptorExtendedType);
4897}
4898
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004899/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4900/// requires copy/dispose. Note that this must match the logic
4901/// in buildByrefHelpers.
4902bool ASTContext::BlockRequiresCopying(QualType Ty,
4903 const VarDecl *D) {
4904 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4905 const Expr *copyExpr = getBlockVarCopyInits(D);
4906 if (!copyExpr && record->hasTrivialDestructor()) return false;
4907
Mike Stump94967902009-10-21 18:16:27 +00004908 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004909 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004910
4911 if (!Ty->isObjCRetainableType()) return false;
4912
4913 Qualifiers qs = Ty.getQualifiers();
4914
4915 // If we have lifetime, that dominates.
4916 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4917 assert(getLangOpts().ObjCAutoRefCount);
4918
4919 switch (lifetime) {
4920 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4921
4922 // These are just bits as far as the runtime is concerned.
4923 case Qualifiers::OCL_ExplicitNone:
4924 case Qualifiers::OCL_Autoreleasing:
4925 return false;
4926
4927 // Tell the runtime that this is ARC __weak, called by the
4928 // byref routines.
4929 case Qualifiers::OCL_Weak:
4930 // ARC __strong __block variables need to be retained.
4931 case Qualifiers::OCL_Strong:
4932 return true;
4933 }
4934 llvm_unreachable("fell out of lifetime switch!");
4935 }
4936 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4937 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004938}
4939
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004940bool ASTContext::getByrefLifetime(QualType Ty,
4941 Qualifiers::ObjCLifetime &LifeTime,
4942 bool &HasByrefExtendedLayout) const {
4943
4944 if (!getLangOpts().ObjC1 ||
4945 getLangOpts().getGC() != LangOptions::NonGC)
4946 return false;
4947
4948 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004949 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004950 HasByrefExtendedLayout = true;
4951 LifeTime = Qualifiers::OCL_None;
4952 }
4953 else if (getLangOpts().ObjCAutoRefCount)
4954 LifeTime = Ty.getObjCLifetime();
4955 // MRR.
4956 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4957 LifeTime = Qualifiers::OCL_ExplicitNone;
4958 else
4959 LifeTime = Qualifiers::OCL_None;
4960 return true;
4961}
4962
Douglas Gregorbab8a962011-09-08 01:46:34 +00004963TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4964 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004965 ObjCInstanceTypeDecl =
4966 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004967 return ObjCInstanceTypeDecl;
4968}
4969
Anders Carlsson18acd442007-10-29 06:33:42 +00004970// This returns true if a type has been typedefed to BOOL:
4971// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004972static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004973 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004974 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4975 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004976
Anders Carlssond8499822007-10-29 05:01:08 +00004977 return false;
4978}
4979
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004980/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004981/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004982CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004983 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4984 return CharUnits::Zero();
4985
Ken Dyck40775002010-01-11 17:06:35 +00004986 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004987
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004988 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004989 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004990 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004991 // Treat arrays as pointers, since that's how they're passed in.
4992 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004993 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004994 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004995}
4996
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004997bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4998 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4999 VD->getType()->isIntegralOrEnumerationType() &&
Alexey Bataev15413ea2015-05-20 11:57:02 +00005000 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005001}
5002
Ken Dyck40775002010-01-11 17:06:35 +00005003static inline
5004std::string charUnitsToString(const CharUnits &CU) {
5005 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005006}
5007
John McCall351762c2011-02-07 10:33:21 +00005008/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005009/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005010std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5011 std::string S;
5012
David Chisnall950a9512009-11-17 19:33:30 +00005013 const BlockDecl *Decl = Expr->getBlockDecl();
5014 QualType BlockTy =
5015 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5016 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005017 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005018 getObjCEncodingForMethodParameter(
5019 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5020 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005021 else
Alp Toker314cc812014-01-25 16:55:45 +00005022 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005023 // Compute size of all parameters.
5024 // Start with computing size of a pointer in number of bytes.
5025 // FIXME: There might(should) be a better way of doing this computation!
5026 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005027 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5028 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005029 for (auto PI : Decl->params()) {
5030 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005031 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005032 if (sz.isZero())
5033 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005034 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005035 ParmOffset += sz;
5036 }
5037 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005038 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005039 // Block pointer and offset.
5040 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005041
5042 // Argument types.
5043 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005044 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005045 QualType PType = PVDecl->getOriginalType();
5046 if (const ArrayType *AT =
5047 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5048 // Use array's original type only if it has known number of
5049 // elements.
5050 if (!isa<ConstantArrayType>(AT))
5051 PType = PVDecl->getType();
5052 } else if (PType->isFunctionType())
5053 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005054 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005055 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5056 S, true /*Extended*/);
5057 else
5058 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005059 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005060 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005061 }
John McCall351762c2011-02-07 10:33:21 +00005062
5063 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005064}
5065
Douglas Gregora9d84932011-05-27 01:19:52 +00005066bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005067 std::string& S) {
5068 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005069 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005070 CharUnits ParmOffset;
5071 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005072 for (auto PI : Decl->params()) {
5073 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005074 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005075 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005076 continue;
5077
David Chisnall50e4eba2010-12-30 14:05:53 +00005078 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005079 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005080 ParmOffset += sz;
5081 }
5082 S += charUnitsToString(ParmOffset);
5083 ParmOffset = CharUnits::Zero();
5084
5085 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005086 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005087 QualType PType = PVDecl->getOriginalType();
5088 if (const ArrayType *AT =
5089 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5090 // Use array's original type only if it has known number of
5091 // elements.
5092 if (!isa<ConstantArrayType>(AT))
5093 PType = PVDecl->getType();
5094 } else if (PType->isFunctionType())
5095 PType = PVDecl->getType();
5096 getObjCEncodingForType(PType, S);
5097 S += charUnitsToString(ParmOffset);
5098 ParmOffset += getObjCEncodingTypeSize(PType);
5099 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005100
5101 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005102}
5103
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005104/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5105/// method parameter or return type. If Extended, include class names and
5106/// block object types.
5107void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5108 QualType T, std::string& S,
5109 bool Extended) const {
5110 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5111 getObjCEncodingForTypeQualifier(QT, S);
5112 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005113 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005114 true /*OutermostType*/,
5115 false /*EncodingProperty*/,
5116 false /*StructField*/,
5117 Extended /*EncodeBlockParameters*/,
5118 Extended /*EncodeClassNames*/);
5119}
5120
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005121/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005122/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005123bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005124 std::string& S,
5125 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005126 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005127 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005128 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5129 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005130 // Compute size of all parameters.
5131 // Start with computing size of a pointer in number of bytes.
5132 // FIXME: There might(should) be a better way of doing this computation!
5133 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005134 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005135 // The first two arguments (self and _cmd) are pointers; account for
5136 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005137 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005138 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005139 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005140 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005141 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005142 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005143 continue;
5144
Ken Dyck40775002010-01-11 17:06:35 +00005145 assert (sz.isPositive() &&
5146 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005147 ParmOffset += sz;
5148 }
Ken Dyck40775002010-01-11 17:06:35 +00005149 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005150 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005151 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005152
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005153 // Argument types.
5154 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005155 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005156 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005157 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005158 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005159 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005160 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5161 // Use array's original type only if it has known number of
5162 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005163 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005164 PType = PVDecl->getType();
5165 } else if (PType->isFunctionType())
5166 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005167 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5168 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005169 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005170 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005171 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005172
5173 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005174}
5175
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005176ObjCPropertyImplDecl *
5177ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5178 const ObjCPropertyDecl *PD,
5179 const Decl *Container) const {
5180 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005181 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005182 if (const ObjCCategoryImplDecl *CID =
5183 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005184 for (auto *PID : CID->property_impls())
5185 if (PID->getPropertyDecl() == PD)
5186 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005187 } else {
5188 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5189 for (auto *PID : OID->property_impls())
5190 if (PID->getPropertyDecl() == PD)
5191 return PID;
5192 }
5193 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005194}
5195
Daniel Dunbar4932b362008-08-28 04:38:10 +00005196/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005197/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005198/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5199/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005200/// Property attributes are stored as a comma-delimited C string. The simple
5201/// attributes readonly and bycopy are encoded as single characters. The
5202/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5203/// encoded as single characters, followed by an identifier. Property types
5204/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005205/// these attributes are defined by the following enumeration:
5206/// @code
5207/// enum PropertyAttributes {
5208/// kPropertyReadOnly = 'R', // property is read-only.
5209/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5210/// kPropertyByref = '&', // property is a reference to the value last assigned
5211/// kPropertyDynamic = 'D', // property is dynamic
5212/// kPropertyGetter = 'G', // followed by getter selector name
5213/// kPropertySetter = 'S', // followed by setter selector name
5214/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005215/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005216/// kPropertyWeak = 'W' // 'weak' property
5217/// kPropertyStrong = 'P' // property GC'able
5218/// kPropertyNonAtomic = 'N' // property non-atomic
5219/// };
5220/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005221void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005222 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005223 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005224 // Collect information from the property implementation decl(s).
5225 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005226 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005227
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005228 if (ObjCPropertyImplDecl *PropertyImpDecl =
5229 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5230 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5231 Dynamic = true;
5232 else
5233 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005234 }
5235
5236 // FIXME: This is not very efficient.
5237 S = "T";
5238
5239 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005240 // GCC has some special rules regarding encoding of properties which
5241 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005242 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005243
5244 if (PD->isReadOnly()) {
5245 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005246 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5247 S += ",C";
5248 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5249 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005250 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5251 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005252 } else {
5253 switch (PD->getSetterKind()) {
5254 case ObjCPropertyDecl::Assign: break;
5255 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005256 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005257 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005258 }
5259 }
5260
5261 // It really isn't clear at all what this means, since properties
5262 // are "dynamic by default".
5263 if (Dynamic)
5264 S += ",D";
5265
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005266 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5267 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005268
Daniel Dunbar4932b362008-08-28 04:38:10 +00005269 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5270 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005271 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005272 }
5273
5274 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5275 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005276 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005277 }
5278
5279 if (SynthesizePID) {
5280 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5281 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005282 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005283 }
5284
5285 // FIXME: OBJCGC: weak & strong
5286}
5287
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005288/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005289/// Another legacy compatibility encoding: 32-bit longs are encoded as
5290/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005291/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5292///
5293void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005294 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005295 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005296 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005297 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005298 else
Jay Foad39c79802011-01-12 09:06:06 +00005299 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005300 PointeeTy = IntTy;
5301 }
5302 }
5303}
5304
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005305void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005306 const FieldDecl *Field,
5307 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005308 // We follow the behavior of gcc, expanding structures which are
5309 // directly pointed to, and expanding embedded structures. Note that
5310 // these rules are sufficient to prevent recursive encoding of the
5311 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005312 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005313 true /* outermost type */, false, false,
5314 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005315}
5316
Joe Groff98ac7d22014-07-07 22:25:15 +00005317void ASTContext::getObjCEncodingForPropertyType(QualType T,
5318 std::string& S) const {
5319 // Encode result type.
5320 // GCC has some special rules regarding encoding of properties which
5321 // closely resembles encoding of ivars.
5322 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5323 true /* outermost type */,
5324 true /* encoding property */);
5325}
5326
John McCall393a78d2012-12-20 02:45:14 +00005327static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5328 BuiltinType::Kind kind) {
5329 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005330 case BuiltinType::Void: return 'v';
5331 case BuiltinType::Bool: return 'B';
5332 case BuiltinType::Char_U:
5333 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005334 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005335 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005336 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005337 case BuiltinType::UInt: return 'I';
5338 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005339 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005340 case BuiltinType::UInt128: return 'T';
5341 case BuiltinType::ULongLong: return 'Q';
5342 case BuiltinType::Char_S:
5343 case BuiltinType::SChar: return 'c';
5344 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005345 case BuiltinType::WChar_S:
5346 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005347 case BuiltinType::Int: return 'i';
5348 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005349 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005350 case BuiltinType::LongLong: return 'q';
5351 case BuiltinType::Int128: return 't';
5352 case BuiltinType::Float: return 'f';
5353 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005354 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005355 case BuiltinType::NullPtr: return '*'; // like char*
5356
5357 case BuiltinType::Half:
5358 // FIXME: potentially need @encodes for these!
5359 return ' ';
5360
5361 case BuiltinType::ObjCId:
5362 case BuiltinType::ObjCClass:
5363 case BuiltinType::ObjCSel:
5364 llvm_unreachable("@encoding ObjC primitive type");
5365
5366 // OpenCL and placeholder types don't need @encodings.
5367 case BuiltinType::OCLImage1d:
5368 case BuiltinType::OCLImage1dArray:
5369 case BuiltinType::OCLImage1dBuffer:
5370 case BuiltinType::OCLImage2d:
5371 case BuiltinType::OCLImage2dArray:
5372 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005373 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005374 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005375 case BuiltinType::Dependent:
5376#define BUILTIN_TYPE(KIND, ID)
5377#define PLACEHOLDER_TYPE(KIND, ID) \
5378 case BuiltinType::KIND:
5379#include "clang/AST/BuiltinTypes.def"
5380 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005381 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005382 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005383}
5384
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005385static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5386 EnumDecl *Enum = ET->getDecl();
5387
5388 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5389 if (!Enum->isFixed())
5390 return 'i';
5391
5392 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005393 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5394 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005395}
5396
Jay Foad39c79802011-01-12 09:06:06 +00005397static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005398 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005399 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005400 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005401 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5402 // The GNU runtime requires more information; bitfields are encoded as b,
5403 // then the offset (in bits) of the first element, then the type of the
5404 // bitfield, then the size in bits. For example, in this structure:
5405 //
5406 // struct
5407 // {
5408 // int integer;
5409 // int flags:2;
5410 // };
5411 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5412 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5413 // information is not especially sensible, but we're stuck with it for
5414 // compatibility with GCC, although providing it breaks anything that
5415 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005416 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005417 const RecordDecl *RD = FD->getParent();
5418 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005419 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005420 if (const EnumType *ET = T->getAs<EnumType>())
5421 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005422 else {
5423 const BuiltinType *BT = T->castAs<BuiltinType>();
5424 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5425 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005426 }
Richard Smithcaf33902011-10-10 18:28:20 +00005427 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005428}
5429
Daniel Dunbar07d07852009-10-18 21:17:35 +00005430// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005431void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5432 bool ExpandPointedToStructures,
5433 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005434 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005435 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005436 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005437 bool StructField,
5438 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005439 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005440 bool EncodePointerToObjCTypedef,
5441 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005442 CanQualType CT = getCanonicalType(T);
5443 switch (CT->getTypeClass()) {
5444 case Type::Builtin:
5445 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005446 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005447 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005448 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5449 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5450 else
5451 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005452 return;
Mike Stump11289f42009-09-09 15:08:12 +00005453
John McCall393a78d2012-12-20 02:45:14 +00005454 case Type::Complex: {
5455 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005456 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005457 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005458 return;
5459 }
John McCall393a78d2012-12-20 02:45:14 +00005460
5461 case Type::Atomic: {
5462 const AtomicType *AT = T->castAs<AtomicType>();
5463 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005464 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005465 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005466 }
John McCall393a78d2012-12-20 02:45:14 +00005467
5468 // encoding for pointer or reference types.
5469 case Type::Pointer:
5470 case Type::LValueReference:
5471 case Type::RValueReference: {
5472 QualType PointeeTy;
5473 if (isa<PointerType>(CT)) {
5474 const PointerType *PT = T->castAs<PointerType>();
5475 if (PT->isObjCSelType()) {
5476 S += ':';
5477 return;
5478 }
5479 PointeeTy = PT->getPointeeType();
5480 } else {
5481 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5482 }
5483
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005484 bool isReadOnly = false;
5485 // For historical/compatibility reasons, the read-only qualifier of the
5486 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5487 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005488 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005489 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005490 if (OutermostType && T.isConstQualified()) {
5491 isReadOnly = true;
5492 S += 'r';
5493 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005494 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005495 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005496 while (P->getAs<PointerType>())
5497 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005498 if (P.isConstQualified()) {
5499 isReadOnly = true;
5500 S += 'r';
5501 }
5502 }
5503 if (isReadOnly) {
5504 // Another legacy compatibility encoding. Some ObjC qualifier and type
5505 // combinations need to be rearranged.
5506 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005507 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005508 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005509 }
Mike Stump11289f42009-09-09 15:08:12 +00005510
Anders Carlssond8499822007-10-29 05:01:08 +00005511 if (PointeeTy->isCharType()) {
5512 // char pointer types should be encoded as '*' unless it is a
5513 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005514 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005515 S += '*';
5516 return;
5517 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005518 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005519 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5520 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5521 S += '#';
5522 return;
5523 }
5524 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5525 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5526 S += '@';
5527 return;
5528 }
5529 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005530 }
Anders Carlssond8499822007-10-29 05:01:08 +00005531 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005532 getLegacyIntegralTypeEncoding(PointeeTy);
5533
Mike Stump11289f42009-09-09 15:08:12 +00005534 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005535 nullptr, false, false, false, false, false, false,
5536 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005537 return;
5538 }
John McCall393a78d2012-12-20 02:45:14 +00005539
5540 case Type::ConstantArray:
5541 case Type::IncompleteArray:
5542 case Type::VariableArray: {
5543 const ArrayType *AT = cast<ArrayType>(CT);
5544
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005545 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005546 // Incomplete arrays are encoded as a pointer to the array element.
5547 S += '^';
5548
Mike Stump11289f42009-09-09 15:08:12 +00005549 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005550 false, ExpandStructures, FD);
5551 } else {
5552 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005553
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005554 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5555 S += llvm::utostr(CAT->getSize().getZExtValue());
5556 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005557 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005558 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5559 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005560 S += '0';
5561 }
Mike Stump11289f42009-09-09 15:08:12 +00005562
5563 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005564 false, ExpandStructures, FD,
5565 false, false, false, false, false, false,
5566 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005567 S += ']';
5568 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005569 return;
5570 }
Mike Stump11289f42009-09-09 15:08:12 +00005571
John McCall393a78d2012-12-20 02:45:14 +00005572 case Type::FunctionNoProto:
5573 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005574 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005575 return;
Mike Stump11289f42009-09-09 15:08:12 +00005576
John McCall393a78d2012-12-20 02:45:14 +00005577 case Type::Record: {
5578 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005579 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005580 // Anonymous structures print as '?'
5581 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5582 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005583 if (ClassTemplateSpecializationDecl *Spec
5584 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5585 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005586 llvm::raw_string_ostream OS(S);
5587 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005588 TemplateArgs.data(),
5589 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005590 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005591 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005592 } else {
5593 S += '?';
5594 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005595 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005596 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005597 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005598 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005599 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005600 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005601 if (FD) {
5602 S += '"';
5603 S += Field->getNameAsString();
5604 S += '"';
5605 }
Mike Stump11289f42009-09-09 15:08:12 +00005606
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005607 // Special case bit-fields.
5608 if (Field->isBitField()) {
5609 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005610 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005611 } else {
5612 QualType qt = Field->getType();
5613 getLegacyIntegralTypeEncoding(qt);
5614 getObjCEncodingForTypeImpl(qt, S, false, true,
5615 FD, /*OutermostType*/false,
5616 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005617 /*StructField*/true,
5618 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005619 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005620 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005621 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005622 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005623 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005624 return;
5625 }
Mike Stump11289f42009-09-09 15:08:12 +00005626
John McCall393a78d2012-12-20 02:45:14 +00005627 case Type::BlockPointer: {
5628 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005629 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005630 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005631 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005632
5633 S += '<';
5634 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005635 getObjCEncodingForTypeImpl(
5636 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5637 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005638 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5639 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005640 // Block self
5641 S += "@?";
5642 // Block parameters
5643 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005644 for (const auto &I : FPT->param_types())
5645 getObjCEncodingForTypeImpl(
5646 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5647 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005648 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5649 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005650 }
5651 S += '>';
5652 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005653 return;
5654 }
Mike Stump11289f42009-09-09 15:08:12 +00005655
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005656 case Type::ObjCObject: {
5657 // hack to match legacy encoding of *id and *Class
5658 QualType Ty = getObjCObjectPointerType(CT);
5659 if (Ty->isObjCIdType()) {
5660 S += "{objc_object=}";
5661 return;
5662 }
5663 else if (Ty->isObjCClassType()) {
5664 S += "{objc_class=}";
5665 return;
5666 }
5667 }
5668
John McCall393a78d2012-12-20 02:45:14 +00005669 case Type::ObjCInterface: {
5670 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005671 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005672 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005673 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005674 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005675 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005676 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005677 DeepCollectObjCIvars(OI, true, Ivars);
5678 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005679 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005680 if (Field->isBitField())
5681 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005682 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005683 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5684 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005685 EncodePointerToObjCTypedef,
5686 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005687 }
5688 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005689 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005690 }
Mike Stump11289f42009-09-09 15:08:12 +00005691
John McCall393a78d2012-12-20 02:45:14 +00005692 case Type::ObjCObjectPointer: {
5693 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005694 if (OPT->isObjCIdType()) {
5695 S += '@';
5696 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005697 }
Mike Stump11289f42009-09-09 15:08:12 +00005698
Steve Narofff0c86112009-10-28 22:03:49 +00005699 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5700 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5701 // Since this is a binary compatibility issue, need to consult with runtime
5702 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005703 S += '#';
5704 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005705 }
Mike Stump11289f42009-09-09 15:08:12 +00005706
Chris Lattnere7cabb92009-07-13 00:10:46 +00005707 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005708 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005709 ExpandPointedToStructures,
5710 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005711 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005712 // Note that we do extended encoding of protocol qualifer list
5713 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005714 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005715 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005716 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005717 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005718 S += '>';
5719 }
5720 S += '"';
5721 }
5722 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005723 }
Mike Stump11289f42009-09-09 15:08:12 +00005724
Chris Lattnere7cabb92009-07-13 00:10:46 +00005725 QualType PointeeTy = OPT->getPointeeType();
5726 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005727 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5728 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005729 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005730 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005731 // {...};
5732 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005733 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005734 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005735 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5736 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5737 DeepCollectObjCIvars(OI, true, Ivars);
5738 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5739 if (cast<FieldDecl>(Ivars[i]) == FD) {
5740 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005741 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005742 S += '}';
5743 return;
5744 }
5745 }
5746 }
Mike Stump11289f42009-09-09 15:08:12 +00005747 getObjCEncodingForTypeImpl(PointeeTy, S,
5748 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005749 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005750 false, false, false, false, false,
5751 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005752 return;
5753 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005754
5755 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005756 if (OPT->getInterfaceDecl() &&
5757 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005758 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005759 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005760 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005761 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005762 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005763 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005764 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005765 S += '"';
5766 }
5767 return;
5768 }
Mike Stump11289f42009-09-09 15:08:12 +00005769
John McCalla9e6e8d2010-05-17 23:56:34 +00005770 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005771 // FIXME: we shoul do better than that. 'M' is available.
5772 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005773 // This matches gcc's encoding, even though technically it is insufficient.
5774 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005775 case Type::Vector:
5776 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005777 // Until we have a coherent encoding of these three types, issue warning.
5778 { if (NotEncodedT)
5779 *NotEncodedT = T;
5780 return;
5781 }
5782
5783 // We could see an undeduced auto type here during error recovery.
5784 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005785 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005786 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005787
Richard Smith27d807c2013-04-30 13:56:41 +00005788
John McCall393a78d2012-12-20 02:45:14 +00005789#define ABSTRACT_TYPE(KIND, BASE)
5790#define TYPE(KIND, BASE)
5791#define DEPENDENT_TYPE(KIND, BASE) \
5792 case Type::KIND:
5793#define NON_CANONICAL_TYPE(KIND, BASE) \
5794 case Type::KIND:
5795#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5796 case Type::KIND:
5797#include "clang/AST/TypeNodes.def"
5798 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005799 }
John McCall393a78d2012-12-20 02:45:14 +00005800 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005801}
5802
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005803void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5804 std::string &S,
5805 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005806 bool includeVBases,
5807 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005808 assert(RDecl && "Expected non-null RecordDecl");
5809 assert(!RDecl->isUnion() && "Should not be called for unions");
5810 if (!RDecl->getDefinition())
5811 return;
5812
5813 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5814 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5815 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5816
5817 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005818 for (const auto &BI : CXXRec->bases()) {
5819 if (!BI.isVirtual()) {
5820 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005821 if (base->isEmpty())
5822 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005823 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005824 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5825 std::make_pair(offs, base));
5826 }
5827 }
5828 }
5829
5830 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005831 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005832 uint64_t offs = layout.getFieldOffset(i);
5833 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005834 std::make_pair(offs, Field));
5835 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005836 }
5837
5838 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005839 for (const auto &BI : CXXRec->vbases()) {
5840 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005841 if (base->isEmpty())
5842 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005843 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005844 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5845 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005846 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5847 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005848 }
5849 }
5850
5851 CharUnits size;
5852 if (CXXRec) {
5853 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5854 } else {
5855 size = layout.getSize();
5856 }
5857
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005858#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005859 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005860#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005861 std::multimap<uint64_t, NamedDecl *>::iterator
5862 CurLayObj = FieldOrBaseOffsets.begin();
5863
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005864 if (CXXRec && CXXRec->isDynamicClass() &&
5865 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005866 if (FD) {
5867 S += "\"_vptr$";
5868 std::string recname = CXXRec->getNameAsString();
5869 if (recname.empty()) recname = "?";
5870 S += recname;
5871 S += '"';
5872 }
5873 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005874#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005875 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005876#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005877 }
5878
5879 if (!RDecl->hasFlexibleArrayMember()) {
5880 // Mark the end of the structure.
5881 uint64_t offs = toBits(size);
5882 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005883 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005884 }
5885
5886 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005887#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005888 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005889 if (CurOffs < CurLayObj->first) {
5890 uint64_t padding = CurLayObj->first - CurOffs;
5891 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5892 // packing/alignment of members is different that normal, in which case
5893 // the encoding will be out-of-sync with the real layout.
5894 // If the runtime switches to just consider the size of types without
5895 // taking into account alignment, we could make padding explicit in the
5896 // encoding (e.g. using arrays of chars). The encoding strings would be
5897 // longer then though.
5898 CurOffs += padding;
5899 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005900#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005901
5902 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005903 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005904 break; // reached end of structure.
5905
5906 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5907 // We expand the bases without their virtual bases since those are going
5908 // in the initial structure. Note that this differs from gcc which
5909 // expands virtual bases each time one is encountered in the hierarchy,
5910 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005911 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5912 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005913 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005914#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005915 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005916#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005917 } else {
5918 FieldDecl *field = cast<FieldDecl>(dcl);
5919 if (FD) {
5920 S += '"';
5921 S += field->getNameAsString();
5922 S += '"';
5923 }
5924
5925 if (field->isBitField()) {
5926 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005927#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005928 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005929#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005930 } else {
5931 QualType qt = field->getType();
5932 getLegacyIntegralTypeEncoding(qt);
5933 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5934 /*OutermostType*/false,
5935 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005936 /*StructField*/true,
5937 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005938#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005939 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005940#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005941 }
5942 }
5943 }
5944}
5945
Mike Stump11289f42009-09-09 15:08:12 +00005946void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005947 std::string& S) const {
5948 if (QT & Decl::OBJC_TQ_In)
5949 S += 'n';
5950 if (QT & Decl::OBJC_TQ_Inout)
5951 S += 'N';
5952 if (QT & Decl::OBJC_TQ_Out)
5953 S += 'o';
5954 if (QT & Decl::OBJC_TQ_Bycopy)
5955 S += 'O';
5956 if (QT & Decl::OBJC_TQ_Byref)
5957 S += 'R';
5958 if (QT & Decl::OBJC_TQ_Oneway)
5959 S += 'V';
5960}
5961
Douglas Gregor3ea72692011-08-12 05:46:01 +00005962TypedefDecl *ASTContext::getObjCIdDecl() const {
5963 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00005964 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00005965 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005966 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005967 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005968 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005969}
5970
Douglas Gregor52e02802011-08-12 06:17:30 +00005971TypedefDecl *ASTContext::getObjCSelDecl() const {
5972 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005973 QualType T = getPointerType(ObjCBuiltinSelTy);
5974 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005975 }
5976 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005977}
5978
Douglas Gregor0a586182011-08-12 05:59:41 +00005979TypedefDecl *ASTContext::getObjCClassDecl() const {
5980 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00005981 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00005982 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005983 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005984 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005985 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005986}
5987
Douglas Gregord53ae832012-01-17 18:09:05 +00005988ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5989 if (!ObjCProtocolClassDecl) {
5990 ObjCProtocolClassDecl
5991 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5992 SourceLocation(),
5993 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00005994 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00005995 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005996 SourceLocation(), true);
5997 }
5998
5999 return ObjCProtocolClassDecl;
6000}
6001
Meador Inge5d3fb222012-06-16 03:34:49 +00006002//===----------------------------------------------------------------------===//
6003// __builtin_va_list Construction Functions
6004//===----------------------------------------------------------------------===//
6005
6006static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6007 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006008 QualType T = Context->getPointerType(Context->CharTy);
6009 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006010}
6011
6012static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6013 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006014 QualType T = Context->getPointerType(Context->VoidTy);
6015 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006016}
6017
Tim Northover9bb857a2013-01-31 12:13:10 +00006018static TypedefDecl *
6019CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006020 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006021 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006022 if (Context->getLangOpts().CPlusPlus) {
6023 // namespace std { struct __va_list {
6024 NamespaceDecl *NS;
6025 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6026 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006027 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006028 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006029 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006030 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006031 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006032 }
6033
6034 VaListTagDecl->startDefinition();
6035
6036 const size_t NumFields = 5;
6037 QualType FieldTypes[NumFields];
6038 const char *FieldNames[NumFields];
6039
6040 // void *__stack;
6041 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6042 FieldNames[0] = "__stack";
6043
6044 // void *__gr_top;
6045 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6046 FieldNames[1] = "__gr_top";
6047
6048 // void *__vr_top;
6049 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6050 FieldNames[2] = "__vr_top";
6051
6052 // int __gr_offs;
6053 FieldTypes[3] = Context->IntTy;
6054 FieldNames[3] = "__gr_offs";
6055
6056 // int __vr_offs;
6057 FieldTypes[4] = Context->IntTy;
6058 FieldNames[4] = "__vr_offs";
6059
6060 // Create fields
6061 for (unsigned i = 0; i < NumFields; ++i) {
6062 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6063 VaListTagDecl,
6064 SourceLocation(),
6065 SourceLocation(),
6066 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006067 FieldTypes[i], /*TInfo=*/nullptr,
6068 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006069 /*Mutable=*/false,
6070 ICIS_NoInit);
6071 Field->setAccess(AS_public);
6072 VaListTagDecl->addDecl(Field);
6073 }
6074 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006075 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006076 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006077
6078 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006079 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006080}
6081
Meador Inge5d3fb222012-06-16 03:34:49 +00006082static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6083 // typedef struct __va_list_tag {
6084 RecordDecl *VaListTagDecl;
6085
Alp Toker2dea15b2013-12-17 01:22:38 +00006086 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006087 VaListTagDecl->startDefinition();
6088
6089 const size_t NumFields = 5;
6090 QualType FieldTypes[NumFields];
6091 const char *FieldNames[NumFields];
6092
6093 // unsigned char gpr;
6094 FieldTypes[0] = Context->UnsignedCharTy;
6095 FieldNames[0] = "gpr";
6096
6097 // unsigned char fpr;
6098 FieldTypes[1] = Context->UnsignedCharTy;
6099 FieldNames[1] = "fpr";
6100
6101 // unsigned short reserved;
6102 FieldTypes[2] = Context->UnsignedShortTy;
6103 FieldNames[2] = "reserved";
6104
6105 // void* overflow_arg_area;
6106 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6107 FieldNames[3] = "overflow_arg_area";
6108
6109 // void* reg_save_area;
6110 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6111 FieldNames[4] = "reg_save_area";
6112
6113 // Create fields
6114 for (unsigned i = 0; i < NumFields; ++i) {
6115 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6116 SourceLocation(),
6117 SourceLocation(),
6118 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006119 FieldTypes[i], /*TInfo=*/nullptr,
6120 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006121 /*Mutable=*/false,
6122 ICIS_NoInit);
6123 Field->setAccess(AS_public);
6124 VaListTagDecl->addDecl(Field);
6125 }
6126 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006127 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006128 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6129
6130 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006131 TypedefDecl *VaListTagTypedefDecl =
6132 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6133
Meador Inge5d3fb222012-06-16 03:34:49 +00006134 QualType VaListTagTypedefType =
6135 Context->getTypedefType(VaListTagTypedefDecl);
6136
6137 // typedef __va_list_tag __builtin_va_list[1];
6138 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6139 QualType VaListTagArrayType
6140 = Context->getConstantArrayType(VaListTagTypedefType,
6141 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006142 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006143}
6144
6145static TypedefDecl *
6146CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006147 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006148 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006149 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006150 VaListTagDecl->startDefinition();
6151
6152 const size_t NumFields = 4;
6153 QualType FieldTypes[NumFields];
6154 const char *FieldNames[NumFields];
6155
6156 // unsigned gp_offset;
6157 FieldTypes[0] = Context->UnsignedIntTy;
6158 FieldNames[0] = "gp_offset";
6159
6160 // unsigned fp_offset;
6161 FieldTypes[1] = Context->UnsignedIntTy;
6162 FieldNames[1] = "fp_offset";
6163
6164 // void* overflow_arg_area;
6165 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6166 FieldNames[2] = "overflow_arg_area";
6167
6168 // void* reg_save_area;
6169 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6170 FieldNames[3] = "reg_save_area";
6171
6172 // Create fields
6173 for (unsigned i = 0; i < NumFields; ++i) {
6174 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6175 VaListTagDecl,
6176 SourceLocation(),
6177 SourceLocation(),
6178 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006179 FieldTypes[i], /*TInfo=*/nullptr,
6180 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006181 /*Mutable=*/false,
6182 ICIS_NoInit);
6183 Field->setAccess(AS_public);
6184 VaListTagDecl->addDecl(Field);
6185 }
6186 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006187 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006188 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6189
Richard Smith9b88a4c2015-07-27 05:40:23 +00006190 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006191
Richard Smith9b88a4c2015-07-27 05:40:23 +00006192 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006193 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006194 QualType VaListTagArrayType =
6195 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006196 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006197}
6198
6199static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6200 // typedef int __builtin_va_list[4];
6201 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6202 QualType IntArrayType
6203 = Context->getConstantArrayType(Context->IntTy,
6204 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006205 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006206}
6207
Logan Chien57086ce2012-10-10 06:56:20 +00006208static TypedefDecl *
6209CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006210 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006211 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006212 if (Context->getLangOpts().CPlusPlus) {
6213 // namespace std { struct __va_list {
6214 NamespaceDecl *NS;
6215 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6216 Context->getTranslationUnitDecl(),
6217 /*Inline*/false, SourceLocation(),
6218 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006219 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006220 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006221 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006222 }
6223
6224 VaListDecl->startDefinition();
6225
6226 // void * __ap;
6227 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6228 VaListDecl,
6229 SourceLocation(),
6230 SourceLocation(),
6231 &Context->Idents.get("__ap"),
6232 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006233 /*TInfo=*/nullptr,
6234 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006235 /*Mutable=*/false,
6236 ICIS_NoInit);
6237 Field->setAccess(AS_public);
6238 VaListDecl->addDecl(Field);
6239
6240 // };
6241 VaListDecl->completeDefinition();
6242
6243 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006244 QualType T = Context->getRecordType(VaListDecl);
6245 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006246}
6247
Ulrich Weigand47445072013-05-06 16:26:41 +00006248static TypedefDecl *
6249CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006250 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006251 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006252 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006253 VaListTagDecl->startDefinition();
6254
6255 const size_t NumFields = 4;
6256 QualType FieldTypes[NumFields];
6257 const char *FieldNames[NumFields];
6258
6259 // long __gpr;
6260 FieldTypes[0] = Context->LongTy;
6261 FieldNames[0] = "__gpr";
6262
6263 // long __fpr;
6264 FieldTypes[1] = Context->LongTy;
6265 FieldNames[1] = "__fpr";
6266
6267 // void *__overflow_arg_area;
6268 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6269 FieldNames[2] = "__overflow_arg_area";
6270
6271 // void *__reg_save_area;
6272 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6273 FieldNames[3] = "__reg_save_area";
6274
6275 // Create fields
6276 for (unsigned i = 0; i < NumFields; ++i) {
6277 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6278 VaListTagDecl,
6279 SourceLocation(),
6280 SourceLocation(),
6281 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006282 FieldTypes[i], /*TInfo=*/nullptr,
6283 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006284 /*Mutable=*/false,
6285 ICIS_NoInit);
6286 Field->setAccess(AS_public);
6287 VaListTagDecl->addDecl(Field);
6288 }
6289 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006290 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006291 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006292
Richard Smith9b88a4c2015-07-27 05:40:23 +00006293 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006294
6295 // typedef __va_list_tag __builtin_va_list[1];
6296 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006297 QualType VaListTagArrayType =
6298 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006299
Alp Toker56b5cc92013-12-15 10:36:26 +00006300 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006301}
6302
Meador Inge5d3fb222012-06-16 03:34:49 +00006303static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6304 TargetInfo::BuiltinVaListKind Kind) {
6305 switch (Kind) {
6306 case TargetInfo::CharPtrBuiltinVaList:
6307 return CreateCharPtrBuiltinVaListDecl(Context);
6308 case TargetInfo::VoidPtrBuiltinVaList:
6309 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006310 case TargetInfo::AArch64ABIBuiltinVaList:
6311 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006312 case TargetInfo::PowerABIBuiltinVaList:
6313 return CreatePowerABIBuiltinVaListDecl(Context);
6314 case TargetInfo::X86_64ABIBuiltinVaList:
6315 return CreateX86_64ABIBuiltinVaListDecl(Context);
6316 case TargetInfo::PNaClABIBuiltinVaList:
6317 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006318 case TargetInfo::AAPCSABIBuiltinVaList:
6319 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006320 case TargetInfo::SystemZBuiltinVaList:
6321 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006322 }
6323
6324 llvm_unreachable("Unhandled __builtin_va_list type kind");
6325}
6326
6327TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006328 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006329 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006330 assert(BuiltinVaListDecl->isImplicit());
6331 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006332
6333 return BuiltinVaListDecl;
6334}
6335
Richard Smith9b88a4c2015-07-27 05:40:23 +00006336Decl *ASTContext::getVaListTagDecl() const {
6337 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006338 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006339 if (!VaListTagDecl)
6340 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006341
Richard Smith9b88a4c2015-07-27 05:40:23 +00006342 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006343}
6344
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006345void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006346 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006347 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006348
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006349 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006350}
6351
John McCalld28ae272009-12-02 08:04:21 +00006352/// \brief Retrieve the template name that corresponds to a non-empty
6353/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006354TemplateName
6355ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6356 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006357 unsigned size = End - Begin;
6358 assert(size > 1 && "set is not overloaded!");
6359
6360 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6361 size * sizeof(FunctionTemplateDecl*));
6362 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6363
6364 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006365 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006366 NamedDecl *D = *I;
6367 assert(isa<FunctionTemplateDecl>(D) ||
6368 (isa<UsingShadowDecl>(D) &&
6369 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6370 *Storage++ = D;
6371 }
6372
6373 return TemplateName(OT);
6374}
6375
Douglas Gregordc572a32009-03-30 22:58:21 +00006376/// \brief Retrieve the template name that represents a qualified
6377/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006378TemplateName
6379ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6380 bool TemplateKeyword,
6381 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006382 assert(NNS && "Missing nested-name-specifier in qualified template name");
6383
Douglas Gregorc42075a2010-02-04 18:10:26 +00006384 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006385 llvm::FoldingSetNodeID ID;
6386 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6387
Craig Topper36250ad2014-05-12 05:36:57 +00006388 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006389 QualifiedTemplateName *QTN =
6390 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6391 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006392 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6393 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006394 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6395 }
6396
6397 return TemplateName(QTN);
6398}
6399
6400/// \brief Retrieve the template name that represents a dependent
6401/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006402TemplateName
6403ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6404 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006405 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006406 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006407
6408 llvm::FoldingSetNodeID ID;
6409 DependentTemplateName::Profile(ID, NNS, Name);
6410
Craig Topper36250ad2014-05-12 05:36:57 +00006411 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006412 DependentTemplateName *QTN =
6413 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6414
6415 if (QTN)
6416 return TemplateName(QTN);
6417
6418 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6419 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006420 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6421 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006422 } else {
6423 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006424 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6425 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006426 DependentTemplateName *CheckQTN =
6427 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6428 assert(!CheckQTN && "Dependent type name canonicalization broken");
6429 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006430 }
6431
6432 DependentTemplateNames.InsertNode(QTN, InsertPos);
6433 return TemplateName(QTN);
6434}
6435
Douglas Gregor71395fa2009-11-04 00:56:37 +00006436/// \brief Retrieve the template name that represents a dependent
6437/// template name such as \c MetaFun::template operator+.
6438TemplateName
6439ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006440 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006441 assert((!NNS || NNS->isDependent()) &&
6442 "Nested name specifier must be dependent");
6443
6444 llvm::FoldingSetNodeID ID;
6445 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006446
6447 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006448 DependentTemplateName *QTN
6449 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006450
6451 if (QTN)
6452 return TemplateName(QTN);
6453
6454 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6455 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006456 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6457 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006458 } else {
6459 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006460 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6461 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006462
6463 DependentTemplateName *CheckQTN
6464 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6465 assert(!CheckQTN && "Dependent template name canonicalization broken");
6466 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006467 }
6468
6469 DependentTemplateNames.InsertNode(QTN, InsertPos);
6470 return TemplateName(QTN);
6471}
6472
Douglas Gregor5590be02011-01-15 06:45:20 +00006473TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006474ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6475 TemplateName replacement) const {
6476 llvm::FoldingSetNodeID ID;
6477 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006478
6479 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006480 SubstTemplateTemplateParmStorage *subst
6481 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6482
6483 if (!subst) {
6484 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6485 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6486 }
6487
6488 return TemplateName(subst);
6489}
6490
6491TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006492ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6493 const TemplateArgument &ArgPack) const {
6494 ASTContext &Self = const_cast<ASTContext &>(*this);
6495 llvm::FoldingSetNodeID ID;
6496 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006497
6498 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006499 SubstTemplateTemplateParmPackStorage *Subst
6500 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6501
6502 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006503 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006504 ArgPack.pack_size(),
6505 ArgPack.pack_begin());
6506 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6507 }
6508
6509 return TemplateName(Subst);
6510}
6511
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006512/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006513/// TargetInfo, produce the corresponding type. The unsigned @p Type
6514/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006515CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006516 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006517 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006518 case TargetInfo::SignedChar: return SignedCharTy;
6519 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006520 case TargetInfo::SignedShort: return ShortTy;
6521 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6522 case TargetInfo::SignedInt: return IntTy;
6523 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6524 case TargetInfo::SignedLong: return LongTy;
6525 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6526 case TargetInfo::SignedLongLong: return LongLongTy;
6527 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6528 }
6529
David Blaikie83d382b2011-09-23 05:06:16 +00006530 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006531}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006532
6533//===----------------------------------------------------------------------===//
6534// Type Predicates.
6535//===----------------------------------------------------------------------===//
6536
Fariborz Jahanian96207692009-02-18 21:49:28 +00006537/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6538/// garbage collection attribute.
6539///
John McCall553d45a2011-01-12 00:34:59 +00006540Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006541 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006542 return Qualifiers::GCNone;
6543
David Blaikiebbafb8a2012-03-11 07:00:24 +00006544 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006545 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6546
6547 // Default behaviour under objective-C's gc is for ObjC pointers
6548 // (or pointers to them) be treated as though they were declared
6549 // as __strong.
6550 if (GCAttrs == Qualifiers::GCNone) {
6551 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6552 return Qualifiers::Strong;
6553 else if (Ty->isPointerType())
6554 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6555 } else {
6556 // It's not valid to set GC attributes on anything that isn't a
6557 // pointer.
6558#ifndef NDEBUG
6559 QualType CT = Ty->getCanonicalTypeInternal();
6560 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6561 CT = AT->getElementType();
6562 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6563#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006564 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006565 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006566}
6567
Chris Lattner49af6a42008-04-07 06:51:04 +00006568//===----------------------------------------------------------------------===//
6569// Type Compatibility Testing
6570//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006571
Mike Stump11289f42009-09-09 15:08:12 +00006572/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006573/// compatible.
6574static bool areCompatVectorTypes(const VectorType *LHS,
6575 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006576 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006577 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006578 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006579}
6580
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006581bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6582 QualType SecondVec) {
6583 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6584 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6585
6586 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6587 return true;
6588
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006589 // Treat Neon vector types and most AltiVec vector types as if they are the
6590 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006591 const VectorType *First = FirstVec->getAs<VectorType>();
6592 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006593 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006594 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006595 First->getVectorKind() != VectorType::AltiVecPixel &&
6596 First->getVectorKind() != VectorType::AltiVecBool &&
6597 Second->getVectorKind() != VectorType::AltiVecPixel &&
6598 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006599 return true;
6600
6601 return false;
6602}
6603
Steve Naroff8e6aee52009-07-23 01:01:38 +00006604//===----------------------------------------------------------------------===//
6605// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6606//===----------------------------------------------------------------------===//
6607
6608/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6609/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006610bool
6611ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6612 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006613 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006614 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006615 for (auto *PI : rProto->protocols())
6616 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006617 return true;
6618 return false;
6619}
6620
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006621/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6622/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006623bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6624 QualType rhs) {
6625 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6626 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6627 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6628
Aaron Ballman83731462014-03-17 16:14:00 +00006629 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006630 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006631 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006632 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6633 match = true;
6634 break;
6635 }
6636 }
6637 if (!match)
6638 return false;
6639 }
6640 return true;
6641}
6642
Steve Naroff8e6aee52009-07-23 01:01:38 +00006643/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6644/// ObjCQualifiedIDType.
6645bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6646 bool compare) {
6647 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006648 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006649 lhs->isObjCIdType() || lhs->isObjCClassType())
6650 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006651 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006652 rhs->isObjCIdType() || rhs->isObjCClassType())
6653 return true;
6654
6655 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006656 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006657
Steve Naroff8e6aee52009-07-23 01:01:38 +00006658 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006659
Steve Naroff8e6aee52009-07-23 01:01:38 +00006660 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006661 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006662 // make sure we check the class hierarchy.
6663 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006664 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006665 // when comparing an id<P> on lhs with a static type on rhs,
6666 // see if static class implements all of id's protocols, directly or
6667 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006668 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006669 return false;
6670 }
6671 }
6672 // If there are no qualifiers and no interface, we have an 'id'.
6673 return true;
6674 }
Mike Stump11289f42009-09-09 15:08:12 +00006675 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006676 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006677 bool match = false;
6678
6679 // when comparing an id<P> on lhs with a static type on rhs,
6680 // see if static class implements all of id's protocols, directly or
6681 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006682 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006683 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6684 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6685 match = true;
6686 break;
6687 }
6688 }
Mike Stump11289f42009-09-09 15:08:12 +00006689 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006690 // make sure we check the class hierarchy.
6691 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006692 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006693 // when comparing an id<P> on lhs with a static type on rhs,
6694 // see if static class implements all of id's protocols, directly or
6695 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006696 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006697 match = true;
6698 break;
6699 }
6700 }
6701 }
6702 if (!match)
6703 return false;
6704 }
Mike Stump11289f42009-09-09 15:08:12 +00006705
Steve Naroff8e6aee52009-07-23 01:01:38 +00006706 return true;
6707 }
Mike Stump11289f42009-09-09 15:08:12 +00006708
Steve Naroff8e6aee52009-07-23 01:01:38 +00006709 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6710 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6711
Mike Stump11289f42009-09-09 15:08:12 +00006712 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006713 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006714 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006715 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006716 bool match = false;
6717
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006718 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006719 // see if static class implements all of id's protocols, directly or
6720 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006721 // First, lhs protocols in the qualifier list must be found, direct
6722 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006723 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006724 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6725 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6726 match = true;
6727 break;
6728 }
6729 }
6730 if (!match)
6731 return false;
6732 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006733
6734 // Static class's protocols, or its super class or category protocols
6735 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6736 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6737 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6738 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6739 // This is rather dubious but matches gcc's behavior. If lhs has
6740 // no type qualifier and its class has no static protocol(s)
6741 // assume that it is mismatch.
6742 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6743 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006744 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006745 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006746 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006747 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6748 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6749 match = true;
6750 break;
6751 }
6752 }
6753 if (!match)
6754 return false;
6755 }
6756 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006757 return true;
6758 }
6759 return false;
6760}
6761
Eli Friedman47f77112008-08-22 00:56:42 +00006762/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006763/// compatible for assignment from RHS to LHS. This handles validation of any
6764/// protocol qualifiers on the LHS or RHS.
6765///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006766bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6767 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006768 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6769 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6770
Steve Naroff1329fa02009-07-15 18:40:39 +00006771 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006772 if (LHS->isObjCUnqualifiedIdOrClass() ||
6773 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006774 return true;
6775
Douglas Gregorab209d82015-07-07 03:58:42 +00006776 // Function object that propagates a successful result or handles
6777 // __kindof types.
6778 auto finish = [&](bool succeeded) -> bool {
6779 if (succeeded)
6780 return true;
6781
6782 if (!RHS->isKindOfType())
6783 return false;
6784
6785 // Strip off __kindof and protocol qualifiers, then check whether
6786 // we can assign the other way.
6787 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6788 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6789 };
6790
6791 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6792 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6793 QualType(RHSOPT,0),
6794 false));
6795 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006796
Douglas Gregorab209d82015-07-07 03:58:42 +00006797 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6798 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6799 QualType(RHSOPT,0)));
6800 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006801
John McCall8b07ec22010-05-15 11:32:37 +00006802 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006803 if (LHS->getInterface() && RHS->getInterface()) {
6804 return finish(canAssignObjCInterfaces(LHS, RHS));
6805 }
Mike Stump11289f42009-09-09 15:08:12 +00006806
Steve Naroff8e6aee52009-07-23 01:01:38 +00006807 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006808}
6809
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006810/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006811/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006812/// arguments in block literals. When passed as arguments, passing 'A*' where
6813/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6814/// not OK. For the return type, the opposite is not OK.
6815bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6816 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006817 const ObjCObjectPointerType *RHSOPT,
6818 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006819
6820 // Function object that propagates a successful result or handles
6821 // __kindof types.
6822 auto finish = [&](bool succeeded) -> bool {
6823 if (succeeded)
6824 return true;
6825
6826 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6827 if (!Expected->isKindOfType())
6828 return false;
6829
6830 // Strip off __kindof and protocol qualifiers, then check whether
6831 // we can assign the other way.
6832 return canAssignObjCInterfacesInBlockPointer(
6833 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6834 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6835 BlockReturnType);
6836 };
6837
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006838 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006839 return true;
6840
6841 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006842 return finish(RHSOPT->isObjCBuiltinType() ||
6843 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006844 }
6845
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006846 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006847 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6848 QualType(RHSOPT,0),
6849 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006850
6851 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6852 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6853 if (LHS && RHS) { // We have 2 user-defined types.
6854 if (LHS != RHS) {
6855 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006856 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006857 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006858 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006859 }
6860 else
6861 return true;
6862 }
6863 return false;
6864}
6865
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006866/// Comparison routine for Objective-C protocols to be used with
6867/// llvm::array_pod_sort.
6868static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6869 ObjCProtocolDecl * const *rhs) {
6870 return (*lhs)->getName().compare((*rhs)->getName());
6871
6872}
6873
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006874/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006875/// of protocols inherited from two distinct objective-c pointer objects with
6876/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006877/// It is used to build composite qualifier list of the composite type of
6878/// the conditional expression involving two objective-c pointer objects.
6879static
6880void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006881 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006882 const ObjCObjectPointerType *LHSOPT,
6883 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006884 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006885
John McCall8b07ec22010-05-15 11:32:37 +00006886 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6887 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6888 assert(LHS->getInterface() && "LHS must have an interface base");
6889 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006890
6891 // Add all of the protocols for the LHS.
6892 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6893
6894 // Start with the protocol qualifiers.
6895 for (auto proto : LHS->quals()) {
6896 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006897 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006898
6899 // Also add the protocols associated with the LHS interface.
6900 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6901
6902 // Add all of the protocls for the RHS.
6903 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6904
6905 // Start with the protocol qualifiers.
6906 for (auto proto : RHS->quals()) {
6907 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006908 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006909
6910 // Also add the protocols associated with the RHS interface.
6911 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6912
6913 // Compute the intersection of the collected protocol sets.
6914 for (auto proto : LHSProtocolSet) {
6915 if (RHSProtocolSet.count(proto))
6916 IntersectionSet.push_back(proto);
6917 }
6918
6919 // Compute the set of protocols that is implied by either the common type or
6920 // the protocols within the intersection.
6921 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6922 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6923
6924 // Remove any implied protocols from the list of inherited protocols.
6925 if (!ImpliedProtocols.empty()) {
6926 IntersectionSet.erase(
6927 std::remove_if(IntersectionSet.begin(),
6928 IntersectionSet.end(),
6929 [&](ObjCProtocolDecl *proto) -> bool {
6930 return ImpliedProtocols.count(proto) > 0;
6931 }),
6932 IntersectionSet.end());
6933 }
6934
6935 // Sort the remaining protocols by name.
6936 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
6937 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006938}
6939
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006940/// Determine whether the first type is a subtype of the second.
6941static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
6942 QualType rhs) {
6943 // Common case: two object pointers.
6944 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
6945 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6946 if (lhsOPT && rhsOPT)
6947 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
6948
6949 // Two block pointers.
6950 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
6951 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
6952 if (lhsBlock && rhsBlock)
6953 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
6954
6955 // If either is an unqualified 'id' and the other is a block, it's
6956 // acceptable.
6957 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
6958 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
6959 return true;
6960
6961 return false;
6962}
6963
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006964// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006965static bool sameObjCTypeArgs(ASTContext &ctx,
6966 const ObjCInterfaceDecl *iface,
6967 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00006968 ArrayRef<QualType> rhsArgs,
6969 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006970 if (lhsArgs.size() != rhsArgs.size())
6971 return false;
6972
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006973 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006974 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006975 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
6976 continue;
6977
6978 switch (typeParams->begin()[i]->getVariance()) {
6979 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00006980 if (!stripKindOf ||
6981 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
6982 rhsArgs[i].stripObjCKindOfType(ctx))) {
6983 return false;
6984 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006985 break;
6986
6987 case ObjCTypeParamVariance::Covariant:
6988 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
6989 return false;
6990 break;
6991
6992 case ObjCTypeParamVariance::Contravariant:
6993 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
6994 return false;
6995 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00006996 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006997 }
6998
6999 return true;
7000}
7001
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007002QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007003 const ObjCObjectPointerType *Lptr,
7004 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007005 const ObjCObjectType *LHS = Lptr->getObjectType();
7006 const ObjCObjectType *RHS = Rptr->getObjectType();
7007 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7008 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007009
7010 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007011 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007012
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007013 // Follow the left-hand side up the class hierarchy until we either hit a
7014 // root or find the RHS. Record the ancestors in case we don't find it.
7015 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7016 LHSAncestors;
7017 while (true) {
7018 // Record this ancestor. We'll need this if the common type isn't in the
7019 // path from the LHS to the root.
7020 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007021
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007022 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7023 // Get the type arguments.
7024 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7025 bool anyChanges = false;
7026 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7027 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007028 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7029 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007030 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007031 return QualType();
7032 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7033 // If only one has type arguments, the result will not have type
7034 // arguments.
7035 LHSTypeArgs = { };
7036 anyChanges = true;
7037 }
7038
7039 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007040 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007041 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7042 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007043 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007044 anyChanges = true;
7045
7046 // If anything in the LHS will have changed, build a new result type.
7047 if (anyChanges) {
7048 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007049 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7050 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007051 return getObjCObjectPointerType(Result);
7052 }
7053
7054 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007055 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007056
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007057 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007058 QualType LHSSuperType = LHS->getSuperClassType();
7059 if (LHSSuperType.isNull())
7060 break;
7061
7062 LHS = LHSSuperType->castAs<ObjCObjectType>();
7063 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007064
7065 // We didn't find anything by following the LHS to its root; now check
7066 // the RHS against the cached set of ancestors.
7067 while (true) {
7068 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7069 if (KnownLHS != LHSAncestors.end()) {
7070 LHS = KnownLHS->second;
7071
7072 // Get the type arguments.
7073 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7074 bool anyChanges = false;
7075 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7076 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007077 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7078 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007079 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007080 return QualType();
7081 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7082 // If only one has type arguments, the result will not have type
7083 // arguments.
7084 RHSTypeArgs = { };
7085 anyChanges = true;
7086 }
7087
7088 // Compute the intersection of protocols.
7089 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7090 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7091 Protocols);
7092 if (!Protocols.empty())
7093 anyChanges = true;
7094
7095 if (anyChanges) {
7096 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007097 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7098 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007099 return getObjCObjectPointerType(Result);
7100 }
7101
7102 return getObjCObjectPointerType(QualType(RHS, 0));
7103 }
7104
7105 // Find the superclass of the RHS.
7106 QualType RHSSuperType = RHS->getSuperClassType();
7107 if (RHSSuperType.isNull())
7108 break;
7109
7110 RHS = RHSSuperType->castAs<ObjCObjectType>();
7111 }
7112
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007113 return QualType();
7114}
7115
John McCall8b07ec22010-05-15 11:32:37 +00007116bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7117 const ObjCObjectType *RHS) {
7118 assert(LHS->getInterface() && "LHS is not an interface type");
7119 assert(RHS->getInterface() && "RHS is not an interface type");
7120
Chris Lattner49af6a42008-04-07 06:51:04 +00007121 // Verify that the base decls are compatible: the RHS must be a subclass of
7122 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007123 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7124 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7125 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007126 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007127
Douglas Gregore83b9562015-07-07 03:57:53 +00007128 // If the LHS has protocol qualifiers, determine whether all of them are
7129 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7130 // LHS).
7131 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007132 // OK if conversion of LHS to SuperClass results in narrowing of types
7133 // ; i.e., SuperClass may implement at least one of the protocols
7134 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7135 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7136 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7137 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7138 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7139 // qualifiers.
7140 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007141 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007142 // If there is no protocols associated with RHS, it is not a match.
7143 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007144 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007145
7146 for (const auto *LHSProto : LHS->quals()) {
7147 bool SuperImplementsProtocol = false;
7148 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7149 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7150 SuperImplementsProtocol = true;
7151 break;
7152 }
7153 if (!SuperImplementsProtocol)
7154 return false;
7155 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007156 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007157
7158 // If the LHS is specialized, we may need to check type arguments.
7159 if (LHS->isSpecialized()) {
7160 // Follow the superclass chain until we've matched the LHS class in the
7161 // hierarchy. This substitutes type arguments through.
7162 const ObjCObjectType *RHSSuper = RHS;
7163 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7164 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7165
7166 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007167 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007168 !sameObjCTypeArgs(*this, LHS->getInterface(),
7169 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007170 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007171 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007172 }
7173 }
7174
7175 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007176}
7177
Steve Naroffb7605152009-02-12 17:52:19 +00007178bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7179 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007180 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7181 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007182
Steve Naroff7cae42b2009-07-10 23:34:53 +00007183 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007184 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007185
7186 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7187 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007188}
7189
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007190bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7191 return canAssignObjCInterfaces(
7192 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7193 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7194}
7195
Mike Stump11289f42009-09-09 15:08:12 +00007196/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007197/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007198/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007199/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007200bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7201 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007202 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007203 return hasSameType(LHS, RHS);
7204
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007205 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007206}
7207
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007208bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007209 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007210}
7211
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007212bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7213 return !mergeTypes(LHS, RHS, true).isNull();
7214}
7215
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007216/// mergeTransparentUnionType - if T is a transparent union type and a member
7217/// of T is compatible with SubType, return the merged type, else return
7218/// QualType()
7219QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7220 bool OfBlockPointer,
7221 bool Unqualified) {
7222 if (const RecordType *UT = T->getAsUnionType()) {
7223 RecordDecl *UD = UT->getDecl();
7224 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007225 for (const auto *I : UD->fields()) {
7226 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007227 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7228 if (!MT.isNull())
7229 return MT;
7230 }
7231 }
7232 }
7233
7234 return QualType();
7235}
7236
Alp Toker9cacbab2014-01-20 20:26:09 +00007237/// mergeFunctionParameterTypes - merge two types which appear as function
7238/// parameter types
7239QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7240 bool OfBlockPointer,
7241 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007242 // GNU extension: two types are compatible if they appear as a function
7243 // argument, one of the types is a transparent union type and the other
7244 // type is compatible with a union member
7245 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7246 Unqualified);
7247 if (!lmerge.isNull())
7248 return lmerge;
7249
7250 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7251 Unqualified);
7252 if (!rmerge.isNull())
7253 return rmerge;
7254
7255 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7256}
7257
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007258QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007259 bool OfBlockPointer,
7260 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007261 const FunctionType *lbase = lhs->getAs<FunctionType>();
7262 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007263 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7264 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007265 bool allLTypes = true;
7266 bool allRTypes = true;
7267
7268 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007269 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007270 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007271 QualType RHS = rbase->getReturnType();
7272 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007273 bool UnqualifiedResult = Unqualified;
7274 if (!UnqualifiedResult)
7275 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007276 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007277 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007278 else
Alp Toker314cc812014-01-25 16:55:45 +00007279 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007280 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007281 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007282
7283 if (Unqualified)
7284 retType = retType.getUnqualifiedType();
7285
Alp Toker314cc812014-01-25 16:55:45 +00007286 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7287 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007288 if (Unqualified) {
7289 LRetType = LRetType.getUnqualifiedType();
7290 RRetType = RRetType.getUnqualifiedType();
7291 }
7292
7293 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007294 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007295 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007296 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007297
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007298 // FIXME: double check this
7299 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7300 // rbase->getRegParmAttr() != 0 &&
7301 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007302 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7303 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007304
Douglas Gregor8c940862010-01-18 17:14:39 +00007305 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007306 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007307 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007308
John McCall8c6b56f2010-12-15 01:06:38 +00007309 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007310 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7311 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007312 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7313 return QualType();
7314
John McCall31168b02011-06-15 23:02:42 +00007315 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7316 return QualType();
7317
John McCall8c6b56f2010-12-15 01:06:38 +00007318 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7319 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007320
Rafael Espindola8778c282012-11-29 16:09:03 +00007321 if (lbaseInfo.getNoReturn() != NoReturn)
7322 allLTypes = false;
7323 if (rbaseInfo.getNoReturn() != NoReturn)
7324 allRTypes = false;
7325
John McCall31168b02011-06-15 23:02:42 +00007326 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007327
Eli Friedman47f77112008-08-22 00:56:42 +00007328 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007329 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7330 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007331 // Compatible functions must have the same number of parameters
7332 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007333 return QualType();
7334
7335 // Variadic and non-variadic functions aren't compatible
7336 if (lproto->isVariadic() != rproto->isVariadic())
7337 return QualType();
7338
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007339 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7340 return QualType();
7341
Fariborz Jahanian97676972011-09-28 21:52:05 +00007342 if (LangOpts.ObjCAutoRefCount &&
7343 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7344 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007345
7346 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007347 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007348 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7349 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7350 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7351 QualType paramType = mergeFunctionParameterTypes(
7352 lParamType, rParamType, OfBlockPointer, Unqualified);
7353 if (paramType.isNull())
7354 return QualType();
7355
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007356 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007357 paramType = paramType.getUnqualifiedType();
7358
7359 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007360 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007361 lParamType = lParamType.getUnqualifiedType();
7362 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007363 }
Alp Toker601b22c2014-01-21 23:35:24 +00007364
7365 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007366 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007367 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007368 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007369 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007370
Eli Friedman47f77112008-08-22 00:56:42 +00007371 if (allLTypes) return lhs;
7372 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007373
7374 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7375 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007376 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007377 }
7378
7379 if (lproto) allRTypes = false;
7380 if (rproto) allLTypes = false;
7381
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007382 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007383 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007384 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007385 if (proto->isVariadic()) return QualType();
7386 // Check that the types are compatible with the types that
7387 // would result from default argument promotions (C99 6.7.5.3p15).
7388 // The only types actually affected are promotable integer
7389 // types and floats, which would be passed as a different
7390 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007391 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7392 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007393
Eli Friedman448ce402012-08-30 00:44:15 +00007394 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007395 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007396 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7397 paramTy = Enum->getDecl()->getIntegerType();
7398 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007399 return QualType();
7400 }
Alp Toker601b22c2014-01-21 23:35:24 +00007401
7402 if (paramTy->isPromotableIntegerType() ||
7403 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007404 return QualType();
7405 }
7406
7407 if (allLTypes) return lhs;
7408 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007409
7410 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7411 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007412 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007413 }
7414
7415 if (allLTypes) return lhs;
7416 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007417 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007418}
7419
John McCall433c2e62013-03-21 00:10:07 +00007420/// Given that we have an enum type and a non-enum type, try to merge them.
7421static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7422 QualType other, bool isBlockReturnType) {
7423 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7424 // a signed integer type, or an unsigned integer type.
7425 // Compatibility is based on the underlying type, not the promotion
7426 // type.
7427 QualType underlyingType = ET->getDecl()->getIntegerType();
7428 if (underlyingType.isNull()) return QualType();
7429 if (Context.hasSameType(underlyingType, other))
7430 return other;
7431
7432 // In block return types, we're more permissive and accept any
7433 // integral type of the same size.
7434 if (isBlockReturnType && other->isIntegerType() &&
7435 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7436 return other;
7437
7438 return QualType();
7439}
7440
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007441QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007442 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007443 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007444 // C++ [expr]: If an expression initially has the type "reference to T", the
7445 // type is adjusted to "T" prior to any further analysis, the expression
7446 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007447 // expression is an lvalue unless the reference is an rvalue reference and
7448 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007449 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7450 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007451
7452 if (Unqualified) {
7453 LHS = LHS.getUnqualifiedType();
7454 RHS = RHS.getUnqualifiedType();
7455 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007456
Eli Friedman47f77112008-08-22 00:56:42 +00007457 QualType LHSCan = getCanonicalType(LHS),
7458 RHSCan = getCanonicalType(RHS);
7459
7460 // If two types are identical, they are compatible.
7461 if (LHSCan == RHSCan)
7462 return LHS;
7463
John McCall8ccfcb52009-09-24 19:53:00 +00007464 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007465 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7466 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007467 if (LQuals != RQuals) {
7468 // If any of these qualifiers are different, we have a type
7469 // mismatch.
7470 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007471 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7472 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007473 return QualType();
7474
7475 // Exactly one GC qualifier difference is allowed: __strong is
7476 // okay if the other type has no GC qualifier but is an Objective
7477 // C object pointer (i.e. implicitly strong by default). We fix
7478 // this by pretending that the unqualified type was actually
7479 // qualified __strong.
7480 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7481 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7482 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7483
7484 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7485 return QualType();
7486
7487 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7488 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7489 }
7490 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7491 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7492 }
Eli Friedman47f77112008-08-22 00:56:42 +00007493 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007494 }
7495
7496 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007497
Eli Friedmandcca6332009-06-01 01:22:52 +00007498 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7499 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007500
Chris Lattnerfd652912008-01-14 05:45:46 +00007501 // We want to consider the two function types to be the same for these
7502 // comparisons, just force one to the other.
7503 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7504 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007505
7506 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007507 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7508 LHSClass = Type::ConstantArray;
7509 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7510 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007511
John McCall8b07ec22010-05-15 11:32:37 +00007512 // ObjCInterfaces are just specialized ObjCObjects.
7513 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7514 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7515
Nate Begemance4d7fc2008-04-18 23:10:10 +00007516 // Canonicalize ExtVector -> Vector.
7517 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7518 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007519
Chris Lattner95554662008-04-07 05:43:21 +00007520 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007521 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007522 // Note that we only have special rules for turning block enum
7523 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007524 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007525 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007526 }
John McCall9dd450b2009-09-21 23:43:11 +00007527 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007528 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007529 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007530 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007531 if (OfBlockPointer && !BlockReturnType) {
7532 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7533 return LHS;
7534 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7535 return RHS;
7536 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007537
Eli Friedman47f77112008-08-22 00:56:42 +00007538 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007539 }
Eli Friedman47f77112008-08-22 00:56:42 +00007540
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007541 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007542 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007543#define TYPE(Class, Base)
7544#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007545#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007546#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7547#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7548#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007549 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007550
Richard Smith27d807c2013-04-30 13:56:41 +00007551 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007552 case Type::LValueReference:
7553 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007554 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007555 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007556
John McCall8b07ec22010-05-15 11:32:37 +00007557 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007558 case Type::IncompleteArray:
7559 case Type::VariableArray:
7560 case Type::FunctionProto:
7561 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007562 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007563
Chris Lattnerfd652912008-01-14 05:45:46 +00007564 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007565 {
7566 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007567 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7568 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007569 if (Unqualified) {
7570 LHSPointee = LHSPointee.getUnqualifiedType();
7571 RHSPointee = RHSPointee.getUnqualifiedType();
7572 }
7573 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7574 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007575 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007576 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007577 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007578 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007579 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007580 return getPointerType(ResultType);
7581 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007582 case Type::BlockPointer:
7583 {
7584 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007585 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7586 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007587 if (Unqualified) {
7588 LHSPointee = LHSPointee.getUnqualifiedType();
7589 RHSPointee = RHSPointee.getUnqualifiedType();
7590 }
7591 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7592 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007593 if (ResultType.isNull()) return QualType();
7594 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7595 return LHS;
7596 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7597 return RHS;
7598 return getBlockPointerType(ResultType);
7599 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007600 case Type::Atomic:
7601 {
7602 // Merge two pointer types, while trying to preserve typedef info
7603 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7604 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7605 if (Unqualified) {
7606 LHSValue = LHSValue.getUnqualifiedType();
7607 RHSValue = RHSValue.getUnqualifiedType();
7608 }
7609 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7610 Unqualified);
7611 if (ResultType.isNull()) return QualType();
7612 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7613 return LHS;
7614 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7615 return RHS;
7616 return getAtomicType(ResultType);
7617 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007618 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007619 {
7620 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7621 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7622 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7623 return QualType();
7624
7625 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7626 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007627 if (Unqualified) {
7628 LHSElem = LHSElem.getUnqualifiedType();
7629 RHSElem = RHSElem.getUnqualifiedType();
7630 }
7631
7632 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007633 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007634 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7635 return LHS;
7636 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7637 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007638 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7639 ArrayType::ArraySizeModifier(), 0);
7640 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7641 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007642 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7643 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007644 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7645 return LHS;
7646 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7647 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007648 if (LVAT) {
7649 // FIXME: This isn't correct! But tricky to implement because
7650 // the array's size has to be the size of LHS, but the type
7651 // has to be different.
7652 return LHS;
7653 }
7654 if (RVAT) {
7655 // FIXME: This isn't correct! But tricky to implement because
7656 // the array's size has to be the size of RHS, but the type
7657 // has to be different.
7658 return RHS;
7659 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007660 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7661 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007662 return getIncompleteArrayType(ResultType,
7663 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007664 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007665 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007666 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007667 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007668 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007669 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007670 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007671 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007672 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007673 case Type::Complex:
7674 // Distinct complex types are incompatible.
7675 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007676 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007677 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007678 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7679 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007680 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007681 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007682 case Type::ObjCObject: {
7683 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007684 // FIXME: This should be type compatibility, e.g. whether
7685 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007686 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7687 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7688 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007689 return LHS;
7690
Eli Friedman47f77112008-08-22 00:56:42 +00007691 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007692 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007693 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007694 if (OfBlockPointer) {
7695 if (canAssignObjCInterfacesInBlockPointer(
7696 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007697 RHS->getAs<ObjCObjectPointerType>(),
7698 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007699 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007700 return QualType();
7701 }
John McCall9dd450b2009-09-21 23:43:11 +00007702 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7703 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007704 return LHS;
7705
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007706 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007707 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007708 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007709
David Blaikie8a40f702012-01-17 06:56:22 +00007710 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007711}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007712
Fariborz Jahanian97676972011-09-28 21:52:05 +00007713bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7714 const FunctionProtoType *FromFunctionType,
7715 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007716 if (FromFunctionType->hasAnyConsumedParams() !=
7717 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007718 return false;
7719 FunctionProtoType::ExtProtoInfo FromEPI =
7720 FromFunctionType->getExtProtoInfo();
7721 FunctionProtoType::ExtProtoInfo ToEPI =
7722 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007723 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007724 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7725 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007726 return false;
7727 }
7728 return true;
7729}
7730
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007731/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7732/// 'RHS' attributes and returns the merged version; including for function
7733/// return types.
7734QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7735 QualType LHSCan = getCanonicalType(LHS),
7736 RHSCan = getCanonicalType(RHS);
7737 // If two types are identical, they are compatible.
7738 if (LHSCan == RHSCan)
7739 return LHS;
7740 if (RHSCan->isFunctionType()) {
7741 if (!LHSCan->isFunctionType())
7742 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007743 QualType OldReturnType =
7744 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007745 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007746 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007747 QualType ResReturnType =
7748 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7749 if (ResReturnType.isNull())
7750 return QualType();
7751 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7752 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7753 // In either case, use OldReturnType to build the new function type.
7754 const FunctionType *F = LHS->getAs<FunctionType>();
7755 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007756 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7757 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007758 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007759 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007760 return ResultType;
7761 }
7762 }
7763 return QualType();
7764 }
7765
7766 // If the qualifiers are different, the types can still be merged.
7767 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7768 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7769 if (LQuals != RQuals) {
7770 // If any of these qualifiers are different, we have a type mismatch.
7771 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7772 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7773 return QualType();
7774
7775 // Exactly one GC qualifier difference is allowed: __strong is
7776 // okay if the other type has no GC qualifier but is an Objective
7777 // C object pointer (i.e. implicitly strong by default). We fix
7778 // this by pretending that the unqualified type was actually
7779 // qualified __strong.
7780 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7781 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7782 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7783
7784 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7785 return QualType();
7786
7787 if (GC_L == Qualifiers::Strong)
7788 return LHS;
7789 if (GC_R == Qualifiers::Strong)
7790 return RHS;
7791 return QualType();
7792 }
7793
7794 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7795 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7796 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7797 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7798 if (ResQT == LHSBaseQT)
7799 return LHS;
7800 if (ResQT == RHSBaseQT)
7801 return RHS;
7802 }
7803 return QualType();
7804}
7805
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007806//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007807// Integer Predicates
7808//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007809
Jay Foad39c79802011-01-12 09:06:06 +00007810unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007811 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007812 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007813 if (T->isBooleanType())
7814 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007815 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007816 return (unsigned)getTypeSize(T);
7817}
7818
Abramo Bagnara13640492012-09-09 10:21:24 +00007819QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007820 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007821
7822 // Turn <4 x signed int> -> <4 x unsigned int>
7823 if (const VectorType *VTy = T->getAs<VectorType>())
7824 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007825 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007826
7827 // For enums, we return the unsigned version of the base type.
7828 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007829 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007830
7831 const BuiltinType *BTy = T->getAs<BuiltinType>();
7832 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007833 switch (BTy->getKind()) {
7834 case BuiltinType::Char_S:
7835 case BuiltinType::SChar:
7836 return UnsignedCharTy;
7837 case BuiltinType::Short:
7838 return UnsignedShortTy;
7839 case BuiltinType::Int:
7840 return UnsignedIntTy;
7841 case BuiltinType::Long:
7842 return UnsignedLongTy;
7843 case BuiltinType::LongLong:
7844 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007845 case BuiltinType::Int128:
7846 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007847 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007848 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007849 }
7850}
7851
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007852ASTMutationListener::~ASTMutationListener() { }
7853
Richard Smith1fa5d642013-05-11 05:45:24 +00007854void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7855 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007856
7857//===----------------------------------------------------------------------===//
7858// Builtin Type Computation
7859//===----------------------------------------------------------------------===//
7860
7861/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007862/// pointer over the consumed characters. This returns the resultant type. If
7863/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7864/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7865/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007866///
7867/// RequiresICE is filled in on return to indicate whether the value is required
7868/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007869static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007870 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007871 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007872 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007873 // Modifiers.
7874 int HowLong = 0;
7875 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007876 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007877
Chris Lattnerdc226c22010-10-01 22:42:38 +00007878 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007879 bool Done = false;
7880 while (!Done) {
7881 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007882 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007883 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007884 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007885 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007886 case 'S':
7887 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7888 assert(!Signed && "Can't use 'S' modifier multiple times!");
7889 Signed = true;
7890 break;
7891 case 'U':
7892 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007893 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007894 Unsigned = true;
7895 break;
7896 case 'L':
7897 assert(HowLong <= 2 && "Can't have LLLL modifier");
7898 ++HowLong;
7899 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007900 case 'W':
7901 // This modifier represents int64 type.
7902 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7903 switch (Context.getTargetInfo().getInt64Type()) {
7904 default:
7905 llvm_unreachable("Unexpected integer type");
7906 case TargetInfo::SignedLong:
7907 HowLong = 1;
7908 break;
7909 case TargetInfo::SignedLongLong:
7910 HowLong = 2;
7911 break;
7912 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007913 }
7914 }
7915
7916 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007917
Chris Lattnerecd79c62009-06-14 00:45:47 +00007918 // Read the base type.
7919 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007920 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007921 case 'v':
7922 assert(HowLong == 0 && !Signed && !Unsigned &&
7923 "Bad modifiers used with 'v'!");
7924 Type = Context.VoidTy;
7925 break;
Jack Carter24bef982013-08-15 15:16:57 +00007926 case 'h':
7927 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007928 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007929 Type = Context.HalfTy;
7930 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007931 case 'f':
7932 assert(HowLong == 0 && !Signed && !Unsigned &&
7933 "Bad modifiers used with 'f'!");
7934 Type = Context.FloatTy;
7935 break;
7936 case 'd':
7937 assert(HowLong < 2 && !Signed && !Unsigned &&
7938 "Bad modifiers used with 'd'!");
7939 if (HowLong)
7940 Type = Context.LongDoubleTy;
7941 else
7942 Type = Context.DoubleTy;
7943 break;
7944 case 's':
7945 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7946 if (Unsigned)
7947 Type = Context.UnsignedShortTy;
7948 else
7949 Type = Context.ShortTy;
7950 break;
7951 case 'i':
7952 if (HowLong == 3)
7953 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7954 else if (HowLong == 2)
7955 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7956 else if (HowLong == 1)
7957 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7958 else
7959 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7960 break;
7961 case 'c':
7962 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7963 if (Signed)
7964 Type = Context.SignedCharTy;
7965 else if (Unsigned)
7966 Type = Context.UnsignedCharTy;
7967 else
7968 Type = Context.CharTy;
7969 break;
7970 case 'b': // boolean
7971 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7972 Type = Context.BoolTy;
7973 break;
7974 case 'z': // size_t.
7975 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7976 Type = Context.getSizeType();
7977 break;
7978 case 'F':
7979 Type = Context.getCFConstantStringType();
7980 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007981 case 'G':
7982 Type = Context.getObjCIdType();
7983 break;
7984 case 'H':
7985 Type = Context.getObjCSelType();
7986 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007987 case 'M':
7988 Type = Context.getObjCSuperType();
7989 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007990 case 'a':
7991 Type = Context.getBuiltinVaListType();
7992 assert(!Type.isNull() && "builtin va list type not initialized!");
7993 break;
7994 case 'A':
7995 // This is a "reference" to a va_list; however, what exactly
7996 // this means depends on how va_list is defined. There are two
7997 // different kinds of va_list: ones passed by value, and ones
7998 // passed by reference. An example of a by-value va_list is
7999 // x86, where va_list is a char*. An example of by-ref va_list
8000 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8001 // we want this argument to be a char*&; for x86-64, we want
8002 // it to be a __va_list_tag*.
8003 Type = Context.getBuiltinVaListType();
8004 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008005 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008006 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008007 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008008 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008009 break;
8010 case 'V': {
8011 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008012 unsigned NumElements = strtoul(Str, &End, 10);
8013 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008014 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008015
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008016 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8017 RequiresICE, false);
8018 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008019
8020 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008021 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008022 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008023 break;
8024 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008025 case 'E': {
8026 char *End;
8027
8028 unsigned NumElements = strtoul(Str, &End, 10);
8029 assert(End != Str && "Missing vector size");
8030
8031 Str = End;
8032
8033 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8034 false);
8035 Type = Context.getExtVectorType(ElementType, NumElements);
8036 break;
8037 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008038 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008039 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8040 false);
8041 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008042 Type = Context.getComplexType(ElementType);
8043 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008044 }
8045 case 'Y' : {
8046 Type = Context.getPointerDiffType();
8047 break;
8048 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008049 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008050 Type = Context.getFILEType();
8051 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008052 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008053 return QualType();
8054 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008055 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008056 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008057 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008058 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008059 else
8060 Type = Context.getjmp_bufType();
8061
Mike Stump2adb4da2009-07-28 23:47:15 +00008062 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008063 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008064 return QualType();
8065 }
8066 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008067 case 'K':
8068 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8069 Type = Context.getucontext_tType();
8070
8071 if (Type.isNull()) {
8072 Error = ASTContext::GE_Missing_ucontext;
8073 return QualType();
8074 }
8075 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008076 case 'p':
8077 Type = Context.getProcessIDType();
8078 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008079 }
Mike Stump11289f42009-09-09 15:08:12 +00008080
Chris Lattnerdc226c22010-10-01 22:42:38 +00008081 // If there are modifiers and if we're allowed to parse them, go for it.
8082 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008083 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008084 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008085 default: Done = true; --Str; break;
8086 case '*':
8087 case '&': {
8088 // Both pointers and references can have their pointee types
8089 // qualified with an address space.
8090 char *End;
8091 unsigned AddrSpace = strtoul(Str, &End, 10);
8092 if (End != Str && AddrSpace != 0) {
8093 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8094 Str = End;
8095 }
8096 if (c == '*')
8097 Type = Context.getPointerType(Type);
8098 else
8099 Type = Context.getLValueReferenceType(Type);
8100 break;
8101 }
8102 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8103 case 'C':
8104 Type = Type.withConst();
8105 break;
8106 case 'D':
8107 Type = Context.getVolatileType(Type);
8108 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008109 case 'R':
8110 Type = Type.withRestrict();
8111 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008112 }
8113 }
Chris Lattner84733392010-10-01 07:13:18 +00008114
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008115 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008116 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008117
Chris Lattnerecd79c62009-06-14 00:45:47 +00008118 return Type;
8119}
8120
8121/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008122QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008123 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008124 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008125 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008126
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008127 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008128
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008129 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008130 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008131 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8132 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008133 if (Error != GE_None)
8134 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008135
8136 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8137
Chris Lattnerecd79c62009-06-14 00:45:47 +00008138 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008139 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008140 if (Error != GE_None)
8141 return QualType();
8142
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008143 // If this argument is required to be an IntegerConstantExpression and the
8144 // caller cares, fill in the bitmask we return.
8145 if (RequiresICE && IntegerConstantArgs)
8146 *IntegerConstantArgs |= 1 << ArgTypes.size();
8147
Chris Lattnerecd79c62009-06-14 00:45:47 +00008148 // Do array -> pointer decay. The builtin should use the decayed type.
8149 if (Ty->isArrayType())
8150 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008151
Chris Lattnerecd79c62009-06-14 00:45:47 +00008152 ArgTypes.push_back(Ty);
8153 }
8154
David Majnemerba3e5ec2015-03-13 18:26:17 +00008155 if (Id == Builtin::BI__GetExceptionInfo)
8156 return QualType();
8157
Chris Lattnerecd79c62009-06-14 00:45:47 +00008158 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8159 "'.' should only occur at end of builtin type list!");
8160
Reid Kleckner78af0702013-08-27 23:08:25 +00008161 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008162 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8163
8164 bool Variadic = (TypeStr[0] == '.');
8165
8166 // We really shouldn't be making a no-proto type here, especially in C++.
8167 if (ArgTypes.empty() && Variadic)
8168 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008169
John McCalldb40c7f2010-12-14 08:05:40 +00008170 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008171 EPI.ExtInfo = EI;
8172 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008173
Jordan Rose5c382722013-03-08 21:51:21 +00008174 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008175}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008176
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008177static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8178 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008179 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008180 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008181
Rafael Espindola3ae00052013-05-13 00:12:11 +00008182 GVALinkage External = GVA_StrongExternal;
8183 switch (FD->getTemplateSpecializationKind()) {
8184 case TSK_Undeclared:
8185 case TSK_ExplicitSpecialization:
8186 External = GVA_StrongExternal;
8187 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008188
Rafael Espindola3ae00052013-05-13 00:12:11 +00008189 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008190 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008191
David Majnemerc3d07332014-05-15 06:25:57 +00008192 // C++11 [temp.explicit]p10:
8193 // [ Note: The intent is that an inline function that is the subject of
8194 // an explicit instantiation declaration will still be implicitly
8195 // instantiated when used so that the body can be considered for
8196 // inlining, but that no out-of-line copy of the inline function would be
8197 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008198 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008199 return GVA_AvailableExternally;
8200
Rafael Espindola3ae00052013-05-13 00:12:11 +00008201 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008202 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008203 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008204 }
8205
8206 if (!FD->isInlined())
8207 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008208
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008209 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8210 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008211 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008212 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8213
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008214 // GNU or C99 inline semantics. Determine whether this symbol should be
8215 // externally visible.
8216 if (FD->isInlineDefinitionExternallyVisible())
8217 return External;
8218
8219 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008220 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008221 }
8222
David Majnemer54e3ba52014-04-02 23:17:29 +00008223 // Functions specified with extern and inline in -fms-compatibility mode
8224 // forcibly get emitted. While the body of the function cannot be later
8225 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008226 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008227 return GVA_StrongODR;
8228
David Majnemer27d69db2014-04-28 22:17:59 +00008229 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008230}
8231
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008232static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
8233 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8234 // dllexport/dllimport on inline functions.
8235 if (D->hasAttr<DLLImportAttr>()) {
8236 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8237 return GVA_AvailableExternally;
8238 } else if (D->hasAttr<DLLExportAttr>()) {
8239 if (L == GVA_DiscardableODR)
8240 return GVA_StrongODR;
8241 }
8242 return L;
8243}
8244
8245GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8246 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
8247 FD);
8248}
8249
8250static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8251 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008252 if (!VD->isExternallyVisible())
8253 return GVA_Internal;
8254
David Majnemer27d69db2014-04-28 22:17:59 +00008255 if (VD->isStaticLocal()) {
8256 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8257 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8258 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8259 LexicalContext = LexicalContext->getLexicalParent();
8260
Richard Smith9e2341d2015-03-23 03:25:59 +00008261 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008262 // enclosing function.
8263 if (LexicalContext)
8264 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008265 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008266
8267 // GVA_StrongODR function linkage is stronger than what we need,
8268 // downgrade to GVA_DiscardableODR.
8269 // This allows us to discard the variable if we never end up needing it.
8270 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8271 : StaticLocalLinkage;
8272 }
8273
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008274 // MSVC treats in-class initialized static data members as definitions.
8275 // By giving them non-strong linkage, out-of-line definitions won't
8276 // cause link errors.
8277 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8278 return GVA_DiscardableODR;
8279
Richard Smith8809a0c2013-09-27 20:14:12 +00008280 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008281 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008282 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008283
David Majnemer6d1780c2015-07-17 23:36:49 +00008284 case TSK_ExplicitSpecialization:
8285 return Context.getLangOpts().MSVCCompat && VD->isStaticDataMember()
8286 ? GVA_StrongODR
8287 : GVA_StrongExternal;
8288
Rafael Espindola3ae00052013-05-13 00:12:11 +00008289 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008290 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008291
David Majnemer27d69db2014-04-28 22:17:59 +00008292 case TSK_ExplicitInstantiationDeclaration:
8293 return GVA_AvailableExternally;
8294
Rafael Espindola3ae00052013-05-13 00:12:11 +00008295 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008296 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008297 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008298
8299 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008300}
8301
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008302GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8303 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8304 VD);
8305}
8306
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008307bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008308 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8309 if (!VD->isFileVarDecl())
8310 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008311 // Global named register variables (GNU extension) are never emitted.
8312 if (VD->getStorageClass() == SC_Register)
8313 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008314 if (VD->getDescribedVarTemplate() ||
8315 isa<VarTemplatePartialSpecializationDecl>(VD))
8316 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008317 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8318 // We never need to emit an uninstantiated function template.
8319 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8320 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008321 } else if (isa<OMPThreadPrivateDecl>(D))
8322 return true;
8323 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008324 return false;
8325
8326 // If this is a member of a class template, we do not need to emit it.
8327 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008328 return false;
8329
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008330 // Weak references don't produce any output by themselves.
8331 if (D->hasAttr<WeakRefAttr>())
8332 return false;
8333
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008334 // Aliases and used decls are required.
8335 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8336 return true;
8337
8338 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8339 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008340 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008341 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008342
8343 // Constructors and destructors are required.
8344 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8345 return true;
8346
John McCall6bd2a892013-01-25 22:31:03 +00008347 // The key function for a class is required. This rule only comes
8348 // into play when inline functions can be key functions, though.
8349 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8350 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8351 const CXXRecordDecl *RD = MD->getParent();
8352 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8353 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8354 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8355 return true;
8356 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008357 }
8358 }
8359
8360 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8361
8362 // static, static inline, always_inline, and extern inline functions can
8363 // always be deferred. Normal inline functions can be deferred in C99/C++.
8364 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008365 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8366 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008367 return false;
8368 return true;
8369 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008370
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008371 const VarDecl *VD = cast<VarDecl>(D);
8372 assert(VD->isFileVarDecl() && "Expected file scoped var");
8373
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008374 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8375 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008376 return false;
8377
Richard Smitha0e5e542012-11-12 21:38:00 +00008378 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008379 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008380 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8381 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008382 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008383
Richard Smitha0e5e542012-11-12 21:38:00 +00008384 // Variables that have destruction with side-effects are required.
8385 if (VD->getType().isDestructedType())
8386 return true;
8387
8388 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008389 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8390 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008391 return true;
8392
8393 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008394}
Charles Davis53c59df2010-08-16 03:33:14 +00008395
Reid Kleckner78af0702013-08-27 23:08:25 +00008396CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8397 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008398 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008399 if (IsCXXMethod)
8400 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008401
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008402 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8403
8404 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008405}
8406
Jay Foad39c79802011-01-12 09:06:06 +00008407bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008408 // Pass through to the C++ ABI object
8409 return ABI->isNearlyEmpty(RD);
8410}
8411
Reid Kleckner96f8f932014-02-05 17:27:08 +00008412VTableContextBase *ASTContext::getVTableContext() {
8413 if (!VTContext.get()) {
8414 if (Target->getCXXABI().isMicrosoft())
8415 VTContext.reset(new MicrosoftVTableContext(*this));
8416 else
8417 VTContext.reset(new ItaniumVTableContext(*this));
8418 }
8419 return VTContext.get();
8420}
8421
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008422MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008423 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008424 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008425 case TargetCXXABI::GenericItanium:
8426 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008427 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008428 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008429 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008430 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008431 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008432 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008433 }
David Blaikie83d382b2011-09-23 05:06:16 +00008434 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008435}
8436
Charles Davis53c59df2010-08-16 03:33:14 +00008437CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008438
8439size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008440 return ASTRecordLayouts.getMemorySize() +
8441 llvm::capacity_in_bytes(ObjCLayouts) +
8442 llvm::capacity_in_bytes(KeyFunctions) +
8443 llvm::capacity_in_bytes(ObjCImpls) +
8444 llvm::capacity_in_bytes(BlockVarCopyInits) +
8445 llvm::capacity_in_bytes(DeclAttrs) +
8446 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8447 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8448 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8449 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8450 llvm::capacity_in_bytes(OverriddenMethods) +
8451 llvm::capacity_in_bytes(Types) +
8452 llvm::capacity_in_bytes(VariableArrayTypes) +
8453 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008454}
Ted Kremenek540017e2011-10-06 05:00:56 +00008455
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008456/// getIntTypeForBitwidth -
8457/// sets integer QualTy according to specified details:
8458/// bitwidth, signed/unsigned.
8459/// Returns empty type if there is no appropriate target types.
8460QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8461 unsigned Signed) const {
8462 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8463 CanQualType QualTy = getFromTargetType(Ty);
8464 if (!QualTy && DestWidth == 128)
8465 return Signed ? Int128Ty : UnsignedInt128Ty;
8466 return QualTy;
8467}
8468
8469/// getRealTypeForBitwidth -
8470/// sets floating point QualTy according to specified bitwidth.
8471/// Returns empty type if there is no appropriate target types.
8472QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8473 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8474 switch (Ty) {
8475 case TargetInfo::Float:
8476 return FloatTy;
8477 case TargetInfo::Double:
8478 return DoubleTy;
8479 case TargetInfo::LongDouble:
8480 return LongDoubleTy;
8481 case TargetInfo::NoFloat:
8482 return QualType();
8483 }
8484
8485 llvm_unreachable("Unhandled TargetInfo::RealType value");
8486}
8487
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008488void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8489 if (Number > 1)
8490 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008491}
8492
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008493unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8494 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8495 MangleNumbers.find(ND);
8496 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008497}
8498
David Majnemer2206bf52014-03-05 08:57:59 +00008499void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8500 if (Number > 1)
8501 StaticLocalNumbers[VD] = Number;
8502}
8503
8504unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8505 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8506 StaticLocalNumbers.find(VD);
8507 return I != StaticLocalNumbers.end() ? I->second : 1;
8508}
8509
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008510MangleNumberingContext &
8511ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008512 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8513 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8514 if (!MCtx)
8515 MCtx = createMangleNumberingContext();
8516 return *MCtx;
8517}
8518
8519MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8520 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008521}
8522
David Majnemere7a818f2015-03-06 18:53:55 +00008523const CXXConstructorDecl *
8524ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8525 return ABI->getCopyConstructorForExceptionObject(
8526 cast<CXXRecordDecl>(RD->getFirstDecl()));
8527}
8528
8529void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8530 CXXConstructorDecl *CD) {
8531 return ABI->addCopyConstructorForExceptionObject(
8532 cast<CXXRecordDecl>(RD->getFirstDecl()),
8533 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8534}
8535
David Majnemerdfa6d202015-03-11 18:36:39 +00008536void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8537 unsigned ParmIdx, Expr *DAE) {
8538 ABI->addDefaultArgExprForConstructor(
8539 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8540}
8541
8542Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8543 unsigned ParmIdx) {
8544 return ABI->getDefaultArgExprForConstructor(
8545 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8546}
8547
Ted Kremenek540017e2011-10-06 05:00:56 +00008548void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8549 ParamIndices[D] = index;
8550}
8551
8552unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8553 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8554 assert(I != ParamIndices.end() &&
8555 "ParmIndices lacks entry set by ParmVarDecl");
8556 return I->second;
8557}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008558
Richard Smithe6c01442013-06-05 00:46:14 +00008559APValue *
8560ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8561 bool MayCreate) {
8562 assert(E && E->getStorageDuration() == SD_Static &&
8563 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008564 if (MayCreate) {
8565 APValue *&MTVI = MaterializedTemporaryValues[E];
8566 if (!MTVI)
8567 MTVI = new (*this) APValue;
8568 return MTVI;
8569 }
Richard Smithe6c01442013-06-05 00:46:14 +00008570
David Majnemer2dcef9e2015-08-13 23:50:15 +00008571 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008572}
8573
Fariborz Jahanian615de762013-05-28 17:37:39 +00008574bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8575 const llvm::Triple &T = getTargetInfo().getTriple();
8576 if (!T.isOSDarwin())
8577 return false;
8578
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008579 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8580 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8581 return false;
8582
Fariborz Jahanian615de762013-05-28 17:37:39 +00008583 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8584 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8585 uint64_t Size = sizeChars.getQuantity();
8586 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8587 unsigned Align = alignChars.getQuantity();
8588 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8589 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8590}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008591
8592namespace {
8593
8594 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8595 /// parents as defined by the \c RecursiveASTVisitor.
8596 ///
8597 /// Note that the relationship described here is purely in terms of AST
8598 /// traversal - there are other relationships (for example declaration context)
8599 /// in the AST that are better modeled by special matchers.
8600 ///
8601 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8602 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8603
8604 public:
8605 /// \brief Builds and returns the translation unit's parent map.
8606 ///
8607 /// The caller takes ownership of the returned \c ParentMap.
8608 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8609 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8610 Visitor.TraverseDecl(&TU);
8611 return Visitor.Parents;
8612 }
8613
8614 private:
8615 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8616
8617 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8618 }
8619
8620 bool shouldVisitTemplateInstantiations() const {
8621 return true;
8622 }
8623 bool shouldVisitImplicitCode() const {
8624 return true;
8625 }
8626 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8627 // are not triggered during data recursion.
8628 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8629 return false;
8630 }
8631
8632 template <typename T>
8633 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008634 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008635 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008636 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008637 // FIXME: Currently we add the same parent multiple times, but only
8638 // when no memoization data is available for the type.
8639 // For example when we visit all subexpressions of template
8640 // instantiations; this is suboptimal, but benign: the only way to
8641 // visit those is with hasAncestor / hasParent, and those do not create
8642 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008643 // The plan is to enable DynTypedNode to be storable in a map or hash
8644 // map. The main problem there is to implement hash functions /
8645 // comparison operators for all types that DynTypedNode supports that
8646 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008647 auto &NodeOrVector = (*Parents)[Node];
8648 if (NodeOrVector.isNull()) {
8649 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008650 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008651 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8652 auto *Node =
8653 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8654 auto *Vector = new ASTContext::ParentVector(1, *Node);
8655 NodeOrVector = Vector;
8656 delete Node;
8657 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008658 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008659
8660 auto *Vector =
8661 NodeOrVector.template get<ASTContext::ParentVector *>();
8662 // Skip duplicates for types that have memoization data.
8663 // We must check that the type has memoization data before calling
8664 // std::find() because DynTypedNode::operator== can't compare all
8665 // types.
8666 bool Found = ParentStack.back().getMemoizationData() &&
8667 std::find(Vector->begin(), Vector->end(),
8668 ParentStack.back()) != Vector->end();
8669 if (!Found)
8670 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008671 }
8672 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008673 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8674 bool Result = (this ->* traverse) (Node);
8675 ParentStack.pop_back();
8676 return Result;
8677 }
8678
8679 bool TraverseDecl(Decl *DeclNode) {
8680 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8681 }
8682
8683 bool TraverseStmt(Stmt *StmtNode) {
8684 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8685 }
8686
8687 ASTContext::ParentMap *Parents;
8688 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8689
8690 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8691 };
8692
8693} // end namespace
8694
Benjamin Kramer07935292014-10-04 17:01:26 +00008695ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008696ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8697 assert(Node.getMemoizationData() &&
8698 "Invariant broken: only nodes that support memoization may be "
8699 "used in the parent map.");
8700 if (!AllParents) {
8701 // We always need to run over the whole translation unit, as
8702 // hasAncestor can escape any subtree.
8703 AllParents.reset(
8704 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8705 }
8706 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8707 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008708 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008709 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008710 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8711 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008712 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008713 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008714}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008715
8716bool
8717ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8718 const ObjCMethodDecl *MethodImpl) {
8719 // No point trying to match an unavailable/deprecated mothod.
8720 if (MethodDecl->hasAttr<UnavailableAttr>()
8721 || MethodDecl->hasAttr<DeprecatedAttr>())
8722 return false;
8723 if (MethodDecl->getObjCDeclQualifier() !=
8724 MethodImpl->getObjCDeclQualifier())
8725 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008726 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008727 return false;
8728
8729 if (MethodDecl->param_size() != MethodImpl->param_size())
8730 return false;
8731
8732 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8733 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8734 EF = MethodDecl->param_end();
8735 IM != EM && IF != EF; ++IM, ++IF) {
8736 const ParmVarDecl *DeclVar = (*IF);
8737 const ParmVarDecl *ImplVar = (*IM);
8738 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8739 return false;
8740 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8741 return false;
8742 }
8743 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8744
8745}
Richard Smith053f6c62014-05-16 23:01:30 +00008746
8747// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8748// doesn't include ASTContext.h
8749template
8750clang::LazyGenerationalUpdatePtr<
8751 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8752clang::LazyGenerationalUpdatePtr<
8753 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8754 const clang::ASTContext &Ctx, Decl *Value);