blob: b344b0687f2a250195ff823b087dc2735115c86e [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}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
635 ExpandedTypes.data(),
636 ExpandedTypes.size(),
637 ExpandedTInfos.data());
638 } else {
639 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000640 SourceLocation(),
641 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000642 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000643 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000644 T,
645 NTTP->isParameterPack(),
646 TInfo);
647 }
648 CanonParams.push_back(Param);
649
650 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
652 cast<TemplateTemplateParmDecl>(*P)));
653 }
654
655 TemplateTemplateParmDecl *CanonTTP
656 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
657 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000658 TTP->getPosition(),
659 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000660 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000661 TemplateParameterList::Create(*this, SourceLocation(),
662 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000663 CanonParams,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 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:
Tim Northover756447a2015-10-30 16:30:36 +0000684 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000686 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000687 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000688 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000689 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000690 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000691 return CreateMicrosoftCXXABI(*this);
692 }
David Blaikie8a40f702012-01-17 06:56:22 +0000693 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000694}
695
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000697 const LangOptions &LOpts) {
698 if (LOpts.FakeAddressSpaceMap) {
699 // The fake address space map must have a distinct entry for each
700 // language-specific address space.
701 static const unsigned FakeAddrSpaceMap[] = {
702 1, // opencl_global
703 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000704 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000705 4, // opencl_generic
706 5, // cuda_device
707 6, // cuda_constant
708 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 }
714}
715
David Tweed31d09b02013-09-13 12:04:22 +0000716static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
717 const LangOptions &LangOpts) {
718 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000719 case LangOptions::ASMM_Target:
720 return TI.useAddressSpaceMapMangling();
721 case LangOptions::ASMM_On:
722 return true;
723 case LangOptions::ASMM_Off:
724 return false;
725 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000726 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000727}
728
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000729ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000730 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000731 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000732 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
733 DependentTemplateSpecializationTypes(this_()),
734 SubstTemplateTemplateParmPacks(this_()),
735 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
736 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000737 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
738 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
739 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000740 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
741 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
742 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
743 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000744 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000745 MakeIntegerSeqDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000746 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000747 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
748 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
749 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
750 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000752 TUDecl = TranslationUnitDecl::Create(*this);
753}
754
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000755ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000756 ReleaseParentMapEntries();
757
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000758 // Release the DenseMaps associated with DeclContext objects.
759 // FIXME: Is this the ideal solution?
760 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000761
Manuel Klimeka7328992013-06-03 13:51:33 +0000762 // Call all of the deallocation functions on all of their targets.
763 for (DeallocationMap::const_iterator I = Deallocations.begin(),
764 E = Deallocations.end(); I != E; ++I)
765 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
766 (I->first)((I->second)[J]);
767
Ted Kremenek076baeb2010-06-08 23:00:58 +0000768 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000769 // because they can contain DenseMaps.
770 for (llvm::DenseMap<const ObjCContainerDecl*,
771 const ASTRecordLayout*>::iterator
772 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
773 // Increment in loop to prevent using deallocated memory.
774 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
775 R->Destroy(*this);
776
Ted Kremenek076baeb2010-06-08 23:00:58 +0000777 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
778 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
779 // Increment in loop to prevent using deallocated memory.
780 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
781 R->Destroy(*this);
782 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000783
784 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
785 AEnd = DeclAttrs.end();
786 A != AEnd; ++A)
787 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000788
David Majnemere694f3e2015-08-14 14:43:50 +0000789 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
790 MaterializedTemporaryValues)
791 MTVPair.second->~APValue();
792
Reid Kleckner588c9372014-02-19 23:44:52 +0000793 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000794}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000795
Manuel Klimek95403e62014-05-21 13:28:59 +0000796void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000797 if (!PointerParents) return;
798 for (const auto &Entry : *PointerParents) {
799 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
800 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
801 } else if (Entry.second.is<ParentVector *>()) {
802 delete Entry.second.get<ParentVector *>();
803 }
804 }
805 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000806 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
807 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000808 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000809 delete Entry.second.get<ParentVector *>();
810 }
811 }
812}
813
Douglas Gregor1a809332010-05-23 18:26:36 +0000814void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000815 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000816}
817
Mike Stump11289f42009-09-09 15:08:12 +0000818void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000819ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
820 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000821}
822
Chris Lattner4eb445d2007-01-26 01:27:23 +0000823void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000824 llvm::errs() << "\n*** AST Context Stats:\n";
825 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000826
Douglas Gregora30d0462009-05-26 14:40:08 +0000827 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000828#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000829#define ABSTRACT_TYPE(Name, Parent)
830#include "clang/AST/TypeNodes.def"
831 0 // Extra
832 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000833
Chris Lattner4eb445d2007-01-26 01:27:23 +0000834 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
835 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000836 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000837 }
838
Douglas Gregora30d0462009-05-26 14:40:08 +0000839 unsigned Idx = 0;
840 unsigned TotalBytes = 0;
841#define TYPE(Name, Parent) \
842 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000843 llvm::errs() << " " << counts[Idx] << " " << #Name \
844 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000845 TotalBytes += counts[Idx] * sizeof(Name##Type); \
846 ++Idx;
847#define ABSTRACT_TYPE(Name, Parent)
848#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000849
Chandler Carruth3c147a72011-07-04 05:32:14 +0000850 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
851
Douglas Gregor7454c562010-07-02 20:37:36 +0000852 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
854 << NumImplicitDefaultConstructors
855 << " implicit default constructors created\n";
856 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
857 << NumImplicitCopyConstructors
858 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
861 << NumImplicitMoveConstructors
862 << " implicit move constructors created\n";
863 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
864 << NumImplicitCopyAssignmentOperators
865 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000866 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
868 << NumImplicitMoveAssignmentOperators
869 << " implicit move assignment operators created\n";
870 llvm::errs() << NumImplicitDestructorsDeclared << "/"
871 << NumImplicitDestructors
872 << " implicit destructors created\n";
873
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000874 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000875 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000876 ExternalSource->PrintStats();
877 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000878
Douglas Gregor5b11d492010-07-25 17:53:33 +0000879 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000880}
881
Richard Smith42413142015-05-15 20:05:43 +0000882void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
883 bool NotifyListeners) {
884 if (NotifyListeners)
885 if (auto *Listener = getASTMutationListener())
886 Listener->RedefinedHiddenDefinition(ND, M);
887
888 if (getLangOpts().ModulesLocalVisibility)
889 MergedDefModules[ND].push_back(M);
890 else
891 ND->setHidden(false);
892}
893
894void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
895 auto It = MergedDefModules.find(ND);
896 if (It == MergedDefModules.end())
897 return;
898
899 auto &Merged = It->second;
900 llvm::DenseSet<Module*> Found;
901 for (Module *&M : Merged)
902 if (!Found.insert(M).second)
903 M = nullptr;
904 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
905}
906
Richard Smithf19e1272015-03-07 00:04:49 +0000907ExternCContextDecl *ASTContext::getExternCContextDecl() const {
908 if (!ExternCContext)
909 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
910
911 return ExternCContext;
912}
913
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000914BuiltinTemplateDecl *
915ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
916 const IdentifierInfo *II) const {
917 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
918 BuiltinTemplate->setImplicit();
919 TUDecl->addDecl(BuiltinTemplate);
920
921 return BuiltinTemplate;
922}
923
924BuiltinTemplateDecl *
925ASTContext::getMakeIntegerSeqDecl() const {
926 if (!MakeIntegerSeqDecl)
927 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
928 getMakeIntegerSeqName());
929 return MakeIntegerSeqDecl;
930}
931
Alp Toker2dea15b2013-12-17 01:22:38 +0000932RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
933 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 SourceLocation Loc;
935 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000936 if (getLangOpts().CPlusPlus)
937 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
938 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000939 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000940 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
941 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000942 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000943 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
944 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000945 return NewDecl;
946}
947
948TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
949 StringRef Name) const {
950 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
951 TypedefDecl *NewDecl = TypedefDecl::Create(
952 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
953 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
954 NewDecl->setImplicit();
955 return NewDecl;
956}
957
Douglas Gregor801c99d2011-08-12 06:49:56 +0000958TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000959 if (!Int128Decl)
960 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000961 return Int128Decl;
962}
963
964TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000965 if (!UInt128Decl)
966 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000967 return UInt128Decl;
968}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000969
Nico Webere1687c52013-06-20 21:44:55 +0000970TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000971 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000972 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000973 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000974
Nico Webere1687c52013-06-20 21:44:55 +0000975 return Float128StubDecl;
976}
977
John McCall48f2d582009-10-23 23:03:21 +0000978void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000979 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000980 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000981 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000982}
983
Artem Belevichb5bc9232015-09-22 17:23:22 +0000984void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
985 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000986 assert((!this->Target || this->Target == &Target) &&
987 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000988 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000989
Douglas Gregore8bbc122011-09-02 00:18:52 +0000990 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000991 this->AuxTarget = AuxTarget;
992
Douglas Gregore8bbc122011-09-02 00:18:52 +0000993 ABI.reset(createCXXABI(Target));
994 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000995 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000996
Chris Lattner970e54e2006-11-12 00:37:36 +0000997 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000998 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattner970e54e2006-11-12 00:37:36 +00001000 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001001 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001002 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001003 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001004 InitBuiltinType(CharTy, BuiltinType::Char_S);
1005 else
1006 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001007 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001008 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1009 InitBuiltinType(ShortTy, BuiltinType::Short);
1010 InitBuiltinType(IntTy, BuiltinType::Int);
1011 InitBuiltinType(LongTy, BuiltinType::Long);
1012 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattner970e54e2006-11-12 00:37:36 +00001014 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001015 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1016 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1017 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1018 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1019 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001020
Chris Lattner970e54e2006-11-12 00:37:36 +00001021 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001022 InitBuiltinType(FloatTy, BuiltinType::Float);
1023 InitBuiltinType(DoubleTy, BuiltinType::Double);
1024 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001025
Chris Lattnerf122cef2009-04-30 02:43:43 +00001026 // GNU extension, 128-bit integers.
1027 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1028 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1029
Hans Wennborg0d81e012013-05-10 10:08:40 +00001030 // C++ 3.9.1p5
1031 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1032 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1033 else // -fshort-wchar makes wchar_t be unsigned.
1034 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1035 if (LangOpts.CPlusPlus && LangOpts.WChar)
1036 WideCharTy = WCharTy;
1037 else {
1038 // C99 (or C++ using -fno-wchar).
1039 WideCharTy = getFromTargetType(Target.getWCharType());
1040 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001041
James Molloy36365542012-05-04 10:55:22 +00001042 WIntTy = getFromTargetType(Target.getWIntType());
1043
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001044 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1045 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1046 else // C99
1047 Char16Ty = getFromTargetType(Target.getChar16Type());
1048
1049 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1050 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1051 else // C99
1052 Char32Ty = getFromTargetType(Target.getChar32Type());
1053
Douglas Gregor4619e432008-12-05 23:32:09 +00001054 // Placeholder type for type-dependent expressions whose type is
1055 // completely unknown. No code should ever check a type against
1056 // DependentTy and users should never see it; however, it is here to
1057 // help diagnose failures to properly check for type-dependent
1058 // expressions.
1059 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060
John McCall36e7fe32010-10-12 00:20:44 +00001061 // Placeholder type for functions.
1062 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1063
John McCall0009fcc2011-04-26 20:42:42 +00001064 // Placeholder type for bound members.
1065 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1066
John McCall526ab472011-10-25 17:37:35 +00001067 // Placeholder type for pseudo-objects.
1068 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1069
John McCall31996342011-04-07 08:22:57 +00001070 // "any" type; useful for debugger-like clients.
1071 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1072
John McCall8a6b59a2011-10-17 18:09:15 +00001073 // Placeholder type for unbridged ARC casts.
1074 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1075
Eli Friedman34866c72012-08-31 00:14:07 +00001076 // Placeholder type for builtin functions.
1077 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1078
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001079 // Placeholder type for OMP array sections.
1080 if (LangOpts.OpenMP)
1081 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1082
Chris Lattner970e54e2006-11-12 00:37:36 +00001083 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001084 FloatComplexTy = getComplexType(FloatTy);
1085 DoubleComplexTy = getComplexType(DoubleTy);
1086 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001088 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001089 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1090 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001091 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001092
1093 if (LangOpts.OpenCL) {
1094 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1095 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1096 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1097 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1098 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001099 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1100 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1101 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1102 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1103 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1104 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1105 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001106 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001107
Guy Benyei61054192013-02-07 10:55:47 +00001108 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001109 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001110 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1111 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1112 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1113 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001114 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001115
1116 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001117 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1118 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001119
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001120 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001121
1122 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001123
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001124 // void * type
1125 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001126
1127 // nullptr type (C++0x 2.14.7)
1128 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001129
1130 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1131 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001132
1133 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001134 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001135}
1136
David Blaikie9c902b52011-09-25 23:23:43 +00001137DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001138 return SourceMgr.getDiagnostics();
1139}
1140
Douglas Gregor561eceb2010-08-30 16:49:28 +00001141AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1142 AttrVec *&Result = DeclAttrs[D];
1143 if (!Result) {
1144 void *Mem = Allocate(sizeof(AttrVec));
1145 Result = new (Mem) AttrVec;
1146 }
1147
1148 return *Result;
1149}
1150
1151/// \brief Erase the attributes corresponding to the given declaration.
1152void ASTContext::eraseDeclAttrs(const Decl *D) {
1153 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1154 if (Pos != DeclAttrs.end()) {
1155 Pos->second->~AttrVec();
1156 DeclAttrs.erase(Pos);
1157 }
1158}
1159
Larisse Voufo39a1e502013-08-06 01:03:05 +00001160// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001161MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001162ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001163 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001164 return getTemplateOrSpecializationInfo(Var)
1165 .dyn_cast<MemberSpecializationInfo *>();
1166}
1167
1168ASTContext::TemplateOrSpecializationInfo
1169ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1170 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1171 TemplateOrInstantiation.find(Var);
1172 if (Pos == TemplateOrInstantiation.end())
1173 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001174
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001175 return Pos->second;
1176}
1177
Mike Stump11289f42009-09-09 15:08:12 +00001178void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001179ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001180 TemplateSpecializationKind TSK,
1181 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001182 assert(Inst->isStaticDataMember() && "Not a static data member");
1183 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001184 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1185 Tmpl, TSK, PointOfInstantiation));
1186}
1187
1188void
1189ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1190 TemplateOrSpecializationInfo TSI) {
1191 assert(!TemplateOrInstantiation[Inst] &&
1192 "Already noted what the variable was instantiated from");
1193 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001194}
1195
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001196FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1197 const FunctionDecl *FD){
1198 assert(FD && "Specialization is 0");
1199 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001200 = ClassScopeSpecializationPattern.find(FD);
1201 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001202 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001203
1204 return Pos->second;
1205}
1206
1207void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1208 FunctionDecl *Pattern) {
1209 assert(FD && "Specialization is 0");
1210 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001211 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001212}
1213
John McCalle61f2ba2009-11-18 02:36:19 +00001214NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001215ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001216 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001217 = InstantiatedFromUsingDecl.find(UUD);
1218 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001219 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001220
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001221 return Pos->second;
1222}
1223
1224void
John McCallb96ec562009-12-04 22:46:56 +00001225ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1226 assert((isa<UsingDecl>(Pattern) ||
1227 isa<UnresolvedUsingValueDecl>(Pattern) ||
1228 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1229 "pattern decl is not a using decl");
1230 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1231 InstantiatedFromUsingDecl[Inst] = Pattern;
1232}
1233
1234UsingShadowDecl *
1235ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1236 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1237 = InstantiatedFromUsingShadowDecl.find(Inst);
1238 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001239 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001240
1241 return Pos->second;
1242}
1243
1244void
1245ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1246 UsingShadowDecl *Pattern) {
1247 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1248 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001249}
1250
Anders Carlsson5da84842009-09-01 04:26:58 +00001251FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1252 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1253 = InstantiatedFromUnnamedFieldDecl.find(Field);
1254 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001255 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001256
Anders Carlsson5da84842009-09-01 04:26:58 +00001257 return Pos->second;
1258}
1259
1260void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1261 FieldDecl *Tmpl) {
1262 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1263 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1264 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1265 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001266
Anders Carlsson5da84842009-09-01 04:26:58 +00001267 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1268}
1269
Douglas Gregor832940b2010-03-02 23:58:15 +00001270ASTContext::overridden_cxx_method_iterator
1271ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1272 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001273 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001274 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001275 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001276
1277 return Pos->second.begin();
1278}
1279
1280ASTContext::overridden_cxx_method_iterator
1281ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1282 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001283 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001284 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001285 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001286
1287 return Pos->second.end();
1288}
1289
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001290unsigned
1291ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1292 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001293 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001294 if (Pos == OverriddenMethods.end())
1295 return 0;
1296
1297 return Pos->second.size();
1298}
1299
Douglas Gregor832940b2010-03-02 23:58:15 +00001300void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1301 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001302 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001303 OverriddenMethods[Method].push_back(Overridden);
1304}
1305
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001306void ASTContext::getOverriddenMethods(
1307 const NamedDecl *D,
1308 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001309 assert(D);
1310
1311 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001312 Overridden.append(overridden_methods_begin(CXXMethod),
1313 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001314 return;
1315 }
1316
1317 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1318 if (!Method)
1319 return;
1320
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001321 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1322 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001323 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001324}
1325
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001326void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1327 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1328 assert(!Import->isFromASTFile() && "Non-local import declaration");
1329 if (!FirstLocalImport) {
1330 FirstLocalImport = Import;
1331 LastLocalImport = Import;
1332 return;
1333 }
1334
1335 LastLocalImport->NextLocalImport = Import;
1336 LastLocalImport = Import;
1337}
1338
Chris Lattner53cfe802007-07-18 17:52:12 +00001339//===----------------------------------------------------------------------===//
1340// Type Sizing and Analysis
1341//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001342
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001343/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1344/// scalar floating point type.
1345const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001346 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001347 assert(BT && "Not a floating point type!");
1348 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001349 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001350 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001351 case BuiltinType::Float: return Target->getFloatFormat();
1352 case BuiltinType::Double: return Target->getDoubleFormat();
1353 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001354 }
1355}
1356
Rafael Espindola71eccb32013-08-08 19:53:46 +00001357CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001358 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001359
John McCall94268702010-10-08 18:24:19 +00001360 bool UseAlignAttrOnly = false;
1361 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1362 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001363
John McCall94268702010-10-08 18:24:19 +00001364 // __attribute__((aligned)) can increase or decrease alignment
1365 // *except* on a struct or struct member, where it only increases
1366 // alignment unless 'packed' is also specified.
1367 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001368 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001369 // ignore that possibility; Sema should diagnose it.
1370 if (isa<FieldDecl>(D)) {
1371 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1372 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1373 } else {
1374 UseAlignAttrOnly = true;
1375 }
1376 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001377 else if (isa<FieldDecl>(D))
1378 UseAlignAttrOnly =
1379 D->hasAttr<PackedAttr>() ||
1380 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001381
John McCall4e819612011-01-20 07:57:12 +00001382 // If we're using the align attribute only, just ignore everything
1383 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001384 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001385 // do nothing
1386
John McCall94268702010-10-08 18:24:19 +00001387 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001388 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001389 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001390 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001391 T = RT->getPointeeType();
1392 else
1393 T = getPointerType(RT->getPointeeType());
1394 }
Richard Smithf6d70302014-06-10 23:34:28 +00001395 QualType BaseT = getBaseElementType(T);
1396 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001397 // Adjust alignments of declarations with array type by the
1398 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001399 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001400 unsigned MinWidth = Target->getLargeArrayMinWidth();
1401 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001402 if (isa<VariableArrayType>(arrayType))
1403 Align = std::max(Align, Target->getLargeArrayAlign());
1404 else if (isa<ConstantArrayType>(arrayType) &&
1405 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1406 Align = std::max(Align, Target->getLargeArrayAlign());
1407 }
John McCall33ddac02011-01-19 10:06:00 +00001408 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001409 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001410 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001411 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001412 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1413 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001414 }
John McCall4e819612011-01-20 07:57:12 +00001415
1416 // Fields can be subject to extra alignment constraints, like if
1417 // the field is packed, the struct is packed, or the struct has a
1418 // a max-field-alignment constraint (#pragma pack). So calculate
1419 // the actual alignment of the field within the struct, and then
1420 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001421 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1422 const RecordDecl *Parent = Field->getParent();
1423 // We can only produce a sensible answer if the record is valid.
1424 if (!Parent->isInvalidDecl()) {
1425 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001426
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001427 // Start with the record's overall alignment.
1428 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001429
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001430 // Use the GCD of that and the offset within the record.
1431 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1432 if (Offset > 0) {
1433 // Alignment is always a power of 2, so the GCD will be a power of 2,
1434 // which means we get to do this crazy thing instead of Euclid's.
1435 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1436 if (LowBitOfOffset < FieldAlign)
1437 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1438 }
1439
1440 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001441 }
Charles Davis3fc51072010-02-23 04:52:00 +00001442 }
Chris Lattner68061312009-01-24 21:53:27 +00001443 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001444
Ken Dyckcc56c542011-01-15 18:38:59 +00001445 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001446}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001447
John McCallf1249922012-08-21 04:10:00 +00001448// getTypeInfoDataSizeInChars - Return the size of a type, in
1449// chars. If the type is a record, its data size is returned. This is
1450// the size of the memcpy that's performed when assigning this type
1451// using a trivial copy/move assignment operator.
1452std::pair<CharUnits, CharUnits>
1453ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1454 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1455
1456 // In C++, objects can sometimes be allocated into the tail padding
1457 // of a base-class subobject. We decide whether that's possible
1458 // during class layout, so here we can just trust the layout results.
1459 if (getLangOpts().CPlusPlus) {
1460 if (const RecordType *RT = T->getAs<RecordType>()) {
1461 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1462 sizeAndAlign.first = layout.getDataSize();
1463 }
1464 }
1465
1466 return sizeAndAlign;
1467}
1468
Richard Trieu04d2d942013-05-14 21:59:17 +00001469/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1470/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1471std::pair<CharUnits, CharUnits>
1472static getConstantArrayInfoInChars(const ASTContext &Context,
1473 const ConstantArrayType *CAT) {
1474 std::pair<CharUnits, CharUnits> EltInfo =
1475 Context.getTypeInfoInChars(CAT->getElementType());
1476 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001477 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1478 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001479 "Overflow in array type char size evaluation");
1480 uint64_t Width = EltInfo.first.getQuantity() * Size;
1481 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001482 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1483 Context.getTargetInfo().getPointerWidth(0) == 64)
1484 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001485 return std::make_pair(CharUnits::fromQuantity(Width),
1486 CharUnits::fromQuantity(Align));
1487}
1488
John McCall87fe5d52010-05-20 01:18:31 +00001489std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001490ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001491 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1492 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001493 TypeInfo Info = getTypeInfo(T);
1494 return std::make_pair(toCharUnitsFromBits(Info.Width),
1495 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001496}
1497
1498std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001499ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001500 return getTypeInfoInChars(T.getTypePtr());
1501}
1502
David Majnemer34b57492014-07-30 01:30:47 +00001503bool ASTContext::isAlignmentRequired(const Type *T) const {
1504 return getTypeInfo(T).AlignIsRequired;
1505}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001506
David Majnemer34b57492014-07-30 01:30:47 +00001507bool ASTContext::isAlignmentRequired(QualType T) const {
1508 return isAlignmentRequired(T.getTypePtr());
1509}
1510
1511TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001512 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1513 if (I != MemoizedTypeInfo.end())
1514 return I->second;
1515
1516 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1517 TypeInfo TI = getTypeInfoImpl(T);
1518 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001519 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001520}
1521
1522/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1523/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001524///
1525/// FIXME: Pointers into different addr spaces could have different sizes and
1526/// alignment requirements: getPointerInfo should take an AddrSpace, this
1527/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001528TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1529 uint64_t Width = 0;
1530 unsigned Align = 8;
1531 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001532 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001533#define TYPE(Class, Base)
1534#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001535#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001536#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001537#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1538 case Type::Class: \
1539 assert(!T->isDependentType() && "should not see dependent types here"); \
1540 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001541#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001542 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001543
Chris Lattner355332d2007-07-13 22:27:08 +00001544 case Type::FunctionNoProto:
1545 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001546 // GCC extension: alignof(function) = 32 bits
1547 Width = 0;
1548 Align = 32;
1549 break;
1550
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001551 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001552 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001553 Width = 0;
1554 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1555 break;
1556
Steve Naroff5c131802007-08-30 01:06:46 +00001557 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001558 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001559
David Majnemer34b57492014-07-30 01:30:47 +00001560 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001561 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001562 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001563 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001564 Width = EltInfo.Width * Size;
1565 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001566 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1567 getTargetInfo().getPointerWidth(0) == 64)
1568 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001569 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001570 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001571 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001572 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001573 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001574 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1575 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001576 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001577 // If the alignment is not a power of 2, round up to the next power of 2.
1578 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001579 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001580 Align = llvm::NextPowerOf2(Align);
1581 Width = llvm::RoundUpToAlignment(Width, Align);
1582 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001583 // Adjust the alignment based on the target max.
1584 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1585 if (TargetVectorAlign && TargetVectorAlign < Align)
1586 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001587 break;
1588 }
Chris Lattner647fb222007-07-18 18:26:58 +00001589
Chris Lattner7570e9c2008-03-08 08:52:55 +00001590 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001591 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001592 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001593 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001594 // GCC extension: alignof(void) = 8 bits.
1595 Width = 0;
1596 Align = 8;
1597 break;
1598
Chris Lattner6a4f7452007-12-19 19:23:28 +00001599 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001600 Width = Target->getBoolWidth();
1601 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001602 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001603 case BuiltinType::Char_S:
1604 case BuiltinType::Char_U:
1605 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001606 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001607 Width = Target->getCharWidth();
1608 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001609 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001610 case BuiltinType::WChar_S:
1611 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001612 Width = Target->getWCharWidth();
1613 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001614 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001615 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001616 Width = Target->getChar16Width();
1617 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001618 break;
1619 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001620 Width = Target->getChar32Width();
1621 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001622 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001623 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001624 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001625 Width = Target->getShortWidth();
1626 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001627 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001628 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001629 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001630 Width = Target->getIntWidth();
1631 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001632 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001633 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001634 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001635 Width = Target->getLongWidth();
1636 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001637 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001638 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001639 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001640 Width = Target->getLongLongWidth();
1641 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001642 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001643 case BuiltinType::Int128:
1644 case BuiltinType::UInt128:
1645 Width = 128;
1646 Align = 128; // int128_t is 128-bit aligned on all targets.
1647 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001648 case BuiltinType::Half:
1649 Width = Target->getHalfWidth();
1650 Align = Target->getHalfAlign();
1651 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001652 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001653 Width = Target->getFloatWidth();
1654 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001655 break;
1656 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001657 Width = Target->getDoubleWidth();
1658 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001659 break;
1660 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001661 Width = Target->getLongDoubleWidth();
1662 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001663 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001664 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001665 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1666 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001667 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001668 case BuiltinType::ObjCId:
1669 case BuiltinType::ObjCClass:
1670 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001671 Width = Target->getPointerWidth(0);
1672 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001673 break;
Guy Benyei61054192013-02-07 10:55:47 +00001674 case BuiltinType::OCLSampler:
1675 // Samplers are modeled as integers.
1676 Width = Target->getIntWidth();
1677 Align = Target->getIntAlign();
1678 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001679 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001680 case BuiltinType::OCLClkEvent:
1681 case BuiltinType::OCLQueue:
1682 case BuiltinType::OCLNDRange:
1683 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001684 case BuiltinType::OCLImage1d:
1685 case BuiltinType::OCLImage1dArray:
1686 case BuiltinType::OCLImage1dBuffer:
1687 case BuiltinType::OCLImage2d:
1688 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001689 case BuiltinType::OCLImage2dDepth:
1690 case BuiltinType::OCLImage2dArrayDepth:
1691 case BuiltinType::OCLImage2dMSAA:
1692 case BuiltinType::OCLImage2dArrayMSAA:
1693 case BuiltinType::OCLImage2dMSAADepth:
1694 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001695 case BuiltinType::OCLImage3d:
1696 // Currently these types are pointers to opaque types.
1697 Width = Target->getPointerWidth(0);
1698 Align = Target->getPointerAlign(0);
1699 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001700 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001701 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001702 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001703 Width = Target->getPointerWidth(0);
1704 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001705 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001706 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001707 unsigned AS = getTargetAddressSpace(
1708 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getPointerWidth(AS);
1710 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001711 break;
1712 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001713 case Type::LValueReference:
1714 case Type::RValueReference: {
1715 // alignof and sizeof should never enter this code path here, so we go
1716 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001717 unsigned AS = getTargetAddressSpace(
1718 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001719 Width = Target->getPointerWidth(AS);
1720 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001721 break;
1722 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001723 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001724 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001725 Width = Target->getPointerWidth(AS);
1726 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001727 break;
1728 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001729 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001730 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001731 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001732 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001733 }
Chris Lattner647fb222007-07-18 18:26:58 +00001734 case Type::Complex: {
1735 // Complex types have the same alignment as their elements, but twice the
1736 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001737 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1738 Width = EltInfo.Width * 2;
1739 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001740 break;
1741 }
John McCall8b07ec22010-05-15 11:32:37 +00001742 case Type::ObjCObject:
1743 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001744 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001745 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001746 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001747 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001748 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001749 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001750 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001751 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001752 break;
1753 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001754 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001755 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001756 const TagType *TT = cast<TagType>(T);
1757
1758 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001759 Width = 8;
1760 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001761 break;
1762 }
Mike Stump11289f42009-09-09 15:08:12 +00001763
David Majnemer475b25e2015-01-21 10:54:38 +00001764 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1765 const EnumDecl *ED = ET->getDecl();
1766 TypeInfo Info =
1767 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1768 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1769 Info.Align = AttrAlign;
1770 Info.AlignIsRequired = true;
1771 }
1772 return Info;
1773 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001774
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001775 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001776 const RecordDecl *RD = RT->getDecl();
1777 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001778 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001779 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001780 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001781 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001782 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001783
Chris Lattner63d2b362009-10-22 05:17:15 +00001784 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001785 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1786 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001787
Richard Smith30482bc2011-02-20 03:19:35 +00001788 case Type::Auto: {
1789 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001790 assert(!A->getDeducedType().isNull() &&
1791 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001792 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001793 }
1794
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001795 case Type::Paren:
1796 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1797
Douglas Gregoref462e62009-04-30 17:32:17 +00001798 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001799 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001800 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001801 // If the typedef has an aligned attribute on it, it overrides any computed
1802 // alignment we have. This violates the GCC documentation (which says that
1803 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001804 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001805 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001806 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001807 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001808 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001809 AlignIsRequired = Info.AlignIsRequired;
1810 }
David Majnemer34b57492014-07-30 01:30:47 +00001811 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001812 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001813 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001814
Abramo Bagnara6150c882010-05-11 21:36:43 +00001815 case Type::Elaborated:
1816 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001817
John McCall81904512011-01-06 01:58:22 +00001818 case Type::Attributed:
1819 return getTypeInfo(
1820 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1821
Eli Friedman0dfb8892011-10-06 23:00:33 +00001822 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001823 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001824 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1825 Width = Info.Width;
1826 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001827
1828 // If the size of the type doesn't exceed the platform's max
1829 // atomic promotion width, make the size and alignment more
1830 // favorable to atomic operations:
1831 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1832 // Round the size up to a power of 2.
1833 if (!llvm::isPowerOf2_64(Width))
1834 Width = llvm::NextPowerOf2(Width);
1835
1836 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001837 Align = static_cast<unsigned>(Width);
1838 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001839 }
1840
Douglas Gregoref462e62009-04-30 17:32:17 +00001841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001843 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001844 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001845}
1846
Alexey Bataev00396512015-07-02 03:40:19 +00001847unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1848 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1849 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1850 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1851 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1852 getTargetInfo().getABI() == "elfv1-qpx" &&
1853 T->isSpecificBuiltinType(BuiltinType::Double))
1854 SimdAlign = 256;
1855 return SimdAlign;
1856}
1857
Ken Dyckcc56c542011-01-15 18:38:59 +00001858/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1859CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1860 return CharUnits::fromQuantity(BitSize / getCharWidth());
1861}
1862
Ken Dyckb0fcc592011-02-11 01:54:29 +00001863/// toBits - Convert a size in characters to a size in characters.
1864int64_t ASTContext::toBits(CharUnits CharSize) const {
1865 return CharSize.getQuantity() * getCharWidth();
1866}
1867
Ken Dyck8c89d592009-12-22 14:23:30 +00001868/// getTypeSizeInChars - Return the size of the specified type, in characters.
1869/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001870CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001871 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001872}
Jay Foad39c79802011-01-12 09:06:06 +00001873CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001874 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001875}
1876
Ken Dycka6046ab2010-01-26 17:25:18 +00001877/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001878/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001879CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001880 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001881}
Jay Foad39c79802011-01-12 09:06:06 +00001882CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001883 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001884}
1885
Chris Lattnera3402cd2009-01-27 18:08:34 +00001886/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1887/// type for the current target in bits. This can be different than the ABI
1888/// alignment in cases where it is beneficial for performance to overalign
1889/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001890unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001891 TypeInfo TI = getTypeInfo(T);
1892 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001893
David Majnemere1544562015-04-24 01:25:05 +00001894 T = T->getBaseElementTypeUnsafe();
1895
1896 // The preferred alignment of member pointers is that of a pointer.
1897 if (T->isMemberPointerType())
1898 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1899
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001900 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1901 return ABIAlign; // Never overalign on XCore.
1902
Eli Friedman7ab09572009-05-25 21:27:19 +00001903 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001904 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001905 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001906 if (const EnumType *ET = T->getAs<EnumType>())
1907 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001908 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001909 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1910 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001911 // Don't increase the alignment if an alignment attribute was specified on a
1912 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001913 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001914 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001915
Chris Lattnera3402cd2009-01-27 18:08:34 +00001916 return ABIAlign;
1917}
1918
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001919/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1920/// for __attribute__((aligned)) on this target, to be used if no alignment
1921/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001922unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001923 return getTargetInfo().getDefaultAlignForAttributeAligned();
1924}
1925
Ulrich Weigandfa806422013-05-06 16:23:57 +00001926/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1927/// to a global variable of the specified type.
1928unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1929 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1930}
1931
1932/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1933/// should be given to a global variable of the specified type.
1934CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1935 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1936}
1937
David Majnemer08ef2ba2015-06-23 20:34:18 +00001938CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1939 CharUnits Offset = CharUnits::Zero();
1940 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1941 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1942 Offset += Layout->getBaseClassOffset(Base);
1943 Layout = &getASTRecordLayout(Base);
1944 }
1945 return Offset;
1946}
1947
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001948/// DeepCollectObjCIvars -
1949/// This routine first collects all declared, but not synthesized, ivars in
1950/// super class and then collects all ivars, including those synthesized for
1951/// current class. This routine is used for implementation of current class
1952/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001953///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001954void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1955 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001956 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001957 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1958 DeepCollectObjCIvars(SuperClass, false, Ivars);
1959 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001960 for (const auto *I : OI->ivars())
1961 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001962 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001963 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001964 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001965 Iv= Iv->getNextIvar())
1966 Ivars.push_back(Iv);
1967 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001968}
1969
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001970/// CollectInheritedProtocols - Collect all protocols in current class and
1971/// those inherited by it.
1972void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001973 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001974 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001975 // We can use protocol_iterator here instead of
1976 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001977 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001978 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001979 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001980
1981 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001982 for (const auto *Cat : OI->visible_categories())
1983 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001984
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001985 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1986 while (SD) {
1987 CollectInheritedProtocols(SD, Protocols);
1988 SD = SD->getSuperClass();
1989 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001990 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001991 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001992 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001993 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001994 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001995 // Insert the protocol.
1996 if (!Protocols.insert(
1997 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1998 return;
1999
2000 for (auto *Proto : OP->protocols())
2001 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002002 }
2003}
2004
Jay Foad39c79802011-01-12 09:06:06 +00002005unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002006 unsigned count = 0;
2007 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002008 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002009 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002010
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002011 // Count ivar defined in this class's implementation. This
2012 // includes synthesized ivars.
2013 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002014 count += ImplDecl->ivar_size();
2015
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002016 return count;
2017}
2018
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002019bool ASTContext::isSentinelNullExpr(const Expr *E) {
2020 if (!E)
2021 return false;
2022
2023 // nullptr_t is always treated as null.
2024 if (E->getType()->isNullPtrType()) return true;
2025
2026 if (E->getType()->isAnyPointerType() &&
2027 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2028 Expr::NPC_ValueDependentIsNull))
2029 return true;
2030
2031 // Unfortunately, __null has type 'int'.
2032 if (isa<GNUNullExpr>(E)) return true;
2033
2034 return false;
2035}
2036
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002037/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2038ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2039 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2040 I = ObjCImpls.find(D);
2041 if (I != ObjCImpls.end())
2042 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002043 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002044}
2045/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2046ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2047 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2048 I = ObjCImpls.find(D);
2049 if (I != ObjCImpls.end())
2050 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002051 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002052}
2053
2054/// \brief Set the implementation of ObjCInterfaceDecl.
2055void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2056 ObjCImplementationDecl *ImplD) {
2057 assert(IFaceD && ImplD && "Passed null params");
2058 ObjCImpls[IFaceD] = ImplD;
2059}
2060/// \brief Set the implementation of ObjCCategoryDecl.
2061void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2062 ObjCCategoryImplDecl *ImplD) {
2063 assert(CatD && ImplD && "Passed null params");
2064 ObjCImpls[CatD] = ImplD;
2065}
2066
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002067const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2068 const NamedDecl *ND) const {
2069 if (const ObjCInterfaceDecl *ID =
2070 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002071 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002072 if (const ObjCCategoryDecl *CD =
2073 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002074 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002075 if (const ObjCImplDecl *IMD =
2076 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002077 return IMD->getClassInterface();
2078
Craig Topper36250ad2014-05-12 05:36:57 +00002079 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002080}
2081
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002082/// \brief Get the copy initialization expression of VarDecl,or NULL if
2083/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002084Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002085 assert(VD && "Passed null params");
2086 assert(VD->hasAttr<BlocksAttr>() &&
2087 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002088 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002089 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002090 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002091}
2092
2093/// \brief Set the copy inialization expression of a block var decl.
2094void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2095 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002096 assert(VD->hasAttr<BlocksAttr>() &&
2097 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002098 BlockVarCopyInits[VD] = Init;
2099}
2100
John McCallbcd03502009-12-07 02:54:59 +00002101TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002102 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002103 if (!DataSize)
2104 DataSize = TypeLoc::getFullDataSizeForType(T);
2105 else
2106 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002107 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002108
John McCallbcd03502009-12-07 02:54:59 +00002109 TypeSourceInfo *TInfo =
2110 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2111 new (TInfo) TypeSourceInfo(T);
2112 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002113}
2114
John McCallbcd03502009-12-07 02:54:59 +00002115TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002116 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002117 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002118 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002119 return DI;
2120}
2121
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002122const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002123ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002124 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002125}
2126
2127const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002128ASTContext::getASTObjCImplementationLayout(
2129 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002130 return getObjCLayout(D->getClassInterface(), D);
2131}
2132
Chris Lattner983a8bb2007-07-13 22:13:22 +00002133//===----------------------------------------------------------------------===//
2134// Type creation/memoization methods
2135//===----------------------------------------------------------------------===//
2136
Jay Foad39c79802011-01-12 09:06:06 +00002137QualType
John McCall33ddac02011-01-19 10:06:00 +00002138ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2139 unsigned fastQuals = quals.getFastQualifiers();
2140 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002141
2142 // Check if we've already instantiated this type.
2143 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002144 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002145 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002146 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2147 assert(eq->getQualifiers() == quals);
2148 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002149 }
2150
John McCall33ddac02011-01-19 10:06:00 +00002151 // If the base type is not canonical, make the appropriate canonical type.
2152 QualType canon;
2153 if (!baseType->isCanonicalUnqualified()) {
2154 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002155 canonSplit.Quals.addConsistentQualifiers(quals);
2156 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002157
2158 // Re-find the insert position.
2159 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2160 }
2161
2162 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2163 ExtQualNodes.InsertNode(eq, insertPos);
2164 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002165}
2166
Jay Foad39c79802011-01-12 09:06:06 +00002167QualType
2168ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002169 QualType CanT = getCanonicalType(T);
2170 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002171 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002172
John McCall8ccfcb52009-09-24 19:53:00 +00002173 // If we are composing extended qualifiers together, merge together
2174 // into one ExtQuals node.
2175 QualifierCollector Quals;
2176 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002177
John McCall8ccfcb52009-09-24 19:53:00 +00002178 // If this type already has an address space specified, it cannot get
2179 // another one.
2180 assert(!Quals.hasAddressSpace() &&
2181 "Type cannot be in multiple addr spaces!");
2182 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002183
John McCall8ccfcb52009-09-24 19:53:00 +00002184 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002185}
2186
Chris Lattnerd60183d2009-02-18 22:53:11 +00002187QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002188 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002189 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002190 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002191 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002192
John McCall53fa7142010-12-24 02:08:15 +00002193 if (const PointerType *ptr = T->getAs<PointerType>()) {
2194 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002195 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002196 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2197 return getPointerType(ResultType);
2198 }
2199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
John McCall8ccfcb52009-09-24 19:53:00 +00002201 // If we are composing extended qualifiers together, merge together
2202 // into one ExtQuals node.
2203 QualifierCollector Quals;
2204 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002205
John McCall8ccfcb52009-09-24 19:53:00 +00002206 // If this type already has an ObjCGC specified, it cannot get
2207 // another one.
2208 assert(!Quals.hasObjCGCAttr() &&
2209 "Type cannot have multiple ObjCGCs!");
2210 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002211
John McCall8ccfcb52009-09-24 19:53:00 +00002212 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002213}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002214
John McCall4f5019e2010-12-19 02:44:49 +00002215const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2216 FunctionType::ExtInfo Info) {
2217 if (T->getExtInfo() == Info)
2218 return T;
2219
2220 QualType Result;
2221 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002222 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002223 } else {
2224 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2225 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2226 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002227 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002228 }
2229
2230 return cast<FunctionType>(Result.getTypePtr());
2231}
2232
Richard Smith2a7d4812013-05-04 07:00:32 +00002233void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2234 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002235 FD = FD->getMostRecentDecl();
2236 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002237 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2238 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002239 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002240 if (FunctionDecl *Next = FD->getPreviousDecl())
2241 FD = Next;
2242 else
2243 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002244 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002245 if (ASTMutationListener *L = getASTMutationListener())
2246 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002247}
2248
Richard Smith0b3a4622014-11-13 20:01:57 +00002249/// Get a function type and produce the equivalent function type with the
2250/// specified exception specification. Type sugar that can be present on a
2251/// declaration of a function with an exception specification is permitted
2252/// and preserved. Other type sugar (for instance, typedefs) is not.
2253static QualType getFunctionTypeWithExceptionSpec(
2254 ASTContext &Context, QualType Orig,
2255 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2256 // Might have some parens.
2257 if (auto *PT = dyn_cast<ParenType>(Orig))
2258 return Context.getParenType(
2259 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2260
2261 // Might have a calling-convention attribute.
2262 if (auto *AT = dyn_cast<AttributedType>(Orig))
2263 return Context.getAttributedType(
2264 AT->getAttrKind(),
2265 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2266 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2267 ESI));
2268
2269 // Anything else must be a function type. Rebuild it with the new exception
2270 // specification.
2271 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2272 return Context.getFunctionType(
2273 Proto->getReturnType(), Proto->getParamTypes(),
2274 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2275}
2276
2277void ASTContext::adjustExceptionSpec(
2278 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2279 bool AsWritten) {
2280 // Update the type.
2281 QualType Updated =
2282 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2283 FD->setType(Updated);
2284
2285 if (!AsWritten)
2286 return;
2287
2288 // Update the type in the type source information too.
2289 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2290 // If the type and the type-as-written differ, we may need to update
2291 // the type-as-written too.
2292 if (TSInfo->getType() != FD->getType())
2293 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2294
2295 // FIXME: When we get proper type location information for exceptions,
2296 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2297 // up the TypeSourceInfo;
2298 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2299 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2300 "TypeLoc size mismatch from updating exception specification");
2301 TSInfo->overrideType(Updated);
2302 }
2303}
2304
Chris Lattnerc6395932007-06-22 20:56:16 +00002305/// getComplexType - Return the uniqued reference to the type for a complex
2306/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002307QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002308 // Unique pointers, to guarantee there is only one pointer of a particular
2309 // structure.
2310 llvm::FoldingSetNodeID ID;
2311 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002312
Craig Topper36250ad2014-05-12 05:36:57 +00002313 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002314 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2315 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002316
Chris Lattnerc6395932007-06-22 20:56:16 +00002317 // If the pointee type isn't canonical, this won't be a canonical type either,
2318 // so fill in the canonical type field.
2319 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002320 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002321 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002322
Chris Lattnerc6395932007-06-22 20:56:16 +00002323 // Get the new insert position for the node we care about.
2324 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002325 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002326 }
John McCall90d1c2d2009-09-24 23:30:46 +00002327 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002328 Types.push_back(New);
2329 ComplexTypes.InsertNode(New, InsertPos);
2330 return QualType(New, 0);
2331}
2332
Chris Lattner970e54e2006-11-12 00:37:36 +00002333/// getPointerType - Return the uniqued reference to the type for a pointer to
2334/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002335QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002336 // Unique pointers, to guarantee there is only one pointer of a particular
2337 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002338 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002339 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002340
Craig Topper36250ad2014-05-12 05:36:57 +00002341 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002342 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002343 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002344
Chris Lattner7ccecb92006-11-12 08:50:50 +00002345 // If the pointee type isn't canonical, this won't be a canonical type either,
2346 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002347 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002348 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002349 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002350
Bob Wilsonc8541f22013-03-15 17:12:43 +00002351 // Get the new insert position for the node we care about.
2352 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002353 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002354 }
John McCall90d1c2d2009-09-24 23:30:46 +00002355 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002356 Types.push_back(New);
2357 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002358 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002359}
2360
Reid Kleckner0503a872013-12-05 01:23:43 +00002361QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2362 llvm::FoldingSetNodeID ID;
2363 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002364 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002365 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2366 if (AT)
2367 return QualType(AT, 0);
2368
2369 QualType Canonical = getCanonicalType(New);
2370
2371 // Get the new insert position for the node we care about.
2372 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002373 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002374
2375 AT = new (*this, TypeAlignment)
2376 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2377 Types.push_back(AT);
2378 AdjustedTypes.InsertNode(AT, InsertPos);
2379 return QualType(AT, 0);
2380}
2381
Reid Kleckner8a365022013-06-24 17:51:48 +00002382QualType ASTContext::getDecayedType(QualType T) const {
2383 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2384
Reid Kleckner8a365022013-06-24 17:51:48 +00002385 QualType Decayed;
2386
2387 // C99 6.7.5.3p7:
2388 // A declaration of a parameter as "array of type" shall be
2389 // adjusted to "qualified pointer to type", where the type
2390 // qualifiers (if any) are those specified within the [ and ] of
2391 // the array type derivation.
2392 if (T->isArrayType())
2393 Decayed = getArrayDecayedType(T);
2394
2395 // C99 6.7.5.3p8:
2396 // A declaration of a parameter as "function returning type"
2397 // shall be adjusted to "pointer to function returning type", as
2398 // in 6.3.2.1.
2399 if (T->isFunctionType())
2400 Decayed = getPointerType(T);
2401
Reid Kleckner0503a872013-12-05 01:23:43 +00002402 llvm::FoldingSetNodeID ID;
2403 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002404 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002405 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2406 if (AT)
2407 return QualType(AT, 0);
2408
Reid Kleckner8a365022013-06-24 17:51:48 +00002409 QualType Canonical = getCanonicalType(Decayed);
2410
2411 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002412 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002413 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002414
Reid Kleckner0503a872013-12-05 01:23:43 +00002415 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2416 Types.push_back(AT);
2417 AdjustedTypes.InsertNode(AT, InsertPos);
2418 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002419}
2420
Mike Stump11289f42009-09-09 15:08:12 +00002421/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002422/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002423QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002424 assert(T->isFunctionType() && "block of function types only");
2425 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002426 // structure.
2427 llvm::FoldingSetNodeID ID;
2428 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002429
Craig Topper36250ad2014-05-12 05:36:57 +00002430 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002431 if (BlockPointerType *PT =
2432 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2433 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002434
2435 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002436 // type either so fill in the canonical type field.
2437 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002438 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002439 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002440
Steve Naroffec33ed92008-08-27 16:04:49 +00002441 // Get the new insert position for the node we care about.
2442 BlockPointerType *NewIP =
2443 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002444 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002445 }
John McCall90d1c2d2009-09-24 23:30:46 +00002446 BlockPointerType *New
2447 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002448 Types.push_back(New);
2449 BlockPointerTypes.InsertNode(New, InsertPos);
2450 return QualType(New, 0);
2451}
2452
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002453/// getLValueReferenceType - Return the uniqued reference to the type for an
2454/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002455QualType
2456ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002457 assert(getCanonicalType(T) != OverloadTy &&
2458 "Unresolved overloaded function type");
2459
Bill Wendling3708c182007-05-27 10:15:43 +00002460 // Unique pointers, to guarantee there is only one pointer of a particular
2461 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002462 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002463 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002464
Craig Topper36250ad2014-05-12 05:36:57 +00002465 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002466 if (LValueReferenceType *RT =
2467 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002468 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002469
John McCallfc93cf92009-10-22 22:37:11 +00002470 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2471
Bill Wendling3708c182007-05-27 10:15:43 +00002472 // If the referencee type isn't canonical, this won't be a canonical type
2473 // either, so fill in the canonical type field.
2474 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002475 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2476 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2477 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002478
Bill Wendling3708c182007-05-27 10:15:43 +00002479 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002480 LValueReferenceType *NewIP =
2481 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002482 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002483 }
2484
John McCall90d1c2d2009-09-24 23:30:46 +00002485 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002486 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2487 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002488 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002489 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002490
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002491 return QualType(New, 0);
2492}
2493
2494/// getRValueReferenceType - Return the uniqued reference to the type for an
2495/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002496QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002497 // Unique pointers, to guarantee there is only one pointer of a particular
2498 // structure.
2499 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002500 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002501
Craig Topper36250ad2014-05-12 05:36:57 +00002502 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002503 if (RValueReferenceType *RT =
2504 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2505 return QualType(RT, 0);
2506
John McCallfc93cf92009-10-22 22:37:11 +00002507 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2508
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002509 // If the referencee type isn't canonical, this won't be a canonical type
2510 // either, so fill in the canonical type field.
2511 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002512 if (InnerRef || !T.isCanonical()) {
2513 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2514 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002515
2516 // Get the new insert position for the node we care about.
2517 RValueReferenceType *NewIP =
2518 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002519 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002520 }
2521
John McCall90d1c2d2009-09-24 23:30:46 +00002522 RValueReferenceType *New
2523 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002524 Types.push_back(New);
2525 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002526 return QualType(New, 0);
2527}
2528
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002529/// getMemberPointerType - Return the uniqued reference to the type for a
2530/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002531QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002532 // Unique pointers, to guarantee there is only one pointer of a particular
2533 // structure.
2534 llvm::FoldingSetNodeID ID;
2535 MemberPointerType::Profile(ID, T, Cls);
2536
Craig Topper36250ad2014-05-12 05:36:57 +00002537 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002538 if (MemberPointerType *PT =
2539 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2540 return QualType(PT, 0);
2541
2542 // If the pointee or class type isn't canonical, this won't be a canonical
2543 // type either, so fill in the canonical type field.
2544 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002545 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002546 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2547
2548 // Get the new insert position for the node we care about.
2549 MemberPointerType *NewIP =
2550 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002551 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002552 }
John McCall90d1c2d2009-09-24 23:30:46 +00002553 MemberPointerType *New
2554 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002555 Types.push_back(New);
2556 MemberPointerTypes.InsertNode(New, InsertPos);
2557 return QualType(New, 0);
2558}
2559
Mike Stump11289f42009-09-09 15:08:12 +00002560/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002561/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002562QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002563 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002564 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002565 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002566 assert((EltTy->isDependentType() ||
2567 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002568 "Constant array of VLAs is illegal!");
2569
Chris Lattnere2df3f92009-05-13 04:12:56 +00002570 // Convert the array size into a canonical width matching the pointer size for
2571 // the target.
2572 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002573 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002574 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002575
Chris Lattner23b7eb62007-06-15 23:05:46 +00002576 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002577 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002578
Craig Topper36250ad2014-05-12 05:36:57 +00002579 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002580 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002581 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002582 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002583
John McCall33ddac02011-01-19 10:06:00 +00002584 // If the element type isn't canonical or has qualifiers, this won't
2585 // be a canonical type either, so fill in the canonical type field.
2586 QualType Canon;
2587 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2588 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002589 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002590 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002591 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002592
Chris Lattner36f8e652007-01-27 08:31:04 +00002593 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002594 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002595 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002596 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002597 }
Mike Stump11289f42009-09-09 15:08:12 +00002598
John McCall90d1c2d2009-09-24 23:30:46 +00002599 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002600 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002601 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002602 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002603 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002604}
2605
John McCall06549462011-01-18 08:40:38 +00002606/// getVariableArrayDecayedType - Turns the given type, which may be
2607/// variably-modified, into the corresponding type with all the known
2608/// sizes replaced with [*].
2609QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2610 // Vastly most common case.
2611 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002612
John McCall06549462011-01-18 08:40:38 +00002613 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002614
John McCall06549462011-01-18 08:40:38 +00002615 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002616 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002617 switch (ty->getTypeClass()) {
2618#define TYPE(Class, Base)
2619#define ABSTRACT_TYPE(Class, Base)
2620#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2621#include "clang/AST/TypeNodes.def"
2622 llvm_unreachable("didn't desugar past all non-canonical types?");
2623
2624 // These types should never be variably-modified.
2625 case Type::Builtin:
2626 case Type::Complex:
2627 case Type::Vector:
2628 case Type::ExtVector:
2629 case Type::DependentSizedExtVector:
2630 case Type::ObjCObject:
2631 case Type::ObjCInterface:
2632 case Type::ObjCObjectPointer:
2633 case Type::Record:
2634 case Type::Enum:
2635 case Type::UnresolvedUsing:
2636 case Type::TypeOfExpr:
2637 case Type::TypeOf:
2638 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002639 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002640 case Type::DependentName:
2641 case Type::InjectedClassName:
2642 case Type::TemplateSpecialization:
2643 case Type::DependentTemplateSpecialization:
2644 case Type::TemplateTypeParm:
2645 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002646 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002647 case Type::PackExpansion:
2648 llvm_unreachable("type should never be variably-modified");
2649
2650 // These types can be variably-modified but should never need to
2651 // further decay.
2652 case Type::FunctionNoProto:
2653 case Type::FunctionProto:
2654 case Type::BlockPointer:
2655 case Type::MemberPointer:
2656 return type;
2657
2658 // These types can be variably-modified. All these modifications
2659 // preserve structure except as noted by comments.
2660 // TODO: if we ever care about optimizing VLAs, there are no-op
2661 // optimizations available here.
2662 case Type::Pointer:
2663 result = getPointerType(getVariableArrayDecayedType(
2664 cast<PointerType>(ty)->getPointeeType()));
2665 break;
2666
2667 case Type::LValueReference: {
2668 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2669 result = getLValueReferenceType(
2670 getVariableArrayDecayedType(lv->getPointeeType()),
2671 lv->isSpelledAsLValue());
2672 break;
2673 }
2674
2675 case Type::RValueReference: {
2676 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2677 result = getRValueReferenceType(
2678 getVariableArrayDecayedType(lv->getPointeeType()));
2679 break;
2680 }
2681
Eli Friedman0dfb8892011-10-06 23:00:33 +00002682 case Type::Atomic: {
2683 const AtomicType *at = cast<AtomicType>(ty);
2684 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2685 break;
2686 }
2687
John McCall06549462011-01-18 08:40:38 +00002688 case Type::ConstantArray: {
2689 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2690 result = getConstantArrayType(
2691 getVariableArrayDecayedType(cat->getElementType()),
2692 cat->getSize(),
2693 cat->getSizeModifier(),
2694 cat->getIndexTypeCVRQualifiers());
2695 break;
2696 }
2697
2698 case Type::DependentSizedArray: {
2699 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2700 result = getDependentSizedArrayType(
2701 getVariableArrayDecayedType(dat->getElementType()),
2702 dat->getSizeExpr(),
2703 dat->getSizeModifier(),
2704 dat->getIndexTypeCVRQualifiers(),
2705 dat->getBracketsRange());
2706 break;
2707 }
2708
2709 // Turn incomplete types into [*] types.
2710 case Type::IncompleteArray: {
2711 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2712 result = getVariableArrayType(
2713 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002714 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002715 ArrayType::Normal,
2716 iat->getIndexTypeCVRQualifiers(),
2717 SourceRange());
2718 break;
2719 }
2720
2721 // Turn VLA types into [*] types.
2722 case Type::VariableArray: {
2723 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2724 result = getVariableArrayType(
2725 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002726 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002727 ArrayType::Star,
2728 vat->getIndexTypeCVRQualifiers(),
2729 vat->getBracketsRange());
2730 break;
2731 }
2732 }
2733
2734 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002735 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002736}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002737
Steve Naroffcadebd02007-08-30 18:14:25 +00002738/// getVariableArrayType - Returns a non-unique reference to the type for a
2739/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002740QualType ASTContext::getVariableArrayType(QualType EltTy,
2741 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002742 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002743 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002744 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002745 // Since we don't unique expressions, it isn't possible to unique VLA's
2746 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002747 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002748
John McCall33ddac02011-01-19 10:06:00 +00002749 // Be sure to pull qualifiers off the element type.
2750 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2751 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002752 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002753 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002754 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002755 }
2756
John McCall90d1c2d2009-09-24 23:30:46 +00002757 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002758 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002759
2760 VariableArrayTypes.push_back(New);
2761 Types.push_back(New);
2762 return QualType(New, 0);
2763}
2764
Douglas Gregor4619e432008-12-05 23:32:09 +00002765/// getDependentSizedArrayType - Returns a non-unique reference to
2766/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002767/// type.
John McCall33ddac02011-01-19 10:06:00 +00002768QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2769 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002770 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002771 unsigned elementTypeQuals,
2772 SourceRange brackets) const {
2773 assert((!numElements || numElements->isTypeDependent() ||
2774 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002775 "Size must be type- or value-dependent!");
2776
John McCall33ddac02011-01-19 10:06:00 +00002777 // Dependently-sized array types that do not have a specified number
2778 // of elements will have their sizes deduced from a dependent
2779 // initializer. We do no canonicalization here at all, which is okay
2780 // because they can't be used in most locations.
2781 if (!numElements) {
2782 DependentSizedArrayType *newType
2783 = new (*this, TypeAlignment)
2784 DependentSizedArrayType(*this, elementType, QualType(),
2785 numElements, ASM, elementTypeQuals,
2786 brackets);
2787 Types.push_back(newType);
2788 return QualType(newType, 0);
2789 }
2790
2791 // Otherwise, we actually build a new type every time, but we
2792 // also build a canonical type.
2793
2794 SplitQualType canonElementType = getCanonicalType(elementType).split();
2795
Craig Topper36250ad2014-05-12 05:36:57 +00002796 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002797 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002798 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002799 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002800 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002801
John McCall33ddac02011-01-19 10:06:00 +00002802 // Look for an existing type with these properties.
2803 DependentSizedArrayType *canonTy =
2804 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002805
John McCall33ddac02011-01-19 10:06:00 +00002806 // If we don't have one, build one.
2807 if (!canonTy) {
2808 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002809 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002810 QualType(), numElements, ASM, elementTypeQuals,
2811 brackets);
2812 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2813 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002814 }
2815
John McCall33ddac02011-01-19 10:06:00 +00002816 // Apply qualifiers from the element type to the array.
2817 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002818 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002819
David Majnemer16a74702015-07-24 05:54:19 +00002820 // If we didn't need extra canonicalization for the element type or the size
2821 // expression, then just use that as our result.
2822 if (QualType(canonElementType.Ty, 0) == elementType &&
2823 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002824 return canon;
2825
2826 // Otherwise, we need to build a type which follows the spelling
2827 // of the element type.
2828 DependentSizedArrayType *sugaredType
2829 = new (*this, TypeAlignment)
2830 DependentSizedArrayType(*this, elementType, canon, numElements,
2831 ASM, elementTypeQuals, brackets);
2832 Types.push_back(sugaredType);
2833 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002834}
2835
John McCall33ddac02011-01-19 10:06:00 +00002836QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002837 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002838 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002839 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002840 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002841
Craig Topper36250ad2014-05-12 05:36:57 +00002842 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002843 if (IncompleteArrayType *iat =
2844 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2845 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002846
2847 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002848 // either, so fill in the canonical type field. We also have to pull
2849 // qualifiers off the element type.
2850 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002851
John McCall33ddac02011-01-19 10:06:00 +00002852 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2853 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002854 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002855 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002856 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002857
2858 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002859 IncompleteArrayType *existing =
2860 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2861 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002862 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002863
John McCall33ddac02011-01-19 10:06:00 +00002864 IncompleteArrayType *newType = new (*this, TypeAlignment)
2865 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002866
John McCall33ddac02011-01-19 10:06:00 +00002867 IncompleteArrayTypes.InsertNode(newType, insertPos);
2868 Types.push_back(newType);
2869 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002870}
2871
Steve Naroff91fcddb2007-07-18 18:00:27 +00002872/// getVectorType - Return the unique reference to a vector type of
2873/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002874QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002875 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002876 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002877
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002878 // Check if we've already instantiated a vector of this type.
2879 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002880 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002881
Craig Topper36250ad2014-05-12 05:36:57 +00002882 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002883 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2884 return QualType(VTP, 0);
2885
2886 // If the element type isn't canonical, this won't be a canonical type either,
2887 // so fill in the canonical type field.
2888 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002889 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002890 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002891
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002892 // Get the new insert position for the node we care about.
2893 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002894 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002895 }
John McCall90d1c2d2009-09-24 23:30:46 +00002896 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002897 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002898 VectorTypes.InsertNode(New, InsertPos);
2899 Types.push_back(New);
2900 return QualType(New, 0);
2901}
2902
Nate Begemance4d7fc2008-04-18 23:10:10 +00002903/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002904/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002905QualType
2906ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002907 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002908
Steve Naroff91fcddb2007-07-18 18:00:27 +00002909 // Check if we've already instantiated a vector of this type.
2910 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002911 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002912 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002913 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002914 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2915 return QualType(VTP, 0);
2916
2917 // If the element type isn't canonical, this won't be a canonical type either,
2918 // so fill in the canonical type field.
2919 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002920 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002921 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002922
Steve Naroff91fcddb2007-07-18 18:00:27 +00002923 // Get the new insert position for the node we care about.
2924 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002925 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002926 }
John McCall90d1c2d2009-09-24 23:30:46 +00002927 ExtVectorType *New = new (*this, TypeAlignment)
2928 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002929 VectorTypes.InsertNode(New, InsertPos);
2930 Types.push_back(New);
2931 return QualType(New, 0);
2932}
2933
Jay Foad39c79802011-01-12 09:06:06 +00002934QualType
2935ASTContext::getDependentSizedExtVectorType(QualType vecType,
2936 Expr *SizeExpr,
2937 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002938 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002939 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002940 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002941
Craig Topper36250ad2014-05-12 05:36:57 +00002942 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002943 DependentSizedExtVectorType *Canon
2944 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2945 DependentSizedExtVectorType *New;
2946 if (Canon) {
2947 // We already have a canonical version of this array type; use it as
2948 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002949 New = new (*this, TypeAlignment)
2950 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2951 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002952 } else {
2953 QualType CanonVecTy = getCanonicalType(vecType);
2954 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002955 New = new (*this, TypeAlignment)
2956 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2957 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002958
2959 DependentSizedExtVectorType *CanonCheck
2960 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2961 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2962 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002963 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2964 } else {
2965 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2966 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002967 New = new (*this, TypeAlignment)
2968 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002969 }
2970 }
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregor758a8692009-06-17 21:51:59 +00002972 Types.push_back(New);
2973 return QualType(New, 0);
2974}
2975
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002976/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002977///
Jay Foad39c79802011-01-12 09:06:06 +00002978QualType
2979ASTContext::getFunctionNoProtoType(QualType ResultTy,
2980 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002981 const CallingConv CallConv = Info.getCC();
2982
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002983 // Unique functions, to guarantee there is only one function of a particular
2984 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002985 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002986 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002987
Craig Topper36250ad2014-05-12 05:36:57 +00002988 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002989 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002990 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002991 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002992
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002993 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002994 if (!ResultTy.isCanonical()) {
2995 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002996
Chris Lattner47955de2007-01-27 08:37:20 +00002997 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002998 FunctionNoProtoType *NewIP =
2999 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003000 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003001 }
Mike Stump11289f42009-09-09 15:08:12 +00003002
Roman Divacky65b88cd2011-03-01 17:40:53 +00003003 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00003004 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00003005 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00003006 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003007 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003008 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003009}
3010
Douglas Gregorcd780372013-01-17 23:36:45 +00003011/// \brief Determine whether \p T is canonical as the result type of a function.
3012static bool isCanonicalResultType(QualType T) {
3013 return T.isCanonical() &&
3014 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3015 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3016}
3017
Douglas Gregora602a152015-10-01 20:20:47 +00003018CanQualType
3019ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3020 CanQualType CanResultType = getCanonicalType(ResultType);
3021
3022 // Canonical result types do not have ARC lifetime qualifiers.
3023 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3024 Qualifiers Qs = CanResultType.getQualifiers();
3025 Qs.removeObjCLifetime();
3026 return CanQualType::CreateUnsafe(
3027 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3028 }
3029
3030 return CanResultType;
3031}
3032
Jay Foad39c79802011-01-12 09:06:06 +00003033QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003034ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003035 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003036 size_t NumArgs = ArgArray.size();
3037
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003038 // Unique functions, to guarantee there is only one function of a particular
3039 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003040 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003041 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3042 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003043
Craig Topper36250ad2014-05-12 05:36:57 +00003044 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003045 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003046 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003047 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003048
3049 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003050 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003051 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003052 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003053 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003054 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003055 isCanonical = false;
3056
3057 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003058 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003059 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003060 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003061 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003062 CanonicalArgs.reserve(NumArgs);
3063 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003064 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003065
John McCalldb40c7f2010-12-14 08:05:40 +00003066 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003067 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003068 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003069
Douglas Gregora602a152015-10-01 20:20:47 +00003070 // Adjust the canonical function result type.
3071 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003072 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003073
Chris Lattnerfd4de792007-01-27 01:15:32 +00003074 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003075 FunctionProtoType *NewIP =
3076 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003077 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003078 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003079
John McCall31168b02011-06-15 23:02:42 +00003080 // FunctionProtoType objects are allocated with extra bytes after
3081 // them for three variable size arrays at the end:
3082 // - parameter types
3083 // - exception types
3084 // - consumed-arguments flags
3085 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003086 // expression, or information used to resolve the exception
3087 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003088 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003089 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003090 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3091 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3092 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003093 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003094 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003095 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003096 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003097 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003098 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003099 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003100 Size += NumArgs * sizeof(bool);
3101
John McCalldb40c7f2010-12-14 08:05:40 +00003102 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003103 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003104 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003105 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003106 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003107 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003108}
Chris Lattneref51c202006-11-10 07:17:23 +00003109
John McCalle78aac42010-03-10 03:28:59 +00003110#ifndef NDEBUG
3111static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3112 if (!isa<CXXRecordDecl>(D)) return false;
3113 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3114 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3115 return true;
3116 if (RD->getDescribedClassTemplate() &&
3117 !isa<ClassTemplateSpecializationDecl>(RD))
3118 return true;
3119 return false;
3120}
3121#endif
3122
3123/// getInjectedClassNameType - Return the unique reference to the
3124/// injected class name type for the specified templated declaration.
3125QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003126 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003127 assert(NeedsInjectedClassNameType(Decl));
3128 if (Decl->TypeForDecl) {
3129 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003130 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003131 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3132 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3133 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3134 } else {
John McCall424cec92011-01-19 06:33:43 +00003135 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003136 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003137 Decl->TypeForDecl = newType;
3138 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003139 }
3140 return QualType(Decl->TypeForDecl, 0);
3141}
3142
Douglas Gregor83a586e2008-04-13 21:07:44 +00003143/// getTypeDeclType - Return the unique reference to the type for the
3144/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003145QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003146 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003147 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003148
Richard Smithdda56e42011-04-15 14:24:37 +00003149 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003150 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003151
John McCall96f0b5f2010-03-10 06:48:02 +00003152 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3153 "Template type parameter types are always available.");
3154
John McCall81e38502010-02-16 03:57:14 +00003155 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003156 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003157 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003158 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003159 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003160 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003161 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003162 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003163 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003164 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3165 Decl->TypeForDecl = newType;
3166 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003167 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003168 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003169
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003170 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003171}
3172
Chris Lattner32d920b2007-01-26 02:01:53 +00003173/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003174/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003175QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003176ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3177 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003178 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003179
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003180 if (Canonical.isNull())
3181 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003182 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003183 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003184 Decl->TypeForDecl = newType;
3185 Types.push_back(newType);
3186 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003187}
3188
Jay Foad39c79802011-01-12 09:06:06 +00003189QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003190 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3191
Douglas Gregorec9fd132012-01-14 16:38:05 +00003192 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003193 if (PrevDecl->TypeForDecl)
3194 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3195
John McCall424cec92011-01-19 06:33:43 +00003196 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3197 Decl->TypeForDecl = newType;
3198 Types.push_back(newType);
3199 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003200}
3201
Jay Foad39c79802011-01-12 09:06:06 +00003202QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003203 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3204
Douglas Gregorec9fd132012-01-14 16:38:05 +00003205 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003206 if (PrevDecl->TypeForDecl)
3207 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3208
John McCall424cec92011-01-19 06:33:43 +00003209 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3210 Decl->TypeForDecl = newType;
3211 Types.push_back(newType);
3212 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003213}
3214
John McCall81904512011-01-06 01:58:22 +00003215QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3216 QualType modifiedType,
3217 QualType equivalentType) {
3218 llvm::FoldingSetNodeID id;
3219 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3220
Craig Topper36250ad2014-05-12 05:36:57 +00003221 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003222 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3223 if (type) return QualType(type, 0);
3224
3225 QualType canon = getCanonicalType(equivalentType);
3226 type = new (*this, TypeAlignment)
3227 AttributedType(canon, attrKind, modifiedType, equivalentType);
3228
3229 Types.push_back(type);
3230 AttributedTypes.InsertNode(type, insertPos);
3231
3232 return QualType(type, 0);
3233}
3234
John McCallcebee162009-10-18 09:09:24 +00003235/// \brief Retrieve a substitution-result type.
3236QualType
3237ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003238 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003239 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003240 && "replacement types must always be canonical");
3241
3242 llvm::FoldingSetNodeID ID;
3243 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003244 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003245 SubstTemplateTypeParmType *SubstParm
3246 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3247
3248 if (!SubstParm) {
3249 SubstParm = new (*this, TypeAlignment)
3250 SubstTemplateTypeParmType(Parm, Replacement);
3251 Types.push_back(SubstParm);
3252 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3253 }
3254
3255 return QualType(SubstParm, 0);
3256}
3257
Douglas Gregorada4b792011-01-14 02:55:32 +00003258/// \brief Retrieve a
3259QualType ASTContext::getSubstTemplateTypeParmPackType(
3260 const TemplateTypeParmType *Parm,
3261 const TemplateArgument &ArgPack) {
3262#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003263 for (const auto &P : ArgPack.pack_elements()) {
3264 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3265 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003266 }
3267#endif
3268
3269 llvm::FoldingSetNodeID ID;
3270 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003271 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003272 if (SubstTemplateTypeParmPackType *SubstParm
3273 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3274 return QualType(SubstParm, 0);
3275
3276 QualType Canon;
3277 if (!Parm->isCanonicalUnqualified()) {
3278 Canon = getCanonicalType(QualType(Parm, 0));
3279 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3280 ArgPack);
3281 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3282 }
3283
3284 SubstTemplateTypeParmPackType *SubstParm
3285 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3286 ArgPack);
3287 Types.push_back(SubstParm);
3288 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3289 return QualType(SubstParm, 0);
3290}
3291
Douglas Gregoreff93e02009-02-05 23:33:38 +00003292/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003293/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003294/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003295QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003296 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003297 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003298 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003299 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003300 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003301 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003302 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3303
3304 if (TypeParm)
3305 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003306
Chandler Carruth08836322011-05-01 00:51:33 +00003307 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003308 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003309 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003310
3311 TemplateTypeParmType *TypeCheck
3312 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3313 assert(!TypeCheck && "Template type parameter canonical type broken");
3314 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003315 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003316 TypeParm = new (*this, TypeAlignment)
3317 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003318
3319 Types.push_back(TypeParm);
3320 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3321
3322 return QualType(TypeParm, 0);
3323}
3324
John McCalle78aac42010-03-10 03:28:59 +00003325TypeSourceInfo *
3326ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3327 SourceLocation NameLoc,
3328 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003329 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003330 assert(!Name.getAsDependentTemplateName() &&
3331 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003332 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003333
3334 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003335 TemplateSpecializationTypeLoc TL =
3336 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003337 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003338 TL.setTemplateNameLoc(NameLoc);
3339 TL.setLAngleLoc(Args.getLAngleLoc());
3340 TL.setRAngleLoc(Args.getRAngleLoc());
3341 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3342 TL.setArgLocInfo(i, Args[i].getLocInfo());
3343 return DI;
3344}
3345
Mike Stump11289f42009-09-09 15:08:12 +00003346QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003347ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003348 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003349 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003350 assert(!Template.getAsDependentTemplateName() &&
3351 "No dependent template names here!");
3352
John McCall6b51f282009-11-23 01:53:49 +00003353 unsigned NumArgs = Args.size();
3354
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003355 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003356 ArgVec.reserve(NumArgs);
3357 for (unsigned i = 0; i != NumArgs; ++i)
3358 ArgVec.push_back(Args[i].getArgument());
3359
John McCall2408e322010-04-27 00:57:59 +00003360 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003361 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003362}
3363
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003364#ifndef NDEBUG
3365static bool hasAnyPackExpansions(const TemplateArgument *Args,
3366 unsigned NumArgs) {
3367 for (unsigned I = 0; I != NumArgs; ++I)
3368 if (Args[I].isPackExpansion())
3369 return true;
3370
3371 return true;
3372}
3373#endif
3374
John McCall0ad16662009-10-29 08:12:44 +00003375QualType
3376ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003377 const TemplateArgument *Args,
3378 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003379 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003380 assert(!Template.getAsDependentTemplateName() &&
3381 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003382 // Look through qualified template names.
3383 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3384 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003385
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003386 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003387 Template.getAsTemplateDecl() &&
3388 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003389 QualType CanonType;
3390 if (!Underlying.isNull())
3391 CanonType = getCanonicalType(Underlying);
3392 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003393 // We can get here with an alias template when the specialization contains
3394 // a pack expansion that does not match up with a parameter pack.
3395 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3396 "Caller must compute aliased type");
3397 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003398 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3399 NumArgs);
3400 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003401
Douglas Gregora8e02e72009-07-28 23:00:59 +00003402 // Allocate the (non-canonical) template specialization type, but don't
3403 // try to unique it: these types typically have location information that
3404 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003405 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3406 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003407 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003408 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003409 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003410 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3411 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003412
Douglas Gregor8bf42052009-02-09 18:46:07 +00003413 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003414 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003415}
3416
Mike Stump11289f42009-09-09 15:08:12 +00003417QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003418ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3419 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003420 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003421 assert(!Template.getAsDependentTemplateName() &&
3422 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003423
Douglas Gregore29139c2011-03-03 17:04:51 +00003424 // Look through qualified template names.
3425 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3426 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003427
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003428 // Build the canonical template specialization type.
3429 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003430 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003431 CanonArgs.reserve(NumArgs);
3432 for (unsigned I = 0; I != NumArgs; ++I)
3433 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3434
3435 // Determine whether this canonical template specialization type already
3436 // exists.
3437 llvm::FoldingSetNodeID ID;
3438 TemplateSpecializationType::Profile(ID, CanonTemplate,
3439 CanonArgs.data(), NumArgs, *this);
3440
Craig Topper36250ad2014-05-12 05:36:57 +00003441 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003442 TemplateSpecializationType *Spec
3443 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3444
3445 if (!Spec) {
3446 // Allocate a new canonical template specialization type.
3447 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3448 sizeof(TemplateArgument) * NumArgs),
3449 TypeAlignment);
3450 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3451 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003452 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003453 Types.push_back(Spec);
3454 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3455 }
3456
3457 assert(Spec->isDependentType() &&
3458 "Non-dependent template-id type must have a canonical type");
3459 return QualType(Spec, 0);
3460}
3461
3462QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003463ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3464 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003465 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003466 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003467 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003468
Craig Topper36250ad2014-05-12 05:36:57 +00003469 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003470 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003471 if (T)
3472 return QualType(T, 0);
3473
Douglas Gregorc42075a2010-02-04 18:10:26 +00003474 QualType Canon = NamedType;
3475 if (!Canon.isCanonical()) {
3476 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003477 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3478 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003479 (void)CheckT;
3480 }
3481
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003482 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003483 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003484 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003485 return QualType(T, 0);
3486}
3487
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003488QualType
Jay Foad39c79802011-01-12 09:06:06 +00003489ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003490 llvm::FoldingSetNodeID ID;
3491 ParenType::Profile(ID, InnerType);
3492
Craig Topper36250ad2014-05-12 05:36:57 +00003493 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003494 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3495 if (T)
3496 return QualType(T, 0);
3497
3498 QualType Canon = InnerType;
3499 if (!Canon.isCanonical()) {
3500 Canon = getCanonicalType(InnerType);
3501 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3502 assert(!CheckT && "Paren canonical type broken");
3503 (void)CheckT;
3504 }
3505
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003506 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003507 Types.push_back(T);
3508 ParenTypes.InsertNode(T, InsertPos);
3509 return QualType(T, 0);
3510}
3511
Douglas Gregor02085352010-03-31 20:19:30 +00003512QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3513 NestedNameSpecifier *NNS,
3514 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003515 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003516 if (Canon.isNull()) {
3517 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003518 ElaboratedTypeKeyword CanonKeyword = Keyword;
3519 if (Keyword == ETK_None)
3520 CanonKeyword = ETK_Typename;
3521
3522 if (CanonNNS != NNS || CanonKeyword != Keyword)
3523 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003524 }
3525
3526 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003527 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003528
Craig Topper36250ad2014-05-12 05:36:57 +00003529 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003530 DependentNameType *T
3531 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003532 if (T)
3533 return QualType(T, 0);
3534
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003535 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003536 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003537 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003538 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003539}
3540
Mike Stump11289f42009-09-09 15:08:12 +00003541QualType
John McCallc392f372010-06-11 00:33:02 +00003542ASTContext::getDependentTemplateSpecializationType(
3543 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003544 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003545 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003546 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003547 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003548 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003549 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3550 ArgCopy.push_back(Args[I].getArgument());
3551 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3552 ArgCopy.size(),
3553 ArgCopy.data());
3554}
3555
3556QualType
3557ASTContext::getDependentTemplateSpecializationType(
3558 ElaboratedTypeKeyword Keyword,
3559 NestedNameSpecifier *NNS,
3560 const IdentifierInfo *Name,
3561 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003562 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003563 assert((!NNS || NNS->isDependent()) &&
3564 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003565
Douglas Gregorc42075a2010-02-04 18:10:26 +00003566 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003567 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3568 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003569
Craig Topper36250ad2014-05-12 05:36:57 +00003570 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003571 DependentTemplateSpecializationType *T
3572 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003573 if (T)
3574 return QualType(T, 0);
3575
John McCallc392f372010-06-11 00:33:02 +00003576 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003577
John McCallc392f372010-06-11 00:33:02 +00003578 ElaboratedTypeKeyword CanonKeyword = Keyword;
3579 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3580
3581 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003582 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003583 for (unsigned I = 0; I != NumArgs; ++I) {
3584 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3585 if (!CanonArgs[I].structurallyEquals(Args[I]))
3586 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003587 }
3588
John McCallc392f372010-06-11 00:33:02 +00003589 QualType Canon;
3590 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3591 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3592 Name, NumArgs,
3593 CanonArgs.data());
3594
3595 // Find the insert position again.
3596 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3597 }
3598
3599 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3600 sizeof(TemplateArgument) * NumArgs),
3601 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003602 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003603 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003604 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003605 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003606 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003607}
3608
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003609QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003610 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003611 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003612 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003613
3614 assert(Pattern->containsUnexpandedParameterPack() &&
3615 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003616 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003617 PackExpansionType *T
3618 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3619 if (T)
3620 return QualType(T, 0);
3621
3622 QualType Canon;
3623 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003624 Canon = getCanonicalType(Pattern);
3625 // The canonical type might not contain an unexpanded parameter pack, if it
3626 // contains an alias template specialization which ignores one of its
3627 // parameters.
3628 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003629 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003630
Richard Smith68eea502012-07-16 00:20:35 +00003631 // Find the insert position again, in case we inserted an element into
3632 // PackExpansionTypes and invalidated our insert position.
3633 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3634 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003635 }
3636
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003637 T = new (*this, TypeAlignment)
3638 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003639 Types.push_back(T);
3640 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003641 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003642}
3643
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003644/// CmpProtocolNames - Comparison predicate for sorting protocols
3645/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003646static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3647 ObjCProtocolDecl *const *RHS) {
3648 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003649}
3650
John McCall8b07ec22010-05-15 11:32:37 +00003651static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003652 unsigned NumProtocols) {
3653 if (NumProtocols == 0) return true;
3654
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003655 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3656 return false;
3657
John McCallfc93cf92009-10-22 22:37:11 +00003658 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003659 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003660 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003661 return false;
3662 return true;
3663}
3664
Craig Topper6a8c1512015-10-22 01:56:18 +00003665static void
3666SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003667 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003668 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003669
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003670 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003671 for (ObjCProtocolDecl *&P : Protocols)
3672 P = P->getCanonicalDecl();
3673
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003674 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003675 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3676 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003677}
3678
John McCall8b07ec22010-05-15 11:32:37 +00003679QualType ASTContext::getObjCObjectType(QualType BaseType,
3680 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003681 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003682 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003683 llvm::makeArrayRef(Protocols, NumProtocols),
3684 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003685}
3686
3687QualType ASTContext::getObjCObjectType(
3688 QualType baseType,
3689 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003690 ArrayRef<ObjCProtocolDecl *> protocols,
3691 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003692 // If the base type is an interface and there aren't any protocols or
3693 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003694 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3695 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003696 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003697
3698 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003699 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003700 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003701 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003702 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3703 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003704
Douglas Gregore9d95f12015-07-07 03:57:35 +00003705 // Determine the type arguments to be used for canonicalization,
3706 // which may be explicitly specified here or written on the base
3707 // type.
3708 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3709 if (effectiveTypeArgs.empty()) {
3710 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3711 effectiveTypeArgs = baseObject->getTypeArgs();
3712 }
John McCallfc93cf92009-10-22 22:37:11 +00003713
Douglas Gregore9d95f12015-07-07 03:57:35 +00003714 // Build the canonical type, which has the canonical base type and a
3715 // sorted-and-uniqued list of protocols and the type arguments
3716 // canonicalized.
3717 QualType canonical;
3718 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3719 effectiveTypeArgs.end(),
3720 [&](QualType type) {
3721 return type.isCanonical();
3722 });
3723 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3724 protocols.size());
3725 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3726 // Determine the canonical type arguments.
3727 ArrayRef<QualType> canonTypeArgs;
3728 SmallVector<QualType, 4> canonTypeArgsVec;
3729 if (!typeArgsAreCanonical) {
3730 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3731 for (auto typeArg : effectiveTypeArgs)
3732 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3733 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003734 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003735 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003736 }
3737
Douglas Gregore9d95f12015-07-07 03:57:35 +00003738 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3739 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3740 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003741 canonProtocolsVec.append(protocols.begin(), protocols.end());
3742 SortAndUniqueProtocols(canonProtocolsVec);
3743 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003744 } else {
3745 canonProtocols = protocols;
3746 }
3747
3748 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003749 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003750
John McCallfc93cf92009-10-22 22:37:11 +00003751 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003752 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3753 }
3754
Douglas Gregore9d95f12015-07-07 03:57:35 +00003755 unsigned size = sizeof(ObjCObjectTypeImpl);
3756 size += typeArgs.size() * sizeof(QualType);
3757 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3758 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003759 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003760 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3761 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003762
3763 Types.push_back(T);
3764 ObjCObjectTypes.InsertNode(T, InsertPos);
3765 return QualType(T, 0);
3766}
3767
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003768/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3769/// protocol list adopt all protocols in QT's qualified-id protocol
3770/// list.
3771bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3772 ObjCInterfaceDecl *IC) {
3773 if (!QT->isObjCQualifiedIdType())
3774 return false;
3775
3776 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3777 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003778 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003779 if (!IC->ClassImplementsProtocol(Proto, false))
3780 return false;
3781 }
3782 return true;
3783 }
3784 return false;
3785}
3786
3787/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3788/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3789/// of protocols.
3790bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3791 ObjCInterfaceDecl *IDecl) {
3792 if (!QT->isObjCQualifiedIdType())
3793 return false;
3794 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3795 if (!OPT)
3796 return false;
3797 if (!IDecl->hasDefinition())
3798 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003799 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3800 CollectInheritedProtocols(IDecl, InheritedProtocols);
3801 if (InheritedProtocols.empty())
3802 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003803 // Check that if every protocol in list of id<plist> conforms to a protcol
3804 // of IDecl's, then bridge casting is ok.
3805 bool Conforms = false;
3806 for (auto *Proto : OPT->quals()) {
3807 Conforms = false;
3808 for (auto *PI : InheritedProtocols) {
3809 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3810 Conforms = true;
3811 break;
3812 }
3813 }
3814 if (!Conforms)
3815 break;
3816 }
3817 if (Conforms)
3818 return true;
3819
Aaron Ballman83731462014-03-17 16:14:00 +00003820 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003821 // If both the right and left sides have qualifiers.
3822 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003823 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003824 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003825 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003826 break;
3827 }
3828 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003829 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003830 }
3831 return true;
3832}
3833
John McCall8b07ec22010-05-15 11:32:37 +00003834/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3835/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003836QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003837 llvm::FoldingSetNodeID ID;
3838 ObjCObjectPointerType::Profile(ID, ObjectT);
3839
Craig Topper36250ad2014-05-12 05:36:57 +00003840 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003841 if (ObjCObjectPointerType *QT =
3842 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3843 return QualType(QT, 0);
3844
3845 // Find the canonical object type.
3846 QualType Canonical;
3847 if (!ObjectT.isCanonical()) {
3848 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3849
3850 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003851 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3852 }
3853
Douglas Gregorf85bee62010-02-08 22:59:26 +00003854 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003855 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3856 ObjCObjectPointerType *QType =
3857 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003858
Steve Narofffb4330f2009-06-17 22:40:22 +00003859 Types.push_back(QType);
3860 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003861 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003862}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003863
Douglas Gregor1c283312010-08-11 12:19:30 +00003864/// getObjCInterfaceType - Return the unique reference to the type for the
3865/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003866QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3867 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003868 if (Decl->TypeForDecl)
3869 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003870
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003871 if (PrevDecl) {
3872 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3873 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3874 return QualType(PrevDecl->TypeForDecl, 0);
3875 }
3876
Douglas Gregor7671e532011-12-16 16:34:57 +00003877 // Prefer the definition, if there is one.
3878 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3879 Decl = Def;
3880
Douglas Gregor1c283312010-08-11 12:19:30 +00003881 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3882 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3883 Decl->TypeForDecl = T;
3884 Types.push_back(T);
3885 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003886}
3887
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003888/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3889/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003890/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003891/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003892/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003893QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003894 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003895 if (tofExpr->isTypeDependent()) {
3896 llvm::FoldingSetNodeID ID;
3897 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003898
Craig Topper36250ad2014-05-12 05:36:57 +00003899 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003900 DependentTypeOfExprType *Canon
3901 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3902 if (Canon) {
3903 // We already have a "canonical" version of an identical, dependent
3904 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003905 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003906 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003907 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003908 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003909 Canon
3910 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003911 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3912 toe = Canon;
3913 }
3914 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003915 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003916 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003917 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003918 Types.push_back(toe);
3919 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003920}
3921
Steve Naroffa773cd52007-08-01 18:02:17 +00003922/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003923/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003924/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003925/// an issue. This doesn't affect the type checker, since it operates
3926/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003927QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003928 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003929 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003930 Types.push_back(tot);
3931 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003932}
3933
Richard Smith8eb1d322014-06-05 20:13:13 +00003934/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3935/// nodes. This would never be helpful, since each such type has its own
3936/// expression, and would not give a significant memory saving, since there
3937/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003938QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003939 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003940
3941 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003942 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003943 // unique dependent type. Two such decltype-specifiers refer to the same
3944 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003945 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003946 llvm::FoldingSetNodeID ID;
3947 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003948
Craig Topper36250ad2014-05-12 05:36:57 +00003949 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003950 DependentDecltypeType *Canon
3951 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003952 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003953 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003954 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003955 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003956 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003957 dt = new (*this, TypeAlignment)
3958 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003959 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003960 dt = new (*this, TypeAlignment)
3961 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003962 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003963 Types.push_back(dt);
3964 return QualType(dt, 0);
3965}
3966
Alexis Hunte852b102011-05-24 22:41:36 +00003967/// getUnaryTransformationType - We don't unique these, since the memory
3968/// savings are minimal and these are rare.
3969QualType ASTContext::getUnaryTransformType(QualType BaseType,
3970 QualType UnderlyingType,
3971 UnaryTransformType::UTTKind Kind)
3972 const {
3973 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003974 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3975 Kind,
3976 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003977 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003978 Types.push_back(Ty);
3979 return QualType(Ty, 0);
3980}
3981
Richard Smith2a7d4812013-05-04 07:00:32 +00003982/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3983/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3984/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00003985QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003986 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00003987 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003988 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003989
Richard Smith2a7d4812013-05-04 07:00:32 +00003990 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003991 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003992 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00003993 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003994 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3995 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003996
Richard Smith74aeef52013-04-26 16:15:35 +00003997 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00003998 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003999 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004000 Types.push_back(AT);
4001 if (InsertPos)
4002 AutoTypes.InsertNode(AT, InsertPos);
4003 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004004}
4005
Eli Friedman0dfb8892011-10-06 23:00:33 +00004006/// getAtomicType - Return the uniqued reference to the atomic type for
4007/// the given value type.
4008QualType ASTContext::getAtomicType(QualType T) const {
4009 // Unique pointers, to guarantee there is only one pointer of a particular
4010 // structure.
4011 llvm::FoldingSetNodeID ID;
4012 AtomicType::Profile(ID, T);
4013
Craig Topper36250ad2014-05-12 05:36:57 +00004014 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004015 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4016 return QualType(AT, 0);
4017
4018 // If the atomic value type isn't canonical, this won't be a canonical type
4019 // either, so fill in the canonical type field.
4020 QualType Canonical;
4021 if (!T.isCanonical()) {
4022 Canonical = getAtomicType(getCanonicalType(T));
4023
4024 // Get the new insert position for the node we care about.
4025 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004026 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004027 }
4028 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4029 Types.push_back(New);
4030 AtomicTypes.InsertNode(New, InsertPos);
4031 return QualType(New, 0);
4032}
4033
Richard Smith02e85f32011-04-14 22:09:26 +00004034/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4035QualType ASTContext::getAutoDeductType() const {
4036 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004037 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004038 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004039 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004040 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004041 return AutoDeductTy;
4042}
4043
4044/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4045QualType ASTContext::getAutoRRefDeductType() const {
4046 if (AutoRRefDeductTy.isNull())
4047 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4048 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4049 return AutoRRefDeductTy;
4050}
4051
Chris Lattnerfb072462007-01-23 05:45:31 +00004052/// getTagDeclType - Return the unique reference to the type for the
4053/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004054QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004055 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004056 // FIXME: What is the design on getTagDeclType when it requires casting
4057 // away const? mutable?
4058 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004059}
4060
Mike Stump11289f42009-09-09 15:08:12 +00004061/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4062/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4063/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004064CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004065 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004066}
Chris Lattnerfb072462007-01-23 05:45:31 +00004067
Hans Wennborg27541db2011-10-27 08:29:09 +00004068/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4069CanQualType ASTContext::getIntMaxType() const {
4070 return getFromTargetType(Target->getIntMaxType());
4071}
4072
4073/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4074CanQualType ASTContext::getUIntMaxType() const {
4075 return getFromTargetType(Target->getUIntMaxType());
4076}
4077
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004078/// getSignedWCharType - Return the type of "signed wchar_t".
4079/// Used when in C++, as a GCC extension.
4080QualType ASTContext::getSignedWCharType() const {
4081 // FIXME: derive from "Target" ?
4082 return WCharTy;
4083}
4084
4085/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4086/// Used when in C++, as a GCC extension.
4087QualType ASTContext::getUnsignedWCharType() const {
4088 // FIXME: derive from "Target" ?
4089 return UnsignedIntTy;
4090}
4091
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004092QualType ASTContext::getIntPtrType() const {
4093 return getFromTargetType(Target->getIntPtrType());
4094}
4095
4096QualType ASTContext::getUIntPtrType() const {
4097 return getCorrespondingUnsignedType(getIntPtrType());
4098}
4099
Hans Wennborg27541db2011-10-27 08:29:09 +00004100/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004101/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4102QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004103 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004104}
4105
Eli Friedman4e91899e2012-11-27 02:58:24 +00004106/// \brief Return the unique type for "pid_t" defined in
4107/// <sys/types.h>. We need this to compute the correct type for vfork().
4108QualType ASTContext::getProcessIDType() const {
4109 return getFromTargetType(Target->getProcessIDType());
4110}
4111
Chris Lattnera21ad802008-04-02 05:18:44 +00004112//===----------------------------------------------------------------------===//
4113// Type Operators
4114//===----------------------------------------------------------------------===//
4115
Jay Foad39c79802011-01-12 09:06:06 +00004116CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004117 // Push qualifiers into arrays, and then discard any remaining
4118 // qualifiers.
4119 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004120 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004121 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004122 QualType Result;
4123 if (isa<ArrayType>(Ty)) {
4124 Result = getArrayDecayedType(QualType(Ty,0));
4125 } else if (isa<FunctionType>(Ty)) {
4126 Result = getPointerType(QualType(Ty, 0));
4127 } else {
4128 Result = QualType(Ty, 0);
4129 }
4130
4131 return CanQualType::CreateUnsafe(Result);
4132}
4133
John McCall6c9dd522011-01-18 07:41:22 +00004134QualType ASTContext::getUnqualifiedArrayType(QualType type,
4135 Qualifiers &quals) {
4136 SplitQualType splitType = type.getSplitUnqualifiedType();
4137
4138 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4139 // the unqualified desugared type and then drops it on the floor.
4140 // We then have to strip that sugar back off with
4141 // getUnqualifiedDesugaredType(), which is silly.
4142 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004143 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004144
4145 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004146 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004147 quals = splitType.Quals;
4148 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004149 }
4150
John McCall6c9dd522011-01-18 07:41:22 +00004151 // Otherwise, recurse on the array's element type.
4152 QualType elementType = AT->getElementType();
4153 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4154
4155 // If that didn't change the element type, AT has no qualifiers, so we
4156 // can just use the results in splitType.
4157 if (elementType == unqualElementType) {
4158 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004159 quals = splitType.Quals;
4160 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004161 }
4162
4163 // Otherwise, add in the qualifiers from the outermost type, then
4164 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004165 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004166
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004167 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004168 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004169 CAT->getSizeModifier(), 0);
4170 }
4171
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004172 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004173 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004174 }
4175
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004176 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004177 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004178 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004179 VAT->getSizeModifier(),
4180 VAT->getIndexTypeCVRQualifiers(),
4181 VAT->getBracketsRange());
4182 }
4183
4184 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004185 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004186 DSAT->getSizeModifier(), 0,
4187 SourceRange());
4188}
4189
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004190/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4191/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4192/// they point to and return true. If T1 and T2 aren't pointer types
4193/// or pointer-to-member types, or if they are not similar at this
4194/// level, returns false and leaves T1 and T2 unchanged. Top-level
4195/// qualifiers on T1 and T2 are ignored. This function will typically
4196/// be called in a loop that successively "unwraps" pointer and
4197/// pointer-to-member types to compare them at each level.
4198bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4199 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4200 *T2PtrType = T2->getAs<PointerType>();
4201 if (T1PtrType && T2PtrType) {
4202 T1 = T1PtrType->getPointeeType();
4203 T2 = T2PtrType->getPointeeType();
4204 return true;
4205 }
4206
4207 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4208 *T2MPType = T2->getAs<MemberPointerType>();
4209 if (T1MPType && T2MPType &&
4210 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4211 QualType(T2MPType->getClass(), 0))) {
4212 T1 = T1MPType->getPointeeType();
4213 T2 = T2MPType->getPointeeType();
4214 return true;
4215 }
4216
David Blaikiebbafb8a2012-03-11 07:00:24 +00004217 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004218 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4219 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4220 if (T1OPType && T2OPType) {
4221 T1 = T1OPType->getPointeeType();
4222 T2 = T2OPType->getPointeeType();
4223 return true;
4224 }
4225 }
4226
4227 // FIXME: Block pointers, too?
4228
4229 return false;
4230}
4231
Jay Foad39c79802011-01-12 09:06:06 +00004232DeclarationNameInfo
4233ASTContext::getNameForTemplate(TemplateName Name,
4234 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004235 switch (Name.getKind()) {
4236 case TemplateName::QualifiedTemplate:
4237 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004238 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004239 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4240 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004241
John McCalld9dfe3a2011-06-30 08:33:18 +00004242 case TemplateName::OverloadedTemplate: {
4243 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4244 // DNInfo work in progress: CHECKME: what about DNLoc?
4245 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4246 }
4247
4248 case TemplateName::DependentTemplate: {
4249 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004250 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004251 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004252 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4253 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004254 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004255 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4256 // DNInfo work in progress: FIXME: source locations?
4257 DeclarationNameLoc DNLoc;
4258 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4259 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4260 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004261 }
4262 }
4263
John McCalld9dfe3a2011-06-30 08:33:18 +00004264 case TemplateName::SubstTemplateTemplateParm: {
4265 SubstTemplateTemplateParmStorage *subst
4266 = Name.getAsSubstTemplateTemplateParm();
4267 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4268 NameLoc);
4269 }
4270
4271 case TemplateName::SubstTemplateTemplateParmPack: {
4272 SubstTemplateTemplateParmPackStorage *subst
4273 = Name.getAsSubstTemplateTemplateParmPack();
4274 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4275 NameLoc);
4276 }
4277 }
4278
4279 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004280}
4281
Jay Foad39c79802011-01-12 09:06:06 +00004282TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004283 switch (Name.getKind()) {
4284 case TemplateName::QualifiedTemplate:
4285 case TemplateName::Template: {
4286 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004287 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004288 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004289 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4290
4291 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004292 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004293 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004294
John McCalld9dfe3a2011-06-30 08:33:18 +00004295 case TemplateName::OverloadedTemplate:
4296 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004297
John McCalld9dfe3a2011-06-30 08:33:18 +00004298 case TemplateName::DependentTemplate: {
4299 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4300 assert(DTN && "Non-dependent template names must refer to template decls.");
4301 return DTN->CanonicalTemplateName;
4302 }
4303
4304 case TemplateName::SubstTemplateTemplateParm: {
4305 SubstTemplateTemplateParmStorage *subst
4306 = Name.getAsSubstTemplateTemplateParm();
4307 return getCanonicalTemplateName(subst->getReplacement());
4308 }
4309
4310 case TemplateName::SubstTemplateTemplateParmPack: {
4311 SubstTemplateTemplateParmPackStorage *subst
4312 = Name.getAsSubstTemplateTemplateParmPack();
4313 TemplateTemplateParmDecl *canonParameter
4314 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4315 TemplateArgument canonArgPack
4316 = getCanonicalTemplateArgument(subst->getArgumentPack());
4317 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4318 }
4319 }
4320
4321 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004322}
4323
Douglas Gregoradee3e32009-11-11 23:06:43 +00004324bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4325 X = getCanonicalTemplateName(X);
4326 Y = getCanonicalTemplateName(Y);
4327 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4328}
4329
Mike Stump11289f42009-09-09 15:08:12 +00004330TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004331ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004332 switch (Arg.getKind()) {
4333 case TemplateArgument::Null:
4334 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004335
Douglas Gregora8e02e72009-07-28 23:00:59 +00004336 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004337 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004338
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004339 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004340 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004341 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004342 }
Mike Stump11289f42009-09-09 15:08:12 +00004343
Eli Friedmanb826a002012-09-26 02:36:12 +00004344 case TemplateArgument::NullPtr:
4345 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4346 /*isNullPtr*/true);
4347
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004348 case TemplateArgument::Template:
4349 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004350
4351 case TemplateArgument::TemplateExpansion:
4352 return TemplateArgument(getCanonicalTemplateName(
4353 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004354 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004355
Douglas Gregora8e02e72009-07-28 23:00:59 +00004356 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004357 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004358
Douglas Gregora8e02e72009-07-28 23:00:59 +00004359 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004360 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004361
Douglas Gregora8e02e72009-07-28 23:00:59 +00004362 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004363 if (Arg.pack_size() == 0)
4364 return Arg;
4365
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004366 TemplateArgument *CanonArgs
4367 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004368 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004369 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004370 AEnd = Arg.pack_end();
4371 A != AEnd; (void)++A, ++Idx)
4372 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004373
Benjamin Kramercce63472015-08-05 09:40:22 +00004374 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004375 }
4376 }
4377
4378 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004379 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004380}
4381
Douglas Gregor333489b2009-03-27 23:10:48 +00004382NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004383ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004384 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004385 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004386
4387 switch (NNS->getKind()) {
4388 case NestedNameSpecifier::Identifier:
4389 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004390 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004391 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4392 NNS->getAsIdentifier());
4393
4394 case NestedNameSpecifier::Namespace:
4395 // A namespace is canonical; build a nested-name-specifier with
4396 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004397 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004398 NNS->getAsNamespace()->getOriginalNamespace());
4399
4400 case NestedNameSpecifier::NamespaceAlias:
4401 // A namespace is canonical; build a nested-name-specifier with
4402 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004403 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004404 NNS->getAsNamespaceAlias()->getNamespace()
4405 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004406
4407 case NestedNameSpecifier::TypeSpec:
4408 case NestedNameSpecifier::TypeSpecWithTemplate: {
4409 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004410
4411 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4412 // break it apart into its prefix and identifier, then reconsititute those
4413 // as the canonical nested-name-specifier. This is required to canonicalize
4414 // a dependent nested-name-specifier involving typedefs of dependent-name
4415 // types, e.g.,
4416 // typedef typename T::type T1;
4417 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004418 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4419 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004420 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004421
Eli Friedman5358a0a2012-03-03 04:09:56 +00004422 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4423 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4424 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004425 return NestedNameSpecifier::Create(*this, nullptr, false,
4426 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004427 }
4428
4429 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004430 case NestedNameSpecifier::Super:
4431 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004432 return NNS;
4433 }
4434
David Blaikie8a40f702012-01-17 06:56:22 +00004435 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004436}
4437
Jay Foad39c79802011-01-12 09:06:06 +00004438const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004439 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004440 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004441 // Handle the common positive case fast.
4442 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4443 return AT;
4444 }
Mike Stump11289f42009-09-09 15:08:12 +00004445
John McCall8ccfcb52009-09-24 19:53:00 +00004446 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004447 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004448 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004449
John McCall8ccfcb52009-09-24 19:53:00 +00004450 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004451 // implements C99 6.7.3p8: "If the specification of an array type includes
4452 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004453
Chris Lattner7adf0762008-08-04 07:31:14 +00004454 // If we get here, we either have type qualifiers on the type, or we have
4455 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004456 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004457
John McCall33ddac02011-01-19 10:06:00 +00004458 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004459 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004460
Chris Lattner7adf0762008-08-04 07:31:14 +00004461 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004462 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004463 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004464 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004465
Chris Lattner7adf0762008-08-04 07:31:14 +00004466 // Otherwise, we have an array and we have qualifiers on it. Push the
4467 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004468 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004469
Chris Lattner7adf0762008-08-04 07:31:14 +00004470 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4471 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4472 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004473 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004474 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4475 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4476 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004477 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004478
Mike Stump11289f42009-09-09 15:08:12 +00004479 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004480 = dyn_cast<DependentSizedArrayType>(ATy))
4481 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004482 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004483 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004484 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004485 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004486 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004487
Chris Lattner7adf0762008-08-04 07:31:14 +00004488 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004489 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004490 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004491 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004492 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004493 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004494}
4495
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004496QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004497 if (T->isArrayType() || T->isFunctionType())
4498 return getDecayedType(T);
4499 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004500}
4501
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004502QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004503 T = getVariableArrayDecayedType(T);
4504 T = getAdjustedParameterType(T);
4505 return T.getUnqualifiedType();
4506}
4507
David Majnemerd09a51c2015-03-03 01:50:05 +00004508QualType ASTContext::getExceptionObjectType(QualType T) const {
4509 // C++ [except.throw]p3:
4510 // A throw-expression initializes a temporary object, called the exception
4511 // object, the type of which is determined by removing any top-level
4512 // cv-qualifiers from the static type of the operand of throw and adjusting
4513 // the type from "array of T" or "function returning T" to "pointer to T"
4514 // or "pointer to function returning T", [...]
4515 T = getVariableArrayDecayedType(T);
4516 if (T->isArrayType() || T->isFunctionType())
4517 T = getDecayedType(T);
4518 return T.getUnqualifiedType();
4519}
4520
Chris Lattnera21ad802008-04-02 05:18:44 +00004521/// getArrayDecayedType - Return the properly qualified result of decaying the
4522/// specified array type to a pointer. This operation is non-trivial when
4523/// handling typedefs etc. The canonical type of "T" must be an array type,
4524/// this returns a pointer to a properly qualified element of the array.
4525///
4526/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004527QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004528 // Get the element type with 'getAsArrayType' so that we don't lose any
4529 // typedefs in the element type of the array. This also handles propagation
4530 // of type qualifiers from the array type into the element type if present
4531 // (C99 6.7.3p8).
4532 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4533 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004534
Chris Lattner7adf0762008-08-04 07:31:14 +00004535 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004536
4537 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004538 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004539}
4540
John McCall33ddac02011-01-19 10:06:00 +00004541QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4542 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004543}
4544
John McCall33ddac02011-01-19 10:06:00 +00004545QualType ASTContext::getBaseElementType(QualType type) const {
4546 Qualifiers qs;
4547 while (true) {
4548 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004549 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004550 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004551
John McCall33ddac02011-01-19 10:06:00 +00004552 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004553 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004554 }
Mike Stump11289f42009-09-09 15:08:12 +00004555
John McCall33ddac02011-01-19 10:06:00 +00004556 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004557}
4558
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004559/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004560uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004561ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4562 uint64_t ElementCount = 1;
4563 do {
4564 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004565 CA = dyn_cast_or_null<ConstantArrayType>(
4566 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004567 } while (CA);
4568 return ElementCount;
4569}
4570
Steve Naroff0af91202007-04-27 21:51:21 +00004571/// getFloatingRank - Return a relative rank for floating point types.
4572/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004573static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004574 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004575 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004576
John McCall9dd450b2009-09-21 23:43:11 +00004577 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4578 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004579 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004580 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004581 case BuiltinType::Float: return FloatRank;
4582 case BuiltinType::Double: return DoubleRank;
4583 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004584 }
4585}
4586
Mike Stump11289f42009-09-09 15:08:12 +00004587/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4588/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004589/// 'typeDomain' is a real floating point or complex type.
4590/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004591QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4592 QualType Domain) const {
4593 FloatingRank EltRank = getFloatingRank(Size);
4594 if (Domain->isComplexType()) {
4595 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004596 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004597 case FloatRank: return FloatComplexTy;
4598 case DoubleRank: return DoubleComplexTy;
4599 case LongDoubleRank: return LongDoubleComplexTy;
4600 }
Steve Naroff0af91202007-04-27 21:51:21 +00004601 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004602
4603 assert(Domain->isRealFloatingType() && "Unknown domain!");
4604 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004605 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004606 case FloatRank: return FloatTy;
4607 case DoubleRank: return DoubleTy;
4608 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004609 }
David Blaikief47fa302012-01-17 02:30:50 +00004610 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004611}
4612
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004613/// getFloatingTypeOrder - Compare the rank of the two specified floating
4614/// point types, ignoring the domain of the type (i.e. 'double' ==
4615/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004616/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004617int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004618 FloatingRank LHSR = getFloatingRank(LHS);
4619 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004620
Chris Lattnerb90739d2008-04-06 23:38:49 +00004621 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004622 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004623 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004624 return 1;
4625 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004626}
4627
Chris Lattner76a00cf2008-04-06 22:59:24 +00004628/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4629/// routine will assert if passed a built-in type that isn't an integer or enum,
4630/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004631unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004632 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004633
Chris Lattner76a00cf2008-04-06 22:59:24 +00004634 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004635 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004636 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004637 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004638 case BuiltinType::Char_S:
4639 case BuiltinType::Char_U:
4640 case BuiltinType::SChar:
4641 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004642 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004643 case BuiltinType::Short:
4644 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004645 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004646 case BuiltinType::Int:
4647 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004648 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004649 case BuiltinType::Long:
4650 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004651 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004652 case BuiltinType::LongLong:
4653 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004654 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004655 case BuiltinType::Int128:
4656 case BuiltinType::UInt128:
4657 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004658 }
4659}
4660
Eli Friedman629ffb92009-08-20 04:21:42 +00004661/// \brief Whether this is a promotable bitfield reference according
4662/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4663///
4664/// \returns the type this bit-field will promote to, or NULL if no
4665/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004666QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004667 if (E->isTypeDependent() || E->isValueDependent())
4668 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004669
4670 // FIXME: We should not do this unless E->refersToBitField() is true. This
4671 // matters in C where getSourceBitField() will find bit-fields for various
4672 // cases where the source expression is not a bit-field designator.
4673
John McCalld25db7e2013-05-06 21:39:12 +00004674 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004675 if (!Field)
4676 return QualType();
4677
4678 QualType FT = Field->getType();
4679
Richard Smithcaf33902011-10-10 18:28:20 +00004680 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004681 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004682 // C++ [conv.prom]p5:
4683 // A prvalue for an integral bit-field can be converted to a prvalue of type
4684 // int if int can represent all the values of the bit-field; otherwise, it
4685 // can be converted to unsigned int if unsigned int can represent all the
4686 // values of the bit-field. If the bit-field is larger yet, no integral
4687 // promotion applies to it.
4688 // C11 6.3.1.1/2:
4689 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4690 // If an int can represent all values of the original type (as restricted by
4691 // the width, for a bit-field), the value is converted to an int; otherwise,
4692 // it is converted to an unsigned int.
4693 //
4694 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4695 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004696 if (BitWidth < IntSize)
4697 return IntTy;
4698
4699 if (BitWidth == IntSize)
4700 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4701
4702 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004703 // like the base type. GCC has some weird bugs in this area that we
4704 // deliberately do not follow (GCC follows a pre-standard resolution to
4705 // C's DR315 which treats bit-width as being part of the type, and this leaks
4706 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004707 return QualType();
4708}
4709
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004710/// getPromotedIntegerType - Returns the type that Promotable will
4711/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4712/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004713QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004714 assert(!Promotable.isNull());
4715 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004716 if (const EnumType *ET = Promotable->getAs<EnumType>())
4717 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004718
4719 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4720 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4721 // (3.9.1) can be converted to a prvalue of the first of the following
4722 // types that can represent all the values of its underlying type:
4723 // int, unsigned int, long int, unsigned long int, long long int, or
4724 // unsigned long long int [...]
4725 // FIXME: Is there some better way to compute this?
4726 if (BT->getKind() == BuiltinType::WChar_S ||
4727 BT->getKind() == BuiltinType::WChar_U ||
4728 BT->getKind() == BuiltinType::Char16 ||
4729 BT->getKind() == BuiltinType::Char32) {
4730 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4731 uint64_t FromSize = getTypeSize(BT);
4732 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4733 LongLongTy, UnsignedLongLongTy };
4734 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4735 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4736 if (FromSize < ToSize ||
4737 (FromSize == ToSize &&
4738 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4739 return PromoteTypes[Idx];
4740 }
4741 llvm_unreachable("char type should fit into long long");
4742 }
4743 }
4744
4745 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004746 if (Promotable->isSignedIntegerType())
4747 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004748 uint64_t PromotableSize = getIntWidth(Promotable);
4749 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004750 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4751 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4752}
4753
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004754/// \brief Recurses in pointer/array types until it finds an objc retainable
4755/// type and returns its ownership.
4756Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4757 while (!T.isNull()) {
4758 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4759 return T.getObjCLifetime();
4760 if (T->isArrayType())
4761 T = getBaseElementType(T);
4762 else if (const PointerType *PT = T->getAs<PointerType>())
4763 T = PT->getPointeeType();
4764 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004765 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004766 else
4767 break;
4768 }
4769
4770 return Qualifiers::OCL_None;
4771}
4772
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004773static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4774 // Incomplete enum types are not treated as integer types.
4775 // FIXME: In C++, enum types are never integer types.
4776 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4777 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004778 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004779}
4780
Mike Stump11289f42009-09-09 15:08:12 +00004781/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004782/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004783/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004784int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004785 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4786 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004787
4788 // Unwrap enums to their underlying type.
4789 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4790 LHSC = getIntegerTypeForEnum(ET);
4791 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4792 RHSC = getIntegerTypeForEnum(ET);
4793
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004794 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004795
Chris Lattner76a00cf2008-04-06 22:59:24 +00004796 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4797 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004798
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004799 unsigned LHSRank = getIntegerRank(LHSC);
4800 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004801
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004802 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4803 if (LHSRank == RHSRank) return 0;
4804 return LHSRank > RHSRank ? 1 : -1;
4805 }
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004807 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4808 if (LHSUnsigned) {
4809 // If the unsigned [LHS] type is larger, return it.
4810 if (LHSRank >= RHSRank)
4811 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004812
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004813 // If the signed type can represent all values of the unsigned type, it
4814 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004815 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004816 return -1;
4817 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004818
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004819 // If the unsigned [RHS] type is larger, return it.
4820 if (RHSRank >= LHSRank)
4821 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004822
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004823 // If the signed type can represent all values of the unsigned type, it
4824 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004825 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004826 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004827}
Anders Carlsson98f07902007-08-17 05:31:46 +00004828
Mike Stump11289f42009-09-09 15:08:12 +00004829// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004830QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004831 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004832 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004833 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004834
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004835 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004836
Anders Carlsson98f07902007-08-17 05:31:46 +00004837 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004838 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004839 // int flags;
4840 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004841 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004842 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004843 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004844 FieldTypes[3] = LongTy;
4845
Anders Carlsson98f07902007-08-17 05:31:46 +00004846 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004847 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004848 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004849 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004850 SourceLocation(), nullptr,
4851 FieldTypes[i], /*TInfo=*/nullptr,
4852 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004853 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004854 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004855 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004856 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004857 }
4858
Douglas Gregord5058122010-02-11 01:19:42 +00004859 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004860 }
Mike Stump11289f42009-09-09 15:08:12 +00004861
Anders Carlsson98f07902007-08-17 05:31:46 +00004862 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004863}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004864
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004865QualType ASTContext::getObjCSuperType() const {
4866 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004867 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004868 TUDecl->addDecl(ObjCSuperTypeDecl);
4869 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4870 }
4871 return ObjCSuperType;
4872}
4873
Douglas Gregor512b0772009-04-23 22:29:11 +00004874void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004875 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004876 assert(Rec && "Invalid CFConstantStringType");
4877 CFConstantStringTypeDecl = Rec->getDecl();
4878}
4879
Jay Foad39c79802011-01-12 09:06:06 +00004880QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004881 if (BlockDescriptorType)
4882 return getTagDeclType(BlockDescriptorType);
4883
Alp Toker2dea15b2013-12-17 01:22:38 +00004884 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004885 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004886 RD = buildImplicitRecord("__block_descriptor");
4887 RD->startDefinition();
4888
Mike Stumpd0153282009-10-20 02:12:22 +00004889 QualType FieldTypes[] = {
4890 UnsignedLongTy,
4891 UnsignedLongTy,
4892 };
4893
Craig Topperd6d31ac2013-07-15 08:24:27 +00004894 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004895 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004896 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004897 };
4898
4899 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004900 FieldDecl *Field = FieldDecl::Create(
4901 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004902 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4903 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004904 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004905 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004906 }
4907
Alp Toker2dea15b2013-12-17 01:22:38 +00004908 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004909
Alp Toker2dea15b2013-12-17 01:22:38 +00004910 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004911
4912 return getTagDeclType(BlockDescriptorType);
4913}
4914
Jay Foad39c79802011-01-12 09:06:06 +00004915QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004916 if (BlockDescriptorExtendedType)
4917 return getTagDeclType(BlockDescriptorExtendedType);
4918
Alp Toker2dea15b2013-12-17 01:22:38 +00004919 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004920 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004921 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4922 RD->startDefinition();
4923
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004924 QualType FieldTypes[] = {
4925 UnsignedLongTy,
4926 UnsignedLongTy,
4927 getPointerType(VoidPtrTy),
4928 getPointerType(VoidPtrTy)
4929 };
4930
Craig Topperd6d31ac2013-07-15 08:24:27 +00004931 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004932 "reserved",
4933 "Size",
4934 "CopyFuncPtr",
4935 "DestroyFuncPtr"
4936 };
4937
4938 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004939 FieldDecl *Field = FieldDecl::Create(
4940 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004941 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4942 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004943 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004944 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004945 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004946 }
4947
Alp Toker2dea15b2013-12-17 01:22:38 +00004948 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004949
Alp Toker2dea15b2013-12-17 01:22:38 +00004950 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004951 return getTagDeclType(BlockDescriptorExtendedType);
4952}
4953
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004954/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4955/// requires copy/dispose. Note that this must match the logic
4956/// in buildByrefHelpers.
4957bool ASTContext::BlockRequiresCopying(QualType Ty,
4958 const VarDecl *D) {
4959 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4960 const Expr *copyExpr = getBlockVarCopyInits(D);
4961 if (!copyExpr && record->hasTrivialDestructor()) return false;
4962
Mike Stump94967902009-10-21 18:16:27 +00004963 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004964 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004965
4966 if (!Ty->isObjCRetainableType()) return false;
4967
4968 Qualifiers qs = Ty.getQualifiers();
4969
4970 // If we have lifetime, that dominates.
4971 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004972 switch (lifetime) {
4973 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4974
4975 // These are just bits as far as the runtime is concerned.
4976 case Qualifiers::OCL_ExplicitNone:
4977 case Qualifiers::OCL_Autoreleasing:
4978 return false;
4979
4980 // Tell the runtime that this is ARC __weak, called by the
4981 // byref routines.
4982 case Qualifiers::OCL_Weak:
4983 // ARC __strong __block variables need to be retained.
4984 case Qualifiers::OCL_Strong:
4985 return true;
4986 }
4987 llvm_unreachable("fell out of lifetime switch!");
4988 }
4989 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4990 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004991}
4992
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004993bool ASTContext::getByrefLifetime(QualType Ty,
4994 Qualifiers::ObjCLifetime &LifeTime,
4995 bool &HasByrefExtendedLayout) const {
4996
4997 if (!getLangOpts().ObjC1 ||
4998 getLangOpts().getGC() != LangOptions::NonGC)
4999 return false;
5000
5001 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005002 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005003 HasByrefExtendedLayout = true;
5004 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005005 } else if ((LifeTime = Ty.getObjCLifetime())) {
5006 // Honor the ARC qualifiers.
5007 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5008 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005009 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005010 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005011 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005012 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005013 return true;
5014}
5015
Douglas Gregorbab8a962011-09-08 01:46:34 +00005016TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5017 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005018 ObjCInstanceTypeDecl =
5019 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005020 return ObjCInstanceTypeDecl;
5021}
5022
Anders Carlsson18acd442007-10-29 06:33:42 +00005023// This returns true if a type has been typedefed to BOOL:
5024// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005025static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005026 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005027 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5028 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005029
Anders Carlssond8499822007-10-29 05:01:08 +00005030 return false;
5031}
5032
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005033/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005034/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005035CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005036 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5037 return CharUnits::Zero();
5038
Ken Dyck40775002010-01-11 17:06:35 +00005039 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005040
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005041 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005042 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005043 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005044 // Treat arrays as pointers, since that's how they're passed in.
5045 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005046 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005047 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005048}
5049
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005050bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005051 return getTargetInfo().getCXXABI().isMicrosoft() &&
5052 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005053 VD->getType()->isIntegralOrEnumerationType() &&
5054 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005055}
5056
Ken Dyck40775002010-01-11 17:06:35 +00005057static inline
5058std::string charUnitsToString(const CharUnits &CU) {
5059 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005060}
5061
John McCall351762c2011-02-07 10:33:21 +00005062/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005063/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005064std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5065 std::string S;
5066
David Chisnall950a9512009-11-17 19:33:30 +00005067 const BlockDecl *Decl = Expr->getBlockDecl();
5068 QualType BlockTy =
5069 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5070 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005071 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005072 getObjCEncodingForMethodParameter(
5073 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5074 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005075 else
Alp Toker314cc812014-01-25 16:55:45 +00005076 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005077 // Compute size of all parameters.
5078 // Start with computing size of a pointer in number of bytes.
5079 // FIXME: There might(should) be a better way of doing this computation!
5080 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005081 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5082 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005083 for (auto PI : Decl->params()) {
5084 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005085 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005086 if (sz.isZero())
5087 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005088 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005089 ParmOffset += sz;
5090 }
5091 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005092 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005093 // Block pointer and offset.
5094 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005095
5096 // Argument types.
5097 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005098 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005099 QualType PType = PVDecl->getOriginalType();
5100 if (const ArrayType *AT =
5101 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5102 // Use array's original type only if it has known number of
5103 // elements.
5104 if (!isa<ConstantArrayType>(AT))
5105 PType = PVDecl->getType();
5106 } else if (PType->isFunctionType())
5107 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005108 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005109 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5110 S, true /*Extended*/);
5111 else
5112 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005113 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005114 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005115 }
John McCall351762c2011-02-07 10:33:21 +00005116
5117 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005118}
5119
Douglas Gregora9d84932011-05-27 01:19:52 +00005120bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005121 std::string& S) {
5122 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005123 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005124 CharUnits ParmOffset;
5125 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005126 for (auto PI : Decl->params()) {
5127 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005128 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005129 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005130 continue;
5131
David Chisnall50e4eba2010-12-30 14:05:53 +00005132 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005133 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005134 ParmOffset += sz;
5135 }
5136 S += charUnitsToString(ParmOffset);
5137 ParmOffset = CharUnits::Zero();
5138
5139 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005140 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005141 QualType PType = PVDecl->getOriginalType();
5142 if (const ArrayType *AT =
5143 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5144 // Use array's original type only if it has known number of
5145 // elements.
5146 if (!isa<ConstantArrayType>(AT))
5147 PType = PVDecl->getType();
5148 } else if (PType->isFunctionType())
5149 PType = PVDecl->getType();
5150 getObjCEncodingForType(PType, S);
5151 S += charUnitsToString(ParmOffset);
5152 ParmOffset += getObjCEncodingTypeSize(PType);
5153 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005154
5155 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005156}
5157
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005158/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5159/// method parameter or return type. If Extended, include class names and
5160/// block object types.
5161void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5162 QualType T, std::string& S,
5163 bool Extended) const {
5164 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5165 getObjCEncodingForTypeQualifier(QT, S);
5166 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005167 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005168 true /*OutermostType*/,
5169 false /*EncodingProperty*/,
5170 false /*StructField*/,
5171 Extended /*EncodeBlockParameters*/,
5172 Extended /*EncodeClassNames*/);
5173}
5174
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005175/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005176/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005177bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005178 std::string& S,
5179 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005180 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005181 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005182 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5183 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005184 // Compute size of all parameters.
5185 // Start with computing size of a pointer in number of bytes.
5186 // FIXME: There might(should) be a better way of doing this computation!
5187 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005188 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005189 // The first two arguments (self and _cmd) are pointers; account for
5190 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005191 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005192 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005193 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005194 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005195 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005196 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005197 continue;
5198
Ken Dyck40775002010-01-11 17:06:35 +00005199 assert (sz.isPositive() &&
5200 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005201 ParmOffset += sz;
5202 }
Ken Dyck40775002010-01-11 17:06:35 +00005203 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005204 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005205 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005206
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005207 // Argument types.
5208 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005209 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005210 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005211 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005212 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005213 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005214 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5215 // Use array's original type only if it has known number of
5216 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005217 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005218 PType = PVDecl->getType();
5219 } else if (PType->isFunctionType())
5220 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005221 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5222 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005223 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005224 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005225 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005226
5227 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005228}
5229
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005230ObjCPropertyImplDecl *
5231ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5232 const ObjCPropertyDecl *PD,
5233 const Decl *Container) const {
5234 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005235 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005236 if (const ObjCCategoryImplDecl *CID =
5237 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005238 for (auto *PID : CID->property_impls())
5239 if (PID->getPropertyDecl() == PD)
5240 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005241 } else {
5242 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5243 for (auto *PID : OID->property_impls())
5244 if (PID->getPropertyDecl() == PD)
5245 return PID;
5246 }
5247 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005248}
5249
Daniel Dunbar4932b362008-08-28 04:38:10 +00005250/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005251/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005252/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5253/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005254/// Property attributes are stored as a comma-delimited C string. The simple
5255/// attributes readonly and bycopy are encoded as single characters. The
5256/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5257/// encoded as single characters, followed by an identifier. Property types
5258/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005259/// these attributes are defined by the following enumeration:
5260/// @code
5261/// enum PropertyAttributes {
5262/// kPropertyReadOnly = 'R', // property is read-only.
5263/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5264/// kPropertyByref = '&', // property is a reference to the value last assigned
5265/// kPropertyDynamic = 'D', // property is dynamic
5266/// kPropertyGetter = 'G', // followed by getter selector name
5267/// kPropertySetter = 'S', // followed by setter selector name
5268/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005269/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005270/// kPropertyWeak = 'W' // 'weak' property
5271/// kPropertyStrong = 'P' // property GC'able
5272/// kPropertyNonAtomic = 'N' // property non-atomic
5273/// };
5274/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005275void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005276 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005277 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005278 // Collect information from the property implementation decl(s).
5279 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005280 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005281
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005282 if (ObjCPropertyImplDecl *PropertyImpDecl =
5283 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5284 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5285 Dynamic = true;
5286 else
5287 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005288 }
5289
5290 // FIXME: This is not very efficient.
5291 S = "T";
5292
5293 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005294 // GCC has some special rules regarding encoding of properties which
5295 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005296 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005297
5298 if (PD->isReadOnly()) {
5299 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005300 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5301 S += ",C";
5302 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5303 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005304 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5305 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005306 } else {
5307 switch (PD->getSetterKind()) {
5308 case ObjCPropertyDecl::Assign: break;
5309 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005310 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005311 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005312 }
5313 }
5314
5315 // It really isn't clear at all what this means, since properties
5316 // are "dynamic by default".
5317 if (Dynamic)
5318 S += ",D";
5319
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005320 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5321 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005322
Daniel Dunbar4932b362008-08-28 04:38:10 +00005323 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5324 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005325 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005326 }
5327
5328 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5329 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005330 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005331 }
5332
5333 if (SynthesizePID) {
5334 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5335 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005336 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005337 }
5338
5339 // FIXME: OBJCGC: weak & strong
5340}
5341
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005342/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005343/// Another legacy compatibility encoding: 32-bit longs are encoded as
5344/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005345/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5346///
5347void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005348 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005349 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005350 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005351 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005352 else
Jay Foad39c79802011-01-12 09:06:06 +00005353 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005354 PointeeTy = IntTy;
5355 }
5356 }
5357}
5358
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005359void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005360 const FieldDecl *Field,
5361 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005362 // We follow the behavior of gcc, expanding structures which are
5363 // directly pointed to, and expanding embedded structures. Note that
5364 // these rules are sufficient to prevent recursive encoding of the
5365 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005366 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005367 true /* outermost type */, false, false,
5368 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005369}
5370
Joe Groff98ac7d22014-07-07 22:25:15 +00005371void ASTContext::getObjCEncodingForPropertyType(QualType T,
5372 std::string& S) const {
5373 // Encode result type.
5374 // GCC has some special rules regarding encoding of properties which
5375 // closely resembles encoding of ivars.
5376 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5377 true /* outermost type */,
5378 true /* encoding property */);
5379}
5380
John McCall393a78d2012-12-20 02:45:14 +00005381static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5382 BuiltinType::Kind kind) {
5383 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005384 case BuiltinType::Void: return 'v';
5385 case BuiltinType::Bool: return 'B';
5386 case BuiltinType::Char_U:
5387 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005388 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005389 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005390 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005391 case BuiltinType::UInt: return 'I';
5392 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005393 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005394 case BuiltinType::UInt128: return 'T';
5395 case BuiltinType::ULongLong: return 'Q';
5396 case BuiltinType::Char_S:
5397 case BuiltinType::SChar: return 'c';
5398 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005399 case BuiltinType::WChar_S:
5400 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005401 case BuiltinType::Int: return 'i';
5402 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005403 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005404 case BuiltinType::LongLong: return 'q';
5405 case BuiltinType::Int128: return 't';
5406 case BuiltinType::Float: return 'f';
5407 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005408 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005409 case BuiltinType::NullPtr: return '*'; // like char*
5410
5411 case BuiltinType::Half:
5412 // FIXME: potentially need @encodes for these!
5413 return ' ';
5414
5415 case BuiltinType::ObjCId:
5416 case BuiltinType::ObjCClass:
5417 case BuiltinType::ObjCSel:
5418 llvm_unreachable("@encoding ObjC primitive type");
5419
5420 // OpenCL and placeholder types don't need @encodings.
5421 case BuiltinType::OCLImage1d:
5422 case BuiltinType::OCLImage1dArray:
5423 case BuiltinType::OCLImage1dBuffer:
5424 case BuiltinType::OCLImage2d:
5425 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005426 case BuiltinType::OCLImage2dDepth:
5427 case BuiltinType::OCLImage2dArrayDepth:
5428 case BuiltinType::OCLImage2dMSAA:
5429 case BuiltinType::OCLImage2dArrayMSAA:
5430 case BuiltinType::OCLImage2dMSAADepth:
5431 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005432 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005433 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005434 case BuiltinType::OCLClkEvent:
5435 case BuiltinType::OCLQueue:
5436 case BuiltinType::OCLNDRange:
5437 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005438 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005439 case BuiltinType::Dependent:
5440#define BUILTIN_TYPE(KIND, ID)
5441#define PLACEHOLDER_TYPE(KIND, ID) \
5442 case BuiltinType::KIND:
5443#include "clang/AST/BuiltinTypes.def"
5444 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005445 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005446 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005447}
5448
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005449static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5450 EnumDecl *Enum = ET->getDecl();
5451
5452 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5453 if (!Enum->isFixed())
5454 return 'i';
5455
5456 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005457 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5458 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005459}
5460
Jay Foad39c79802011-01-12 09:06:06 +00005461static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005462 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005463 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005464 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005465 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5466 // The GNU runtime requires more information; bitfields are encoded as b,
5467 // then the offset (in bits) of the first element, then the type of the
5468 // bitfield, then the size in bits. For example, in this structure:
5469 //
5470 // struct
5471 // {
5472 // int integer;
5473 // int flags:2;
5474 // };
5475 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5476 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5477 // information is not especially sensible, but we're stuck with it for
5478 // compatibility with GCC, although providing it breaks anything that
5479 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005480 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005481 const RecordDecl *RD = FD->getParent();
5482 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005483 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005484 if (const EnumType *ET = T->getAs<EnumType>())
5485 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005486 else {
5487 const BuiltinType *BT = T->castAs<BuiltinType>();
5488 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5489 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005490 }
Richard Smithcaf33902011-10-10 18:28:20 +00005491 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005492}
5493
Daniel Dunbar07d07852009-10-18 21:17:35 +00005494// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005495void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5496 bool ExpandPointedToStructures,
5497 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005498 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005499 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005500 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005501 bool StructField,
5502 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005503 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005504 bool EncodePointerToObjCTypedef,
5505 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005506 CanQualType CT = getCanonicalType(T);
5507 switch (CT->getTypeClass()) {
5508 case Type::Builtin:
5509 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005510 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005511 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005512 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5513 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5514 else
5515 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005516 return;
Mike Stump11289f42009-09-09 15:08:12 +00005517
John McCall393a78d2012-12-20 02:45:14 +00005518 case Type::Complex: {
5519 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005520 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005521 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005522 return;
5523 }
John McCall393a78d2012-12-20 02:45:14 +00005524
5525 case Type::Atomic: {
5526 const AtomicType *AT = T->castAs<AtomicType>();
5527 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005528 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005529 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005530 }
John McCall393a78d2012-12-20 02:45:14 +00005531
5532 // encoding for pointer or reference types.
5533 case Type::Pointer:
5534 case Type::LValueReference:
5535 case Type::RValueReference: {
5536 QualType PointeeTy;
5537 if (isa<PointerType>(CT)) {
5538 const PointerType *PT = T->castAs<PointerType>();
5539 if (PT->isObjCSelType()) {
5540 S += ':';
5541 return;
5542 }
5543 PointeeTy = PT->getPointeeType();
5544 } else {
5545 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5546 }
5547
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005548 bool isReadOnly = false;
5549 // For historical/compatibility reasons, the read-only qualifier of the
5550 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5551 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005552 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005553 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005554 if (OutermostType && T.isConstQualified()) {
5555 isReadOnly = true;
5556 S += 'r';
5557 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005558 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005559 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005560 while (P->getAs<PointerType>())
5561 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005562 if (P.isConstQualified()) {
5563 isReadOnly = true;
5564 S += 'r';
5565 }
5566 }
5567 if (isReadOnly) {
5568 // Another legacy compatibility encoding. Some ObjC qualifier and type
5569 // combinations need to be rearranged.
5570 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005571 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005572 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005573 }
Mike Stump11289f42009-09-09 15:08:12 +00005574
Anders Carlssond8499822007-10-29 05:01:08 +00005575 if (PointeeTy->isCharType()) {
5576 // char pointer types should be encoded as '*' unless it is a
5577 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005578 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005579 S += '*';
5580 return;
5581 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005582 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005583 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5584 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5585 S += '#';
5586 return;
5587 }
5588 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5589 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5590 S += '@';
5591 return;
5592 }
5593 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005594 }
Anders Carlssond8499822007-10-29 05:01:08 +00005595 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005596 getLegacyIntegralTypeEncoding(PointeeTy);
5597
Mike Stump11289f42009-09-09 15:08:12 +00005598 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005599 nullptr, false, false, false, false, false, false,
5600 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005601 return;
5602 }
John McCall393a78d2012-12-20 02:45:14 +00005603
5604 case Type::ConstantArray:
5605 case Type::IncompleteArray:
5606 case Type::VariableArray: {
5607 const ArrayType *AT = cast<ArrayType>(CT);
5608
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005609 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005610 // Incomplete arrays are encoded as a pointer to the array element.
5611 S += '^';
5612
Mike Stump11289f42009-09-09 15:08:12 +00005613 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005614 false, ExpandStructures, FD);
5615 } else {
5616 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005617
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005618 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5619 S += llvm::utostr(CAT->getSize().getZExtValue());
5620 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005621 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005622 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5623 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005624 S += '0';
5625 }
Mike Stump11289f42009-09-09 15:08:12 +00005626
5627 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005628 false, ExpandStructures, FD,
5629 false, false, false, false, false, false,
5630 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005631 S += ']';
5632 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005633 return;
5634 }
Mike Stump11289f42009-09-09 15:08:12 +00005635
John McCall393a78d2012-12-20 02:45:14 +00005636 case Type::FunctionNoProto:
5637 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005638 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005639 return;
Mike Stump11289f42009-09-09 15:08:12 +00005640
John McCall393a78d2012-12-20 02:45:14 +00005641 case Type::Record: {
5642 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005643 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005644 // Anonymous structures print as '?'
5645 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5646 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005647 if (ClassTemplateSpecializationDecl *Spec
5648 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5649 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005650 llvm::raw_string_ostream OS(S);
5651 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005652 TemplateArgs.data(),
5653 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005654 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005655 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005656 } else {
5657 S += '?';
5658 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005659 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005660 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005661 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005662 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005663 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005664 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005665 if (FD) {
5666 S += '"';
5667 S += Field->getNameAsString();
5668 S += '"';
5669 }
Mike Stump11289f42009-09-09 15:08:12 +00005670
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005671 // Special case bit-fields.
5672 if (Field->isBitField()) {
5673 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005674 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005675 } else {
5676 QualType qt = Field->getType();
5677 getLegacyIntegralTypeEncoding(qt);
5678 getObjCEncodingForTypeImpl(qt, S, false, true,
5679 FD, /*OutermostType*/false,
5680 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005681 /*StructField*/true,
5682 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005683 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005684 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005685 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005686 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005687 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005688 return;
5689 }
Mike Stump11289f42009-09-09 15:08:12 +00005690
John McCall393a78d2012-12-20 02:45:14 +00005691 case Type::BlockPointer: {
5692 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005693 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005694 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005695 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005696
5697 S += '<';
5698 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005699 getObjCEncodingForTypeImpl(
5700 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5701 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005702 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5703 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005704 // Block self
5705 S += "@?";
5706 // Block parameters
5707 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005708 for (const auto &I : FPT->param_types())
5709 getObjCEncodingForTypeImpl(
5710 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5711 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005712 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5713 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005714 }
5715 S += '>';
5716 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005717 return;
5718 }
Mike Stump11289f42009-09-09 15:08:12 +00005719
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005720 case Type::ObjCObject: {
5721 // hack to match legacy encoding of *id and *Class
5722 QualType Ty = getObjCObjectPointerType(CT);
5723 if (Ty->isObjCIdType()) {
5724 S += "{objc_object=}";
5725 return;
5726 }
5727 else if (Ty->isObjCClassType()) {
5728 S += "{objc_class=}";
5729 return;
5730 }
5731 }
5732
John McCall393a78d2012-12-20 02:45:14 +00005733 case Type::ObjCInterface: {
5734 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005735 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005736 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005737 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005738 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005739 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005740 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005741 DeepCollectObjCIvars(OI, true, Ivars);
5742 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005743 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005744 if (Field->isBitField())
5745 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005746 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005747 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5748 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005749 EncodePointerToObjCTypedef,
5750 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005751 }
5752 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005753 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005754 }
Mike Stump11289f42009-09-09 15:08:12 +00005755
John McCall393a78d2012-12-20 02:45:14 +00005756 case Type::ObjCObjectPointer: {
5757 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005758 if (OPT->isObjCIdType()) {
5759 S += '@';
5760 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005761 }
Mike Stump11289f42009-09-09 15:08:12 +00005762
Steve Narofff0c86112009-10-28 22:03:49 +00005763 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5764 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5765 // Since this is a binary compatibility issue, need to consult with runtime
5766 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005767 S += '#';
5768 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005769 }
Mike Stump11289f42009-09-09 15:08:12 +00005770
Chris Lattnere7cabb92009-07-13 00:10:46 +00005771 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005772 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005773 ExpandPointedToStructures,
5774 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005775 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005776 // Note that we do extended encoding of protocol qualifer list
5777 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005778 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005779 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005780 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005781 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005782 S += '>';
5783 }
5784 S += '"';
5785 }
5786 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005787 }
Mike Stump11289f42009-09-09 15:08:12 +00005788
Chris Lattnere7cabb92009-07-13 00:10:46 +00005789 QualType PointeeTy = OPT->getPointeeType();
5790 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005791 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5792 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005793 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005794 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005795 // {...};
5796 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005797 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005798 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005799 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5800 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5801 DeepCollectObjCIvars(OI, true, Ivars);
5802 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5803 if (cast<FieldDecl>(Ivars[i]) == FD) {
5804 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005805 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005806 S += '}';
5807 return;
5808 }
5809 }
5810 }
Mike Stump11289f42009-09-09 15:08:12 +00005811 getObjCEncodingForTypeImpl(PointeeTy, S,
5812 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005813 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005814 false, false, false, false, false,
5815 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005816 return;
5817 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005818
5819 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005820 if (OPT->getInterfaceDecl() &&
5821 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005822 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005823 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005824 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005825 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005826 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005827 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005828 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005829 S += '"';
5830 }
5831 return;
5832 }
Mike Stump11289f42009-09-09 15:08:12 +00005833
John McCalla9e6e8d2010-05-17 23:56:34 +00005834 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005835 // FIXME: we shoul do better than that. 'M' is available.
5836 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005837 // This matches gcc's encoding, even though technically it is insufficient.
5838 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005839 case Type::Vector:
5840 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005841 // Until we have a coherent encoding of these three types, issue warning.
5842 { if (NotEncodedT)
5843 *NotEncodedT = T;
5844 return;
5845 }
5846
5847 // We could see an undeduced auto type here during error recovery.
5848 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005849 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005850 return;
5851
John McCall393a78d2012-12-20 02:45:14 +00005852#define ABSTRACT_TYPE(KIND, BASE)
5853#define TYPE(KIND, BASE)
5854#define DEPENDENT_TYPE(KIND, BASE) \
5855 case Type::KIND:
5856#define NON_CANONICAL_TYPE(KIND, BASE) \
5857 case Type::KIND:
5858#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5859 case Type::KIND:
5860#include "clang/AST/TypeNodes.def"
5861 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005862 }
John McCall393a78d2012-12-20 02:45:14 +00005863 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005864}
5865
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005866void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5867 std::string &S,
5868 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005869 bool includeVBases,
5870 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005871 assert(RDecl && "Expected non-null RecordDecl");
5872 assert(!RDecl->isUnion() && "Should not be called for unions");
5873 if (!RDecl->getDefinition())
5874 return;
5875
5876 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5877 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5878 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5879
5880 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005881 for (const auto &BI : CXXRec->bases()) {
5882 if (!BI.isVirtual()) {
5883 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005884 if (base->isEmpty())
5885 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005886 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005887 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5888 std::make_pair(offs, base));
5889 }
5890 }
5891 }
5892
5893 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005894 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005895 uint64_t offs = layout.getFieldOffset(i);
5896 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005897 std::make_pair(offs, Field));
5898 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005899 }
5900
5901 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005902 for (const auto &BI : CXXRec->vbases()) {
5903 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005904 if (base->isEmpty())
5905 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005906 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005907 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5908 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005909 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5910 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005911 }
5912 }
5913
5914 CharUnits size;
5915 if (CXXRec) {
5916 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5917 } else {
5918 size = layout.getSize();
5919 }
5920
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005921#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005922 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005923#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005924 std::multimap<uint64_t, NamedDecl *>::iterator
5925 CurLayObj = FieldOrBaseOffsets.begin();
5926
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005927 if (CXXRec && CXXRec->isDynamicClass() &&
5928 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005929 if (FD) {
5930 S += "\"_vptr$";
5931 std::string recname = CXXRec->getNameAsString();
5932 if (recname.empty()) recname = "?";
5933 S += recname;
5934 S += '"';
5935 }
5936 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005937#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005938 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005939#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005940 }
5941
5942 if (!RDecl->hasFlexibleArrayMember()) {
5943 // Mark the end of the structure.
5944 uint64_t offs = toBits(size);
5945 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005946 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005947 }
5948
5949 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005950#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005951 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005952 if (CurOffs < CurLayObj->first) {
5953 uint64_t padding = CurLayObj->first - CurOffs;
5954 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5955 // packing/alignment of members is different that normal, in which case
5956 // the encoding will be out-of-sync with the real layout.
5957 // If the runtime switches to just consider the size of types without
5958 // taking into account alignment, we could make padding explicit in the
5959 // encoding (e.g. using arrays of chars). The encoding strings would be
5960 // longer then though.
5961 CurOffs += padding;
5962 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005963#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005964
5965 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005966 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005967 break; // reached end of structure.
5968
5969 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5970 // We expand the bases without their virtual bases since those are going
5971 // in the initial structure. Note that this differs from gcc which
5972 // expands virtual bases each time one is encountered in the hierarchy,
5973 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005974 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5975 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005976 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005977#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005978 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005979#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005980 } else {
5981 FieldDecl *field = cast<FieldDecl>(dcl);
5982 if (FD) {
5983 S += '"';
5984 S += field->getNameAsString();
5985 S += '"';
5986 }
5987
5988 if (field->isBitField()) {
5989 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005990#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005991 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005992#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005993 } else {
5994 QualType qt = field->getType();
5995 getLegacyIntegralTypeEncoding(qt);
5996 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5997 /*OutermostType*/false,
5998 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005999 /*StructField*/true,
6000 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006001#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006002 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006003#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006004 }
6005 }
6006 }
6007}
6008
Mike Stump11289f42009-09-09 15:08:12 +00006009void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006010 std::string& S) const {
6011 if (QT & Decl::OBJC_TQ_In)
6012 S += 'n';
6013 if (QT & Decl::OBJC_TQ_Inout)
6014 S += 'N';
6015 if (QT & Decl::OBJC_TQ_Out)
6016 S += 'o';
6017 if (QT & Decl::OBJC_TQ_Bycopy)
6018 S += 'O';
6019 if (QT & Decl::OBJC_TQ_Byref)
6020 S += 'R';
6021 if (QT & Decl::OBJC_TQ_Oneway)
6022 S += 'V';
6023}
6024
Douglas Gregor3ea72692011-08-12 05:46:01 +00006025TypedefDecl *ASTContext::getObjCIdDecl() const {
6026 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006027 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006028 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006029 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006030 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006031 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006032}
6033
Douglas Gregor52e02802011-08-12 06:17:30 +00006034TypedefDecl *ASTContext::getObjCSelDecl() const {
6035 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006036 QualType T = getPointerType(ObjCBuiltinSelTy);
6037 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006038 }
6039 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006040}
6041
Douglas Gregor0a586182011-08-12 05:59:41 +00006042TypedefDecl *ASTContext::getObjCClassDecl() const {
6043 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006044 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006045 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006046 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006047 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006048 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006049}
6050
Douglas Gregord53ae832012-01-17 18:09:05 +00006051ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6052 if (!ObjCProtocolClassDecl) {
6053 ObjCProtocolClassDecl
6054 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6055 SourceLocation(),
6056 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006057 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006058 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006059 SourceLocation(), true);
6060 }
6061
6062 return ObjCProtocolClassDecl;
6063}
6064
Meador Inge5d3fb222012-06-16 03:34:49 +00006065//===----------------------------------------------------------------------===//
6066// __builtin_va_list Construction Functions
6067//===----------------------------------------------------------------------===//
6068
Charles Davisc7d5c942015-09-17 20:55:33 +00006069static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6070 StringRef Name) {
6071 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006072 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006073 return Context->buildImplicitTypedef(T, Name);
6074}
6075
6076static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6077 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6078}
6079
6080static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6081 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006082}
6083
6084static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6085 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006086 QualType T = Context->getPointerType(Context->VoidTy);
6087 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006088}
6089
Tim Northover9bb857a2013-01-31 12:13:10 +00006090static TypedefDecl *
6091CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006092 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006093 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006094 if (Context->getLangOpts().CPlusPlus) {
6095 // namespace std { struct __va_list {
6096 NamespaceDecl *NS;
6097 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6098 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006099 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006100 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006101 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006102 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006103 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006104 }
6105
6106 VaListTagDecl->startDefinition();
6107
6108 const size_t NumFields = 5;
6109 QualType FieldTypes[NumFields];
6110 const char *FieldNames[NumFields];
6111
6112 // void *__stack;
6113 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6114 FieldNames[0] = "__stack";
6115
6116 // void *__gr_top;
6117 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6118 FieldNames[1] = "__gr_top";
6119
6120 // void *__vr_top;
6121 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6122 FieldNames[2] = "__vr_top";
6123
6124 // int __gr_offs;
6125 FieldTypes[3] = Context->IntTy;
6126 FieldNames[3] = "__gr_offs";
6127
6128 // int __vr_offs;
6129 FieldTypes[4] = Context->IntTy;
6130 FieldNames[4] = "__vr_offs";
6131
6132 // Create fields
6133 for (unsigned i = 0; i < NumFields; ++i) {
6134 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6135 VaListTagDecl,
6136 SourceLocation(),
6137 SourceLocation(),
6138 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006139 FieldTypes[i], /*TInfo=*/nullptr,
6140 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006141 /*Mutable=*/false,
6142 ICIS_NoInit);
6143 Field->setAccess(AS_public);
6144 VaListTagDecl->addDecl(Field);
6145 }
6146 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006147 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006148 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006149
6150 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006151 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006152}
6153
Meador Inge5d3fb222012-06-16 03:34:49 +00006154static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6155 // typedef struct __va_list_tag {
6156 RecordDecl *VaListTagDecl;
6157
Alp Toker2dea15b2013-12-17 01:22:38 +00006158 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006159 VaListTagDecl->startDefinition();
6160
6161 const size_t NumFields = 5;
6162 QualType FieldTypes[NumFields];
6163 const char *FieldNames[NumFields];
6164
6165 // unsigned char gpr;
6166 FieldTypes[0] = Context->UnsignedCharTy;
6167 FieldNames[0] = "gpr";
6168
6169 // unsigned char fpr;
6170 FieldTypes[1] = Context->UnsignedCharTy;
6171 FieldNames[1] = "fpr";
6172
6173 // unsigned short reserved;
6174 FieldTypes[2] = Context->UnsignedShortTy;
6175 FieldNames[2] = "reserved";
6176
6177 // void* overflow_arg_area;
6178 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6179 FieldNames[3] = "overflow_arg_area";
6180
6181 // void* reg_save_area;
6182 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6183 FieldNames[4] = "reg_save_area";
6184
6185 // Create fields
6186 for (unsigned i = 0; i < NumFields; ++i) {
6187 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6188 SourceLocation(),
6189 SourceLocation(),
6190 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006191 FieldTypes[i], /*TInfo=*/nullptr,
6192 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006193 /*Mutable=*/false,
6194 ICIS_NoInit);
6195 Field->setAccess(AS_public);
6196 VaListTagDecl->addDecl(Field);
6197 }
6198 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006199 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006200 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6201
6202 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006203 TypedefDecl *VaListTagTypedefDecl =
6204 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6205
Meador Inge5d3fb222012-06-16 03:34:49 +00006206 QualType VaListTagTypedefType =
6207 Context->getTypedefType(VaListTagTypedefDecl);
6208
6209 // typedef __va_list_tag __builtin_va_list[1];
6210 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6211 QualType VaListTagArrayType
6212 = Context->getConstantArrayType(VaListTagTypedefType,
6213 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006214 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006215}
6216
6217static TypedefDecl *
6218CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006219 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006220 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006221 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006222 VaListTagDecl->startDefinition();
6223
6224 const size_t NumFields = 4;
6225 QualType FieldTypes[NumFields];
6226 const char *FieldNames[NumFields];
6227
6228 // unsigned gp_offset;
6229 FieldTypes[0] = Context->UnsignedIntTy;
6230 FieldNames[0] = "gp_offset";
6231
6232 // unsigned fp_offset;
6233 FieldTypes[1] = Context->UnsignedIntTy;
6234 FieldNames[1] = "fp_offset";
6235
6236 // void* overflow_arg_area;
6237 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6238 FieldNames[2] = "overflow_arg_area";
6239
6240 // void* reg_save_area;
6241 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6242 FieldNames[3] = "reg_save_area";
6243
6244 // Create fields
6245 for (unsigned i = 0; i < NumFields; ++i) {
6246 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6247 VaListTagDecl,
6248 SourceLocation(),
6249 SourceLocation(),
6250 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006251 FieldTypes[i], /*TInfo=*/nullptr,
6252 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006253 /*Mutable=*/false,
6254 ICIS_NoInit);
6255 Field->setAccess(AS_public);
6256 VaListTagDecl->addDecl(Field);
6257 }
6258 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006259 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006260 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6261
Richard Smith9b88a4c2015-07-27 05:40:23 +00006262 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006263
Richard Smith9b88a4c2015-07-27 05:40:23 +00006264 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006265 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006266 QualType VaListTagArrayType =
6267 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006268 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006269}
6270
6271static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6272 // typedef int __builtin_va_list[4];
6273 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6274 QualType IntArrayType
6275 = Context->getConstantArrayType(Context->IntTy,
6276 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006277 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006278}
6279
Logan Chien57086ce2012-10-10 06:56:20 +00006280static TypedefDecl *
6281CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006282 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006283 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006284 if (Context->getLangOpts().CPlusPlus) {
6285 // namespace std { struct __va_list {
6286 NamespaceDecl *NS;
6287 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6288 Context->getTranslationUnitDecl(),
6289 /*Inline*/false, SourceLocation(),
6290 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006291 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006292 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006293 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006294 }
6295
6296 VaListDecl->startDefinition();
6297
6298 // void * __ap;
6299 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6300 VaListDecl,
6301 SourceLocation(),
6302 SourceLocation(),
6303 &Context->Idents.get("__ap"),
6304 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006305 /*TInfo=*/nullptr,
6306 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006307 /*Mutable=*/false,
6308 ICIS_NoInit);
6309 Field->setAccess(AS_public);
6310 VaListDecl->addDecl(Field);
6311
6312 // };
6313 VaListDecl->completeDefinition();
6314
6315 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006316 QualType T = Context->getRecordType(VaListDecl);
6317 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006318}
6319
Ulrich Weigand47445072013-05-06 16:26:41 +00006320static TypedefDecl *
6321CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006322 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006323 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006324 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006325 VaListTagDecl->startDefinition();
6326
6327 const size_t NumFields = 4;
6328 QualType FieldTypes[NumFields];
6329 const char *FieldNames[NumFields];
6330
6331 // long __gpr;
6332 FieldTypes[0] = Context->LongTy;
6333 FieldNames[0] = "__gpr";
6334
6335 // long __fpr;
6336 FieldTypes[1] = Context->LongTy;
6337 FieldNames[1] = "__fpr";
6338
6339 // void *__overflow_arg_area;
6340 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6341 FieldNames[2] = "__overflow_arg_area";
6342
6343 // void *__reg_save_area;
6344 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6345 FieldNames[3] = "__reg_save_area";
6346
6347 // Create fields
6348 for (unsigned i = 0; i < NumFields; ++i) {
6349 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6350 VaListTagDecl,
6351 SourceLocation(),
6352 SourceLocation(),
6353 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006354 FieldTypes[i], /*TInfo=*/nullptr,
6355 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006356 /*Mutable=*/false,
6357 ICIS_NoInit);
6358 Field->setAccess(AS_public);
6359 VaListTagDecl->addDecl(Field);
6360 }
6361 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006362 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006363 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006364
Richard Smith9b88a4c2015-07-27 05:40:23 +00006365 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006366
6367 // typedef __va_list_tag __builtin_va_list[1];
6368 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006369 QualType VaListTagArrayType =
6370 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006371
Alp Toker56b5cc92013-12-15 10:36:26 +00006372 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006373}
6374
Meador Inge5d3fb222012-06-16 03:34:49 +00006375static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6376 TargetInfo::BuiltinVaListKind Kind) {
6377 switch (Kind) {
6378 case TargetInfo::CharPtrBuiltinVaList:
6379 return CreateCharPtrBuiltinVaListDecl(Context);
6380 case TargetInfo::VoidPtrBuiltinVaList:
6381 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006382 case TargetInfo::AArch64ABIBuiltinVaList:
6383 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006384 case TargetInfo::PowerABIBuiltinVaList:
6385 return CreatePowerABIBuiltinVaListDecl(Context);
6386 case TargetInfo::X86_64ABIBuiltinVaList:
6387 return CreateX86_64ABIBuiltinVaListDecl(Context);
6388 case TargetInfo::PNaClABIBuiltinVaList:
6389 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006390 case TargetInfo::AAPCSABIBuiltinVaList:
6391 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006392 case TargetInfo::SystemZBuiltinVaList:
6393 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006394 }
6395
6396 llvm_unreachable("Unhandled __builtin_va_list type kind");
6397}
6398
6399TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006400 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006401 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006402 assert(BuiltinVaListDecl->isImplicit());
6403 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006404
6405 return BuiltinVaListDecl;
6406}
6407
Richard Smith9b88a4c2015-07-27 05:40:23 +00006408Decl *ASTContext::getVaListTagDecl() const {
6409 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006410 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006411 if (!VaListTagDecl)
6412 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006413
Richard Smith9b88a4c2015-07-27 05:40:23 +00006414 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006415}
6416
Charles Davisc7d5c942015-09-17 20:55:33 +00006417TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6418 if (!BuiltinMSVaListDecl)
6419 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6420
6421 return BuiltinMSVaListDecl;
6422}
6423
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006424void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006425 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006426 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006427
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006428 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006429}
6430
John McCalld28ae272009-12-02 08:04:21 +00006431/// \brief Retrieve the template name that corresponds to a non-empty
6432/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006433TemplateName
6434ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6435 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006436 unsigned size = End - Begin;
6437 assert(size > 1 && "set is not overloaded!");
6438
6439 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6440 size * sizeof(FunctionTemplateDecl*));
6441 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6442
6443 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006444 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006445 NamedDecl *D = *I;
6446 assert(isa<FunctionTemplateDecl>(D) ||
6447 (isa<UsingShadowDecl>(D) &&
6448 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6449 *Storage++ = D;
6450 }
6451
6452 return TemplateName(OT);
6453}
6454
Douglas Gregordc572a32009-03-30 22:58:21 +00006455/// \brief Retrieve the template name that represents a qualified
6456/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006457TemplateName
6458ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6459 bool TemplateKeyword,
6460 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006461 assert(NNS && "Missing nested-name-specifier in qualified template name");
6462
Douglas Gregorc42075a2010-02-04 18:10:26 +00006463 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006464 llvm::FoldingSetNodeID ID;
6465 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6466
Craig Topper36250ad2014-05-12 05:36:57 +00006467 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006468 QualifiedTemplateName *QTN =
6469 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6470 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006471 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6472 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006473 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6474 }
6475
6476 return TemplateName(QTN);
6477}
6478
6479/// \brief Retrieve the template name that represents a dependent
6480/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006481TemplateName
6482ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6483 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006484 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006485 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006486
6487 llvm::FoldingSetNodeID ID;
6488 DependentTemplateName::Profile(ID, NNS, Name);
6489
Craig Topper36250ad2014-05-12 05:36:57 +00006490 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006491 DependentTemplateName *QTN =
6492 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6493
6494 if (QTN)
6495 return TemplateName(QTN);
6496
6497 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6498 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006499 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6500 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006501 } else {
6502 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006503 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6504 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006505 DependentTemplateName *CheckQTN =
6506 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6507 assert(!CheckQTN && "Dependent type name canonicalization broken");
6508 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006509 }
6510
6511 DependentTemplateNames.InsertNode(QTN, InsertPos);
6512 return TemplateName(QTN);
6513}
6514
Douglas Gregor71395fa2009-11-04 00:56:37 +00006515/// \brief Retrieve the template name that represents a dependent
6516/// template name such as \c MetaFun::template operator+.
6517TemplateName
6518ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006519 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006520 assert((!NNS || NNS->isDependent()) &&
6521 "Nested name specifier must be dependent");
6522
6523 llvm::FoldingSetNodeID ID;
6524 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006525
6526 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006527 DependentTemplateName *QTN
6528 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006529
6530 if (QTN)
6531 return TemplateName(QTN);
6532
6533 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6534 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006535 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6536 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006537 } else {
6538 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006539 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6540 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006541
6542 DependentTemplateName *CheckQTN
6543 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6544 assert(!CheckQTN && "Dependent template name canonicalization broken");
6545 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006546 }
6547
6548 DependentTemplateNames.InsertNode(QTN, InsertPos);
6549 return TemplateName(QTN);
6550}
6551
Douglas Gregor5590be02011-01-15 06:45:20 +00006552TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006553ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6554 TemplateName replacement) const {
6555 llvm::FoldingSetNodeID ID;
6556 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006557
6558 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006559 SubstTemplateTemplateParmStorage *subst
6560 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6561
6562 if (!subst) {
6563 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6564 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6565 }
6566
6567 return TemplateName(subst);
6568}
6569
6570TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006571ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6572 const TemplateArgument &ArgPack) const {
6573 ASTContext &Self = const_cast<ASTContext &>(*this);
6574 llvm::FoldingSetNodeID ID;
6575 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006576
6577 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006578 SubstTemplateTemplateParmPackStorage *Subst
6579 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6580
6581 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006582 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006583 ArgPack.pack_size(),
6584 ArgPack.pack_begin());
6585 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6586 }
6587
6588 return TemplateName(Subst);
6589}
6590
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006591/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006592/// TargetInfo, produce the corresponding type. The unsigned @p Type
6593/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006594CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006595 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006596 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006597 case TargetInfo::SignedChar: return SignedCharTy;
6598 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006599 case TargetInfo::SignedShort: return ShortTy;
6600 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6601 case TargetInfo::SignedInt: return IntTy;
6602 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6603 case TargetInfo::SignedLong: return LongTy;
6604 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6605 case TargetInfo::SignedLongLong: return LongLongTy;
6606 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6607 }
6608
David Blaikie83d382b2011-09-23 05:06:16 +00006609 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006610}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006611
6612//===----------------------------------------------------------------------===//
6613// Type Predicates.
6614//===----------------------------------------------------------------------===//
6615
Fariborz Jahanian96207692009-02-18 21:49:28 +00006616/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6617/// garbage collection attribute.
6618///
John McCall553d45a2011-01-12 00:34:59 +00006619Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006620 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006621 return Qualifiers::GCNone;
6622
David Blaikiebbafb8a2012-03-11 07:00:24 +00006623 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006624 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6625
6626 // Default behaviour under objective-C's gc is for ObjC pointers
6627 // (or pointers to them) be treated as though they were declared
6628 // as __strong.
6629 if (GCAttrs == Qualifiers::GCNone) {
6630 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6631 return Qualifiers::Strong;
6632 else if (Ty->isPointerType())
6633 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6634 } else {
6635 // It's not valid to set GC attributes on anything that isn't a
6636 // pointer.
6637#ifndef NDEBUG
6638 QualType CT = Ty->getCanonicalTypeInternal();
6639 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6640 CT = AT->getElementType();
6641 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6642#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006643 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006644 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006645}
6646
Chris Lattner49af6a42008-04-07 06:51:04 +00006647//===----------------------------------------------------------------------===//
6648// Type Compatibility Testing
6649//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006650
Mike Stump11289f42009-09-09 15:08:12 +00006651/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006652/// compatible.
6653static bool areCompatVectorTypes(const VectorType *LHS,
6654 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006655 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006656 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006657 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006658}
6659
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006660bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6661 QualType SecondVec) {
6662 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6663 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6664
6665 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6666 return true;
6667
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006668 // Treat Neon vector types and most AltiVec vector types as if they are the
6669 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006670 const VectorType *First = FirstVec->getAs<VectorType>();
6671 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006672 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006673 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006674 First->getVectorKind() != VectorType::AltiVecPixel &&
6675 First->getVectorKind() != VectorType::AltiVecBool &&
6676 Second->getVectorKind() != VectorType::AltiVecPixel &&
6677 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006678 return true;
6679
6680 return false;
6681}
6682
Steve Naroff8e6aee52009-07-23 01:01:38 +00006683//===----------------------------------------------------------------------===//
6684// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6685//===----------------------------------------------------------------------===//
6686
6687/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6688/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006689bool
6690ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6691 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006692 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006693 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006694 for (auto *PI : rProto->protocols())
6695 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006696 return true;
6697 return false;
6698}
6699
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006700/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6701/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006702bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6703 QualType rhs) {
6704 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6705 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6706 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6707
Aaron Ballman83731462014-03-17 16:14:00 +00006708 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006709 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006710 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006711 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6712 match = true;
6713 break;
6714 }
6715 }
6716 if (!match)
6717 return false;
6718 }
6719 return true;
6720}
6721
Steve Naroff8e6aee52009-07-23 01:01:38 +00006722/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6723/// ObjCQualifiedIDType.
6724bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6725 bool compare) {
6726 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006727 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006728 lhs->isObjCIdType() || lhs->isObjCClassType())
6729 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006730 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006731 rhs->isObjCIdType() || rhs->isObjCClassType())
6732 return true;
6733
6734 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006735 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006736
Steve Naroff8e6aee52009-07-23 01:01:38 +00006737 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006738
Steve Naroff8e6aee52009-07-23 01:01:38 +00006739 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006740 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006741 // make sure we check the class hierarchy.
6742 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006743 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006744 // when comparing an id<P> on lhs with a static type on rhs,
6745 // see if static class implements all of id's protocols, directly or
6746 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006747 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006748 return false;
6749 }
6750 }
6751 // If there are no qualifiers and no interface, we have an 'id'.
6752 return true;
6753 }
Mike Stump11289f42009-09-09 15:08:12 +00006754 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006755 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006756 bool match = false;
6757
6758 // when comparing an id<P> on lhs with a static type on rhs,
6759 // see if static class implements all of id's protocols, directly or
6760 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006761 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006762 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6763 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6764 match = true;
6765 break;
6766 }
6767 }
Mike Stump11289f42009-09-09 15:08:12 +00006768 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006769 // make sure we check the class hierarchy.
6770 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006771 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006772 // when comparing an id<P> on lhs with a static type on rhs,
6773 // see if static class implements all of id's protocols, directly or
6774 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006775 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006776 match = true;
6777 break;
6778 }
6779 }
6780 }
6781 if (!match)
6782 return false;
6783 }
Mike Stump11289f42009-09-09 15:08:12 +00006784
Steve Naroff8e6aee52009-07-23 01:01:38 +00006785 return true;
6786 }
Mike Stump11289f42009-09-09 15:08:12 +00006787
Steve Naroff8e6aee52009-07-23 01:01:38 +00006788 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6789 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6790
Mike Stump11289f42009-09-09 15:08:12 +00006791 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006792 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006793 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006794 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006795 bool match = false;
6796
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006797 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006798 // see if static class implements all of id's protocols, directly or
6799 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006800 // First, lhs protocols in the qualifier list must be found, direct
6801 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006802 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006803 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6804 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6805 match = true;
6806 break;
6807 }
6808 }
6809 if (!match)
6810 return false;
6811 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006812
6813 // Static class's protocols, or its super class or category protocols
6814 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6815 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6816 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6817 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6818 // This is rather dubious but matches gcc's behavior. If lhs has
6819 // no type qualifier and its class has no static protocol(s)
6820 // assume that it is mismatch.
6821 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6822 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006823 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006824 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006825 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006826 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6827 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6828 match = true;
6829 break;
6830 }
6831 }
6832 if (!match)
6833 return false;
6834 }
6835 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006836 return true;
6837 }
6838 return false;
6839}
6840
Eli Friedman47f77112008-08-22 00:56:42 +00006841/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006842/// compatible for assignment from RHS to LHS. This handles validation of any
6843/// protocol qualifiers on the LHS or RHS.
6844///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006845bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6846 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006847 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6848 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6849
Steve Naroff1329fa02009-07-15 18:40:39 +00006850 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006851 if (LHS->isObjCUnqualifiedIdOrClass() ||
6852 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006853 return true;
6854
Douglas Gregorab209d82015-07-07 03:58:42 +00006855 // Function object that propagates a successful result or handles
6856 // __kindof types.
6857 auto finish = [&](bool succeeded) -> bool {
6858 if (succeeded)
6859 return true;
6860
6861 if (!RHS->isKindOfType())
6862 return false;
6863
6864 // Strip off __kindof and protocol qualifiers, then check whether
6865 // we can assign the other way.
6866 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6867 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6868 };
6869
6870 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6871 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6872 QualType(RHSOPT,0),
6873 false));
6874 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006875
Douglas Gregorab209d82015-07-07 03:58:42 +00006876 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6877 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6878 QualType(RHSOPT,0)));
6879 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006880
John McCall8b07ec22010-05-15 11:32:37 +00006881 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006882 if (LHS->getInterface() && RHS->getInterface()) {
6883 return finish(canAssignObjCInterfaces(LHS, RHS));
6884 }
Mike Stump11289f42009-09-09 15:08:12 +00006885
Steve Naroff8e6aee52009-07-23 01:01:38 +00006886 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006887}
6888
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006889/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006890/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006891/// arguments in block literals. When passed as arguments, passing 'A*' where
6892/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6893/// not OK. For the return type, the opposite is not OK.
6894bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6895 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006896 const ObjCObjectPointerType *RHSOPT,
6897 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006898
6899 // Function object that propagates a successful result or handles
6900 // __kindof types.
6901 auto finish = [&](bool succeeded) -> bool {
6902 if (succeeded)
6903 return true;
6904
6905 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6906 if (!Expected->isKindOfType())
6907 return false;
6908
6909 // Strip off __kindof and protocol qualifiers, then check whether
6910 // we can assign the other way.
6911 return canAssignObjCInterfacesInBlockPointer(
6912 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6913 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6914 BlockReturnType);
6915 };
6916
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006917 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006918 return true;
6919
6920 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006921 return finish(RHSOPT->isObjCBuiltinType() ||
6922 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006923 }
6924
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006925 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006926 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6927 QualType(RHSOPT,0),
6928 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006929
6930 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6931 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6932 if (LHS && RHS) { // We have 2 user-defined types.
6933 if (LHS != RHS) {
6934 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006935 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006936 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006937 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006938 }
6939 else
6940 return true;
6941 }
6942 return false;
6943}
6944
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006945/// Comparison routine for Objective-C protocols to be used with
6946/// llvm::array_pod_sort.
6947static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6948 ObjCProtocolDecl * const *rhs) {
6949 return (*lhs)->getName().compare((*rhs)->getName());
6950
6951}
6952
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006953/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006954/// of protocols inherited from two distinct objective-c pointer objects with
6955/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006956/// It is used to build composite qualifier list of the composite type of
6957/// the conditional expression involving two objective-c pointer objects.
6958static
6959void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006960 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006961 const ObjCObjectPointerType *LHSOPT,
6962 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006963 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006964
John McCall8b07ec22010-05-15 11:32:37 +00006965 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6966 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6967 assert(LHS->getInterface() && "LHS must have an interface base");
6968 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006969
6970 // Add all of the protocols for the LHS.
6971 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6972
6973 // Start with the protocol qualifiers.
6974 for (auto proto : LHS->quals()) {
6975 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006976 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006977
6978 // Also add the protocols associated with the LHS interface.
6979 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6980
6981 // Add all of the protocls for the RHS.
6982 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6983
6984 // Start with the protocol qualifiers.
6985 for (auto proto : RHS->quals()) {
6986 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006987 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006988
6989 // Also add the protocols associated with the RHS interface.
6990 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6991
6992 // Compute the intersection of the collected protocol sets.
6993 for (auto proto : LHSProtocolSet) {
6994 if (RHSProtocolSet.count(proto))
6995 IntersectionSet.push_back(proto);
6996 }
6997
6998 // Compute the set of protocols that is implied by either the common type or
6999 // the protocols within the intersection.
7000 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7001 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7002
7003 // Remove any implied protocols from the list of inherited protocols.
7004 if (!ImpliedProtocols.empty()) {
7005 IntersectionSet.erase(
7006 std::remove_if(IntersectionSet.begin(),
7007 IntersectionSet.end(),
7008 [&](ObjCProtocolDecl *proto) -> bool {
7009 return ImpliedProtocols.count(proto) > 0;
7010 }),
7011 IntersectionSet.end());
7012 }
7013
7014 // Sort the remaining protocols by name.
7015 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7016 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007017}
7018
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007019/// Determine whether the first type is a subtype of the second.
7020static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7021 QualType rhs) {
7022 // Common case: two object pointers.
7023 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7024 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7025 if (lhsOPT && rhsOPT)
7026 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7027
7028 // Two block pointers.
7029 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7030 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7031 if (lhsBlock && rhsBlock)
7032 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7033
7034 // If either is an unqualified 'id' and the other is a block, it's
7035 // acceptable.
7036 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7037 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7038 return true;
7039
7040 return false;
7041}
7042
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007043// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007044static bool sameObjCTypeArgs(ASTContext &ctx,
7045 const ObjCInterfaceDecl *iface,
7046 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007047 ArrayRef<QualType> rhsArgs,
7048 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007049 if (lhsArgs.size() != rhsArgs.size())
7050 return false;
7051
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007052 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007053 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007054 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7055 continue;
7056
7057 switch (typeParams->begin()[i]->getVariance()) {
7058 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007059 if (!stripKindOf ||
7060 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7061 rhsArgs[i].stripObjCKindOfType(ctx))) {
7062 return false;
7063 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007064 break;
7065
7066 case ObjCTypeParamVariance::Covariant:
7067 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7068 return false;
7069 break;
7070
7071 case ObjCTypeParamVariance::Contravariant:
7072 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7073 return false;
7074 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007075 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007076 }
7077
7078 return true;
7079}
7080
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007081QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007082 const ObjCObjectPointerType *Lptr,
7083 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007084 const ObjCObjectType *LHS = Lptr->getObjectType();
7085 const ObjCObjectType *RHS = Rptr->getObjectType();
7086 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7087 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007088
7089 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007090 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007091
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007092 // Follow the left-hand side up the class hierarchy until we either hit a
7093 // root or find the RHS. Record the ancestors in case we don't find it.
7094 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7095 LHSAncestors;
7096 while (true) {
7097 // Record this ancestor. We'll need this if the common type isn't in the
7098 // path from the LHS to the root.
7099 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007100
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007101 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7102 // Get the type arguments.
7103 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7104 bool anyChanges = false;
7105 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7106 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007107 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7108 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007109 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007110 return QualType();
7111 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7112 // If only one has type arguments, the result will not have type
7113 // arguments.
7114 LHSTypeArgs = { };
7115 anyChanges = true;
7116 }
7117
7118 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007119 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007120 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7121 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007122 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007123 anyChanges = true;
7124
7125 // If anything in the LHS will have changed, build a new result type.
7126 if (anyChanges) {
7127 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007128 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7129 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007130 return getObjCObjectPointerType(Result);
7131 }
7132
7133 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007134 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007135
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007136 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007137 QualType LHSSuperType = LHS->getSuperClassType();
7138 if (LHSSuperType.isNull())
7139 break;
7140
7141 LHS = LHSSuperType->castAs<ObjCObjectType>();
7142 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007143
7144 // We didn't find anything by following the LHS to its root; now check
7145 // the RHS against the cached set of ancestors.
7146 while (true) {
7147 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7148 if (KnownLHS != LHSAncestors.end()) {
7149 LHS = KnownLHS->second;
7150
7151 // Get the type arguments.
7152 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7153 bool anyChanges = false;
7154 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7155 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007156 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7157 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007158 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007159 return QualType();
7160 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7161 // If only one has type arguments, the result will not have type
7162 // arguments.
7163 RHSTypeArgs = { };
7164 anyChanges = true;
7165 }
7166
7167 // Compute the intersection of protocols.
7168 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7169 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7170 Protocols);
7171 if (!Protocols.empty())
7172 anyChanges = true;
7173
7174 if (anyChanges) {
7175 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007176 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7177 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007178 return getObjCObjectPointerType(Result);
7179 }
7180
7181 return getObjCObjectPointerType(QualType(RHS, 0));
7182 }
7183
7184 // Find the superclass of the RHS.
7185 QualType RHSSuperType = RHS->getSuperClassType();
7186 if (RHSSuperType.isNull())
7187 break;
7188
7189 RHS = RHSSuperType->castAs<ObjCObjectType>();
7190 }
7191
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007192 return QualType();
7193}
7194
John McCall8b07ec22010-05-15 11:32:37 +00007195bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7196 const ObjCObjectType *RHS) {
7197 assert(LHS->getInterface() && "LHS is not an interface type");
7198 assert(RHS->getInterface() && "RHS is not an interface type");
7199
Chris Lattner49af6a42008-04-07 06:51:04 +00007200 // Verify that the base decls are compatible: the RHS must be a subclass of
7201 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007202 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7203 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7204 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007205 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007206
Douglas Gregore83b9562015-07-07 03:57:53 +00007207 // If the LHS has protocol qualifiers, determine whether all of them are
7208 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7209 // LHS).
7210 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007211 // OK if conversion of LHS to SuperClass results in narrowing of types
7212 // ; i.e., SuperClass may implement at least one of the protocols
7213 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7214 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7215 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7216 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7217 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7218 // qualifiers.
7219 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007220 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007221 // If there is no protocols associated with RHS, it is not a match.
7222 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007223 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007224
7225 for (const auto *LHSProto : LHS->quals()) {
7226 bool SuperImplementsProtocol = false;
7227 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7228 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7229 SuperImplementsProtocol = true;
7230 break;
7231 }
7232 if (!SuperImplementsProtocol)
7233 return false;
7234 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007235 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007236
7237 // If the LHS is specialized, we may need to check type arguments.
7238 if (LHS->isSpecialized()) {
7239 // Follow the superclass chain until we've matched the LHS class in the
7240 // hierarchy. This substitutes type arguments through.
7241 const ObjCObjectType *RHSSuper = RHS;
7242 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7243 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7244
7245 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007246 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007247 !sameObjCTypeArgs(*this, LHS->getInterface(),
7248 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007249 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007250 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007251 }
7252 }
7253
7254 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007255}
7256
Steve Naroffb7605152009-02-12 17:52:19 +00007257bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7258 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007259 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7260 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007261
Steve Naroff7cae42b2009-07-10 23:34:53 +00007262 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007263 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007264
7265 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7266 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007267}
7268
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007269bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7270 return canAssignObjCInterfaces(
7271 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7272 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7273}
7274
Mike Stump11289f42009-09-09 15:08:12 +00007275/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007276/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007277/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007278/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007279bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7280 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007281 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007282 return hasSameType(LHS, RHS);
7283
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007284 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007285}
7286
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007287bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007288 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007289}
7290
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007291bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7292 return !mergeTypes(LHS, RHS, true).isNull();
7293}
7294
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007295/// mergeTransparentUnionType - if T is a transparent union type and a member
7296/// of T is compatible with SubType, return the merged type, else return
7297/// QualType()
7298QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7299 bool OfBlockPointer,
7300 bool Unqualified) {
7301 if (const RecordType *UT = T->getAsUnionType()) {
7302 RecordDecl *UD = UT->getDecl();
7303 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007304 for (const auto *I : UD->fields()) {
7305 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007306 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7307 if (!MT.isNull())
7308 return MT;
7309 }
7310 }
7311 }
7312
7313 return QualType();
7314}
7315
Alp Toker9cacbab2014-01-20 20:26:09 +00007316/// mergeFunctionParameterTypes - merge two types which appear as function
7317/// parameter types
7318QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7319 bool OfBlockPointer,
7320 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007321 // GNU extension: two types are compatible if they appear as a function
7322 // argument, one of the types is a transparent union type and the other
7323 // type is compatible with a union member
7324 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7325 Unqualified);
7326 if (!lmerge.isNull())
7327 return lmerge;
7328
7329 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7330 Unqualified);
7331 if (!rmerge.isNull())
7332 return rmerge;
7333
7334 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7335}
7336
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007337QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007338 bool OfBlockPointer,
7339 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007340 const FunctionType *lbase = lhs->getAs<FunctionType>();
7341 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007342 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7343 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007344 bool allLTypes = true;
7345 bool allRTypes = true;
7346
7347 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007348 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007349 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007350 QualType RHS = rbase->getReturnType();
7351 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007352 bool UnqualifiedResult = Unqualified;
7353 if (!UnqualifiedResult)
7354 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007355 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007356 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007357 else
Alp Toker314cc812014-01-25 16:55:45 +00007358 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007359 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007360 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007361
7362 if (Unqualified)
7363 retType = retType.getUnqualifiedType();
7364
Alp Toker314cc812014-01-25 16:55:45 +00007365 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7366 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007367 if (Unqualified) {
7368 LRetType = LRetType.getUnqualifiedType();
7369 RRetType = RRetType.getUnqualifiedType();
7370 }
7371
7372 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007373 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007374 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007375 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007376
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007377 // FIXME: double check this
7378 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7379 // rbase->getRegParmAttr() != 0 &&
7380 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007381 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7382 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007383
Douglas Gregor8c940862010-01-18 17:14:39 +00007384 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007385 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007386 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007387
John McCall8c6b56f2010-12-15 01:06:38 +00007388 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007389 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7390 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007391 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7392 return QualType();
7393
John McCall31168b02011-06-15 23:02:42 +00007394 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7395 return QualType();
7396
John McCall8c6b56f2010-12-15 01:06:38 +00007397 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7398 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007399
Rafael Espindola8778c282012-11-29 16:09:03 +00007400 if (lbaseInfo.getNoReturn() != NoReturn)
7401 allLTypes = false;
7402 if (rbaseInfo.getNoReturn() != NoReturn)
7403 allRTypes = false;
7404
John McCall31168b02011-06-15 23:02:42 +00007405 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007406
Eli Friedman47f77112008-08-22 00:56:42 +00007407 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007408 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7409 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007410 // Compatible functions must have the same number of parameters
7411 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007412 return QualType();
7413
7414 // Variadic and non-variadic functions aren't compatible
7415 if (lproto->isVariadic() != rproto->isVariadic())
7416 return QualType();
7417
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007418 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7419 return QualType();
7420
Fariborz Jahanian97676972011-09-28 21:52:05 +00007421 if (LangOpts.ObjCAutoRefCount &&
7422 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7423 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007424
7425 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007426 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007427 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7428 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7429 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7430 QualType paramType = mergeFunctionParameterTypes(
7431 lParamType, rParamType, OfBlockPointer, Unqualified);
7432 if (paramType.isNull())
7433 return QualType();
7434
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007435 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007436 paramType = paramType.getUnqualifiedType();
7437
7438 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007439 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007440 lParamType = lParamType.getUnqualifiedType();
7441 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007442 }
Alp Toker601b22c2014-01-21 23:35:24 +00007443
7444 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007445 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007446 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007447 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007448 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007449
Eli Friedman47f77112008-08-22 00:56:42 +00007450 if (allLTypes) return lhs;
7451 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007452
7453 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7454 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007455 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007456 }
7457
7458 if (lproto) allRTypes = false;
7459 if (rproto) allLTypes = false;
7460
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007461 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007462 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007463 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007464 if (proto->isVariadic()) return QualType();
7465 // Check that the types are compatible with the types that
7466 // would result from default argument promotions (C99 6.7.5.3p15).
7467 // The only types actually affected are promotable integer
7468 // types and floats, which would be passed as a different
7469 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007470 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7471 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007472
Eli Friedman448ce402012-08-30 00:44:15 +00007473 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007474 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007475 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7476 paramTy = Enum->getDecl()->getIntegerType();
7477 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007478 return QualType();
7479 }
Alp Toker601b22c2014-01-21 23:35:24 +00007480
7481 if (paramTy->isPromotableIntegerType() ||
7482 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007483 return QualType();
7484 }
7485
7486 if (allLTypes) return lhs;
7487 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007488
7489 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7490 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007491 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007492 }
7493
7494 if (allLTypes) return lhs;
7495 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007496 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007497}
7498
John McCall433c2e62013-03-21 00:10:07 +00007499/// Given that we have an enum type and a non-enum type, try to merge them.
7500static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7501 QualType other, bool isBlockReturnType) {
7502 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7503 // a signed integer type, or an unsigned integer type.
7504 // Compatibility is based on the underlying type, not the promotion
7505 // type.
7506 QualType underlyingType = ET->getDecl()->getIntegerType();
7507 if (underlyingType.isNull()) return QualType();
7508 if (Context.hasSameType(underlyingType, other))
7509 return other;
7510
7511 // In block return types, we're more permissive and accept any
7512 // integral type of the same size.
7513 if (isBlockReturnType && other->isIntegerType() &&
7514 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7515 return other;
7516
7517 return QualType();
7518}
7519
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007520QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007521 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007522 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007523 // C++ [expr]: If an expression initially has the type "reference to T", the
7524 // type is adjusted to "T" prior to any further analysis, the expression
7525 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007526 // expression is an lvalue unless the reference is an rvalue reference and
7527 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007528 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7529 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007530
7531 if (Unqualified) {
7532 LHS = LHS.getUnqualifiedType();
7533 RHS = RHS.getUnqualifiedType();
7534 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007535
Eli Friedman47f77112008-08-22 00:56:42 +00007536 QualType LHSCan = getCanonicalType(LHS),
7537 RHSCan = getCanonicalType(RHS);
7538
7539 // If two types are identical, they are compatible.
7540 if (LHSCan == RHSCan)
7541 return LHS;
7542
John McCall8ccfcb52009-09-24 19:53:00 +00007543 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007544 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7545 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007546 if (LQuals != RQuals) {
7547 // If any of these qualifiers are different, we have a type
7548 // mismatch.
7549 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007550 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7551 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007552 return QualType();
7553
7554 // Exactly one GC qualifier difference is allowed: __strong is
7555 // okay if the other type has no GC qualifier but is an Objective
7556 // C object pointer (i.e. implicitly strong by default). We fix
7557 // this by pretending that the unqualified type was actually
7558 // qualified __strong.
7559 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7560 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7561 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7562
7563 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7564 return QualType();
7565
7566 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7567 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7568 }
7569 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7570 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7571 }
Eli Friedman47f77112008-08-22 00:56:42 +00007572 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007573 }
7574
7575 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007576
Eli Friedmandcca6332009-06-01 01:22:52 +00007577 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7578 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007579
Chris Lattnerfd652912008-01-14 05:45:46 +00007580 // We want to consider the two function types to be the same for these
7581 // comparisons, just force one to the other.
7582 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7583 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007584
7585 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007586 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7587 LHSClass = Type::ConstantArray;
7588 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7589 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007590
John McCall8b07ec22010-05-15 11:32:37 +00007591 // ObjCInterfaces are just specialized ObjCObjects.
7592 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7593 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7594
Nate Begemance4d7fc2008-04-18 23:10:10 +00007595 // Canonicalize ExtVector -> Vector.
7596 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7597 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007598
Chris Lattner95554662008-04-07 05:43:21 +00007599 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007600 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007601 // Note that we only have special rules for turning block enum
7602 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007603 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007604 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007605 }
John McCall9dd450b2009-09-21 23:43:11 +00007606 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007607 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007608 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007609 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007610 if (OfBlockPointer && !BlockReturnType) {
7611 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7612 return LHS;
7613 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7614 return RHS;
7615 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007616
Eli Friedman47f77112008-08-22 00:56:42 +00007617 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007618 }
Eli Friedman47f77112008-08-22 00:56:42 +00007619
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007620 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007621 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007622#define TYPE(Class, Base)
7623#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007624#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007625#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7626#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7627#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007628 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007629
Richard Smith27d807c2013-04-30 13:56:41 +00007630 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007631 case Type::LValueReference:
7632 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007633 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007634 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007635
John McCall8b07ec22010-05-15 11:32:37 +00007636 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007637 case Type::IncompleteArray:
7638 case Type::VariableArray:
7639 case Type::FunctionProto:
7640 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007641 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007642
Chris Lattnerfd652912008-01-14 05:45:46 +00007643 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007644 {
7645 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007646 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7647 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007648 if (Unqualified) {
7649 LHSPointee = LHSPointee.getUnqualifiedType();
7650 RHSPointee = RHSPointee.getUnqualifiedType();
7651 }
7652 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7653 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007654 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007655 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007656 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007657 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007658 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007659 return getPointerType(ResultType);
7660 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007661 case Type::BlockPointer:
7662 {
7663 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007664 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7665 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007666 if (Unqualified) {
7667 LHSPointee = LHSPointee.getUnqualifiedType();
7668 RHSPointee = RHSPointee.getUnqualifiedType();
7669 }
7670 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7671 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007672 if (ResultType.isNull()) return QualType();
7673 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7674 return LHS;
7675 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7676 return RHS;
7677 return getBlockPointerType(ResultType);
7678 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007679 case Type::Atomic:
7680 {
7681 // Merge two pointer types, while trying to preserve typedef info
7682 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7683 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7684 if (Unqualified) {
7685 LHSValue = LHSValue.getUnqualifiedType();
7686 RHSValue = RHSValue.getUnqualifiedType();
7687 }
7688 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7689 Unqualified);
7690 if (ResultType.isNull()) return QualType();
7691 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7692 return LHS;
7693 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7694 return RHS;
7695 return getAtomicType(ResultType);
7696 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007697 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007698 {
7699 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7700 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7701 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7702 return QualType();
7703
7704 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7705 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007706 if (Unqualified) {
7707 LHSElem = LHSElem.getUnqualifiedType();
7708 RHSElem = RHSElem.getUnqualifiedType();
7709 }
7710
7711 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007712 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007713 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7714 return LHS;
7715 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7716 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007717 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7718 ArrayType::ArraySizeModifier(), 0);
7719 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7720 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007721 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7722 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007723 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7724 return LHS;
7725 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7726 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007727 if (LVAT) {
7728 // FIXME: This isn't correct! But tricky to implement because
7729 // the array's size has to be the size of LHS, but the type
7730 // has to be different.
7731 return LHS;
7732 }
7733 if (RVAT) {
7734 // FIXME: This isn't correct! But tricky to implement because
7735 // the array's size has to be the size of RHS, but the type
7736 // has to be different.
7737 return RHS;
7738 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007739 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7740 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007741 return getIncompleteArrayType(ResultType,
7742 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007743 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007744 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007745 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007746 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007747 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007748 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007749 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007750 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007751 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007752 case Type::Complex:
7753 // Distinct complex types are incompatible.
7754 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007755 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007756 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007757 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7758 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007759 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007760 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007761 case Type::ObjCObject: {
7762 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007763 // FIXME: This should be type compatibility, e.g. whether
7764 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007765 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7766 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7767 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007768 return LHS;
7769
Eli Friedman47f77112008-08-22 00:56:42 +00007770 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007771 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007772 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007773 if (OfBlockPointer) {
7774 if (canAssignObjCInterfacesInBlockPointer(
7775 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007776 RHS->getAs<ObjCObjectPointerType>(),
7777 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007778 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007779 return QualType();
7780 }
John McCall9dd450b2009-09-21 23:43:11 +00007781 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7782 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007783 return LHS;
7784
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007785 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007786 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007787 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007788
David Blaikie8a40f702012-01-17 06:56:22 +00007789 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007790}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007791
Fariborz Jahanian97676972011-09-28 21:52:05 +00007792bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7793 const FunctionProtoType *FromFunctionType,
7794 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007795 if (FromFunctionType->hasAnyConsumedParams() !=
7796 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007797 return false;
7798 FunctionProtoType::ExtProtoInfo FromEPI =
7799 FromFunctionType->getExtProtoInfo();
7800 FunctionProtoType::ExtProtoInfo ToEPI =
7801 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007802 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007803 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7804 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007805 return false;
7806 }
7807 return true;
7808}
7809
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007810/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7811/// 'RHS' attributes and returns the merged version; including for function
7812/// return types.
7813QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7814 QualType LHSCan = getCanonicalType(LHS),
7815 RHSCan = getCanonicalType(RHS);
7816 // If two types are identical, they are compatible.
7817 if (LHSCan == RHSCan)
7818 return LHS;
7819 if (RHSCan->isFunctionType()) {
7820 if (!LHSCan->isFunctionType())
7821 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007822 QualType OldReturnType =
7823 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007824 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007825 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007826 QualType ResReturnType =
7827 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7828 if (ResReturnType.isNull())
7829 return QualType();
7830 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7831 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7832 // In either case, use OldReturnType to build the new function type.
7833 const FunctionType *F = LHS->getAs<FunctionType>();
7834 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007835 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7836 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007837 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007838 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007839 return ResultType;
7840 }
7841 }
7842 return QualType();
7843 }
7844
7845 // If the qualifiers are different, the types can still be merged.
7846 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7847 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7848 if (LQuals != RQuals) {
7849 // If any of these qualifiers are different, we have a type mismatch.
7850 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7851 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7852 return QualType();
7853
7854 // Exactly one GC qualifier difference is allowed: __strong is
7855 // okay if the other type has no GC qualifier but is an Objective
7856 // C object pointer (i.e. implicitly strong by default). We fix
7857 // this by pretending that the unqualified type was actually
7858 // qualified __strong.
7859 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7860 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7861 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7862
7863 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7864 return QualType();
7865
7866 if (GC_L == Qualifiers::Strong)
7867 return LHS;
7868 if (GC_R == Qualifiers::Strong)
7869 return RHS;
7870 return QualType();
7871 }
7872
7873 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7874 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7875 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7876 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7877 if (ResQT == LHSBaseQT)
7878 return LHS;
7879 if (ResQT == RHSBaseQT)
7880 return RHS;
7881 }
7882 return QualType();
7883}
7884
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007885//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007886// Integer Predicates
7887//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007888
Jay Foad39c79802011-01-12 09:06:06 +00007889unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007890 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007891 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007892 if (T->isBooleanType())
7893 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007894 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007895 return (unsigned)getTypeSize(T);
7896}
7897
Abramo Bagnara13640492012-09-09 10:21:24 +00007898QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007899 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007900
7901 // Turn <4 x signed int> -> <4 x unsigned int>
7902 if (const VectorType *VTy = T->getAs<VectorType>())
7903 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007904 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007905
7906 // For enums, we return the unsigned version of the base type.
7907 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007908 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007909
7910 const BuiltinType *BTy = T->getAs<BuiltinType>();
7911 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007912 switch (BTy->getKind()) {
7913 case BuiltinType::Char_S:
7914 case BuiltinType::SChar:
7915 return UnsignedCharTy;
7916 case BuiltinType::Short:
7917 return UnsignedShortTy;
7918 case BuiltinType::Int:
7919 return UnsignedIntTy;
7920 case BuiltinType::Long:
7921 return UnsignedLongTy;
7922 case BuiltinType::LongLong:
7923 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007924 case BuiltinType::Int128:
7925 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007926 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007927 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007928 }
7929}
7930
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00007931ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007932
Richard Smith1fa5d642013-05-11 05:45:24 +00007933void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7934 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007935
7936//===----------------------------------------------------------------------===//
7937// Builtin Type Computation
7938//===----------------------------------------------------------------------===//
7939
7940/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007941/// pointer over the consumed characters. This returns the resultant type. If
7942/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7943/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7944/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007945///
7946/// RequiresICE is filled in on return to indicate whether the value is required
7947/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007948static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007949 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007950 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007951 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007952 // Modifiers.
7953 int HowLong = 0;
7954 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007955 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007956
Chris Lattnerdc226c22010-10-01 22:42:38 +00007957 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007958 bool Done = false;
7959 while (!Done) {
7960 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007961 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007962 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007963 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007964 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007965 case 'S':
7966 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7967 assert(!Signed && "Can't use 'S' modifier multiple times!");
7968 Signed = true;
7969 break;
7970 case 'U':
7971 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007972 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007973 Unsigned = true;
7974 break;
7975 case 'L':
7976 assert(HowLong <= 2 && "Can't have LLLL modifier");
7977 ++HowLong;
7978 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007979 case 'W':
7980 // This modifier represents int64 type.
7981 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7982 switch (Context.getTargetInfo().getInt64Type()) {
7983 default:
7984 llvm_unreachable("Unexpected integer type");
7985 case TargetInfo::SignedLong:
7986 HowLong = 1;
7987 break;
7988 case TargetInfo::SignedLongLong:
7989 HowLong = 2;
7990 break;
7991 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007992 }
7993 }
7994
7995 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007996
Chris Lattnerecd79c62009-06-14 00:45:47 +00007997 // Read the base type.
7998 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007999 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008000 case 'v':
8001 assert(HowLong == 0 && !Signed && !Unsigned &&
8002 "Bad modifiers used with 'v'!");
8003 Type = Context.VoidTy;
8004 break;
Jack Carter24bef982013-08-15 15:16:57 +00008005 case 'h':
8006 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008007 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008008 Type = Context.HalfTy;
8009 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008010 case 'f':
8011 assert(HowLong == 0 && !Signed && !Unsigned &&
8012 "Bad modifiers used with 'f'!");
8013 Type = Context.FloatTy;
8014 break;
8015 case 'd':
8016 assert(HowLong < 2 && !Signed && !Unsigned &&
8017 "Bad modifiers used with 'd'!");
8018 if (HowLong)
8019 Type = Context.LongDoubleTy;
8020 else
8021 Type = Context.DoubleTy;
8022 break;
8023 case 's':
8024 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8025 if (Unsigned)
8026 Type = Context.UnsignedShortTy;
8027 else
8028 Type = Context.ShortTy;
8029 break;
8030 case 'i':
8031 if (HowLong == 3)
8032 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8033 else if (HowLong == 2)
8034 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8035 else if (HowLong == 1)
8036 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8037 else
8038 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8039 break;
8040 case 'c':
8041 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8042 if (Signed)
8043 Type = Context.SignedCharTy;
8044 else if (Unsigned)
8045 Type = Context.UnsignedCharTy;
8046 else
8047 Type = Context.CharTy;
8048 break;
8049 case 'b': // boolean
8050 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8051 Type = Context.BoolTy;
8052 break;
8053 case 'z': // size_t.
8054 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8055 Type = Context.getSizeType();
8056 break;
8057 case 'F':
8058 Type = Context.getCFConstantStringType();
8059 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008060 case 'G':
8061 Type = Context.getObjCIdType();
8062 break;
8063 case 'H':
8064 Type = Context.getObjCSelType();
8065 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008066 case 'M':
8067 Type = Context.getObjCSuperType();
8068 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008069 case 'a':
8070 Type = Context.getBuiltinVaListType();
8071 assert(!Type.isNull() && "builtin va list type not initialized!");
8072 break;
8073 case 'A':
8074 // This is a "reference" to a va_list; however, what exactly
8075 // this means depends on how va_list is defined. There are two
8076 // different kinds of va_list: ones passed by value, and ones
8077 // passed by reference. An example of a by-value va_list is
8078 // x86, where va_list is a char*. An example of by-ref va_list
8079 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8080 // we want this argument to be a char*&; for x86-64, we want
8081 // it to be a __va_list_tag*.
8082 Type = Context.getBuiltinVaListType();
8083 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008084 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008085 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008086 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008087 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008088 break;
8089 case 'V': {
8090 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008091 unsigned NumElements = strtoul(Str, &End, 10);
8092 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008093 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008094
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008095 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8096 RequiresICE, false);
8097 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008098
8099 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008100 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008101 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008102 break;
8103 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008104 case 'E': {
8105 char *End;
8106
8107 unsigned NumElements = strtoul(Str, &End, 10);
8108 assert(End != Str && "Missing vector size");
8109
8110 Str = End;
8111
8112 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8113 false);
8114 Type = Context.getExtVectorType(ElementType, NumElements);
8115 break;
8116 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008117 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008118 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8119 false);
8120 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008121 Type = Context.getComplexType(ElementType);
8122 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008123 }
8124 case 'Y' : {
8125 Type = Context.getPointerDiffType();
8126 break;
8127 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008128 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008129 Type = Context.getFILEType();
8130 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008131 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008132 return QualType();
8133 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008134 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008135 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008136 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008137 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008138 else
8139 Type = Context.getjmp_bufType();
8140
Mike Stump2adb4da2009-07-28 23:47:15 +00008141 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008142 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008143 return QualType();
8144 }
8145 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008146 case 'K':
8147 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8148 Type = Context.getucontext_tType();
8149
8150 if (Type.isNull()) {
8151 Error = ASTContext::GE_Missing_ucontext;
8152 return QualType();
8153 }
8154 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008155 case 'p':
8156 Type = Context.getProcessIDType();
8157 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008158 }
Mike Stump11289f42009-09-09 15:08:12 +00008159
Chris Lattnerdc226c22010-10-01 22:42:38 +00008160 // If there are modifiers and if we're allowed to parse them, go for it.
8161 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008162 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008163 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008164 default: Done = true; --Str; break;
8165 case '*':
8166 case '&': {
8167 // Both pointers and references can have their pointee types
8168 // qualified with an address space.
8169 char *End;
8170 unsigned AddrSpace = strtoul(Str, &End, 10);
8171 if (End != Str && AddrSpace != 0) {
8172 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8173 Str = End;
8174 }
8175 if (c == '*')
8176 Type = Context.getPointerType(Type);
8177 else
8178 Type = Context.getLValueReferenceType(Type);
8179 break;
8180 }
8181 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8182 case 'C':
8183 Type = Type.withConst();
8184 break;
8185 case 'D':
8186 Type = Context.getVolatileType(Type);
8187 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008188 case 'R':
8189 Type = Type.withRestrict();
8190 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008191 }
8192 }
Chris Lattner84733392010-10-01 07:13:18 +00008193
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008194 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008195 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008196
Chris Lattnerecd79c62009-06-14 00:45:47 +00008197 return Type;
8198}
8199
8200/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008201QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008202 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008203 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008204 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008205
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008206 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008207
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008208 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008209 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008210 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8211 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008212 if (Error != GE_None)
8213 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008214
8215 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8216
Chris Lattnerecd79c62009-06-14 00:45:47 +00008217 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008218 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008219 if (Error != GE_None)
8220 return QualType();
8221
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008222 // If this argument is required to be an IntegerConstantExpression and the
8223 // caller cares, fill in the bitmask we return.
8224 if (RequiresICE && IntegerConstantArgs)
8225 *IntegerConstantArgs |= 1 << ArgTypes.size();
8226
Chris Lattnerecd79c62009-06-14 00:45:47 +00008227 // Do array -> pointer decay. The builtin should use the decayed type.
8228 if (Ty->isArrayType())
8229 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008230
Chris Lattnerecd79c62009-06-14 00:45:47 +00008231 ArgTypes.push_back(Ty);
8232 }
8233
David Majnemerba3e5ec2015-03-13 18:26:17 +00008234 if (Id == Builtin::BI__GetExceptionInfo)
8235 return QualType();
8236
Chris Lattnerecd79c62009-06-14 00:45:47 +00008237 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8238 "'.' should only occur at end of builtin type list!");
8239
Reid Kleckner78af0702013-08-27 23:08:25 +00008240 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008241 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8242
8243 bool Variadic = (TypeStr[0] == '.');
8244
8245 // We really shouldn't be making a no-proto type here, especially in C++.
8246 if (ArgTypes.empty() && Variadic)
8247 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008248
John McCalldb40c7f2010-12-14 08:05:40 +00008249 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008250 EPI.ExtInfo = EI;
8251 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008252
Jordan Rose5c382722013-03-08 21:51:21 +00008253 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008254}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008255
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008256static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8257 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008258 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008259 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008260
Rafael Espindola3ae00052013-05-13 00:12:11 +00008261 GVALinkage External = GVA_StrongExternal;
8262 switch (FD->getTemplateSpecializationKind()) {
8263 case TSK_Undeclared:
8264 case TSK_ExplicitSpecialization:
8265 External = GVA_StrongExternal;
8266 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008267
Rafael Espindola3ae00052013-05-13 00:12:11 +00008268 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008269 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008270
David Majnemerc3d07332014-05-15 06:25:57 +00008271 // C++11 [temp.explicit]p10:
8272 // [ Note: The intent is that an inline function that is the subject of
8273 // an explicit instantiation declaration will still be implicitly
8274 // instantiated when used so that the body can be considered for
8275 // inlining, but that no out-of-line copy of the inline function would be
8276 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008277 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008278 return GVA_AvailableExternally;
8279
Rafael Espindola3ae00052013-05-13 00:12:11 +00008280 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008281 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008282 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008283 }
8284
8285 if (!FD->isInlined())
8286 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008287
David Majnemer3f021502015-10-08 04:53:31 +00008288 if ((!Context.getLangOpts().CPlusPlus &&
8289 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008290 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008291 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008292 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8293
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008294 // GNU or C99 inline semantics. Determine whether this symbol should be
8295 // externally visible.
8296 if (FD->isInlineDefinitionExternallyVisible())
8297 return External;
8298
8299 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008300 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008301 }
8302
David Majnemer54e3ba52014-04-02 23:17:29 +00008303 // Functions specified with extern and inline in -fms-compatibility mode
8304 // forcibly get emitted. While the body of the function cannot be later
8305 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008306 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008307 return GVA_StrongODR;
8308
David Majnemer27d69db2014-04-28 22:17:59 +00008309 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008310}
8311
Artem Belevich7b41f702015-09-23 17:44:53 +00008312static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008313 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8314 // dllexport/dllimport on inline functions.
8315 if (D->hasAttr<DLLImportAttr>()) {
8316 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8317 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008318 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008319 if (L == GVA_DiscardableODR)
8320 return GVA_StrongODR;
8321 }
8322 return L;
8323}
8324
8325GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008326 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8327 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008328}
8329
8330static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8331 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008332 if (!VD->isExternallyVisible())
8333 return GVA_Internal;
8334
David Majnemer27d69db2014-04-28 22:17:59 +00008335 if (VD->isStaticLocal()) {
8336 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8337 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8338 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8339 LexicalContext = LexicalContext->getLexicalParent();
8340
Richard Smith9e2341d2015-03-23 03:25:59 +00008341 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008342 // enclosing function.
8343 if (LexicalContext)
8344 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008345 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008346
8347 // GVA_StrongODR function linkage is stronger than what we need,
8348 // downgrade to GVA_DiscardableODR.
8349 // This allows us to discard the variable if we never end up needing it.
8350 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8351 : StaticLocalLinkage;
8352 }
8353
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008354 // MSVC treats in-class initialized static data members as definitions.
8355 // By giving them non-strong linkage, out-of-line definitions won't
8356 // cause link errors.
8357 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8358 return GVA_DiscardableODR;
8359
Richard Smith8809a0c2013-09-27 20:14:12 +00008360 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008361 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008362 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008363
David Majnemer6d1780c2015-07-17 23:36:49 +00008364 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008365 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8366 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008367 ? GVA_StrongODR
8368 : GVA_StrongExternal;
8369
Rafael Espindola3ae00052013-05-13 00:12:11 +00008370 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008371 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008372
David Majnemer27d69db2014-04-28 22:17:59 +00008373 case TSK_ExplicitInstantiationDeclaration:
8374 return GVA_AvailableExternally;
8375
Rafael Espindola3ae00052013-05-13 00:12:11 +00008376 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008377 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008378 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008379
8380 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008381}
8382
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008383GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008384 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8385 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008386}
8387
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008388bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008389 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8390 if (!VD->isFileVarDecl())
8391 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008392 // Global named register variables (GNU extension) are never emitted.
8393 if (VD->getStorageClass() == SC_Register)
8394 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008395 if (VD->getDescribedVarTemplate() ||
8396 isa<VarTemplatePartialSpecializationDecl>(VD))
8397 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008398 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8399 // We never need to emit an uninstantiated function template.
8400 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8401 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008402 } else if (isa<OMPThreadPrivateDecl>(D))
8403 return true;
8404 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008405 return false;
8406
8407 // If this is a member of a class template, we do not need to emit it.
8408 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008409 return false;
8410
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008411 // Weak references don't produce any output by themselves.
8412 if (D->hasAttr<WeakRefAttr>())
8413 return false;
8414
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008415 // Aliases and used decls are required.
8416 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8417 return true;
8418
8419 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8420 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008421 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008422 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008423
8424 // Constructors and destructors are required.
8425 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8426 return true;
8427
John McCall6bd2a892013-01-25 22:31:03 +00008428 // The key function for a class is required. This rule only comes
8429 // into play when inline functions can be key functions, though.
8430 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8431 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8432 const CXXRecordDecl *RD = MD->getParent();
8433 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8434 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8435 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8436 return true;
8437 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008438 }
8439 }
8440
8441 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8442
8443 // static, static inline, always_inline, and extern inline functions can
8444 // always be deferred. Normal inline functions can be deferred in C99/C++.
8445 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008446 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8447 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008448 return false;
8449 return true;
8450 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008451
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008452 const VarDecl *VD = cast<VarDecl>(D);
8453 assert(VD->isFileVarDecl() && "Expected file scoped var");
8454
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008455 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8456 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008457 return false;
8458
Richard Smitha0e5e542012-11-12 21:38:00 +00008459 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008460 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008461 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8462 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008463 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008464
Richard Smitha0e5e542012-11-12 21:38:00 +00008465 // Variables that have destruction with side-effects are required.
8466 if (VD->getType().isDestructedType())
8467 return true;
8468
8469 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008470 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8471 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008472 return true;
8473
8474 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008475}
Charles Davis53c59df2010-08-16 03:33:14 +00008476
Reid Kleckner78af0702013-08-27 23:08:25 +00008477CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8478 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008479 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008480 if (IsCXXMethod)
8481 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008482
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008483 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8484
8485 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008486}
8487
Jay Foad39c79802011-01-12 09:06:06 +00008488bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008489 // Pass through to the C++ ABI object
8490 return ABI->isNearlyEmpty(RD);
8491}
8492
Reid Kleckner96f8f932014-02-05 17:27:08 +00008493VTableContextBase *ASTContext::getVTableContext() {
8494 if (!VTContext.get()) {
8495 if (Target->getCXXABI().isMicrosoft())
8496 VTContext.reset(new MicrosoftVTableContext(*this));
8497 else
8498 VTContext.reset(new ItaniumVTableContext(*this));
8499 }
8500 return VTContext.get();
8501}
8502
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008503MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008504 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008505 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008506 case TargetCXXABI::GenericItanium:
8507 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008508 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008509 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008510 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008511 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008512 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008513 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008514 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008515 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008516 }
David Blaikie83d382b2011-09-23 05:06:16 +00008517 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008518}
8519
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008520CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008521
8522size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008523 return ASTRecordLayouts.getMemorySize() +
8524 llvm::capacity_in_bytes(ObjCLayouts) +
8525 llvm::capacity_in_bytes(KeyFunctions) +
8526 llvm::capacity_in_bytes(ObjCImpls) +
8527 llvm::capacity_in_bytes(BlockVarCopyInits) +
8528 llvm::capacity_in_bytes(DeclAttrs) +
8529 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8530 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8531 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8532 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8533 llvm::capacity_in_bytes(OverriddenMethods) +
8534 llvm::capacity_in_bytes(Types) +
8535 llvm::capacity_in_bytes(VariableArrayTypes) +
8536 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008537}
Ted Kremenek540017e2011-10-06 05:00:56 +00008538
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008539/// getIntTypeForBitwidth -
8540/// sets integer QualTy according to specified details:
8541/// bitwidth, signed/unsigned.
8542/// Returns empty type if there is no appropriate target types.
8543QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8544 unsigned Signed) const {
8545 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8546 CanQualType QualTy = getFromTargetType(Ty);
8547 if (!QualTy && DestWidth == 128)
8548 return Signed ? Int128Ty : UnsignedInt128Ty;
8549 return QualTy;
8550}
8551
8552/// getRealTypeForBitwidth -
8553/// sets floating point QualTy according to specified bitwidth.
8554/// Returns empty type if there is no appropriate target types.
8555QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8556 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8557 switch (Ty) {
8558 case TargetInfo::Float:
8559 return FloatTy;
8560 case TargetInfo::Double:
8561 return DoubleTy;
8562 case TargetInfo::LongDouble:
8563 return LongDoubleTy;
8564 case TargetInfo::NoFloat:
8565 return QualType();
8566 }
8567
8568 llvm_unreachable("Unhandled TargetInfo::RealType value");
8569}
8570
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008571void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8572 if (Number > 1)
8573 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008574}
8575
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008576unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8577 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8578 MangleNumbers.find(ND);
8579 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008580}
8581
David Majnemer2206bf52014-03-05 08:57:59 +00008582void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8583 if (Number > 1)
8584 StaticLocalNumbers[VD] = Number;
8585}
8586
8587unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8588 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8589 StaticLocalNumbers.find(VD);
8590 return I != StaticLocalNumbers.end() ? I->second : 1;
8591}
8592
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008593MangleNumberingContext &
8594ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008595 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8596 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8597 if (!MCtx)
8598 MCtx = createMangleNumberingContext();
8599 return *MCtx;
8600}
8601
8602MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8603 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008604}
8605
David Majnemere7a818f2015-03-06 18:53:55 +00008606const CXXConstructorDecl *
8607ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8608 return ABI->getCopyConstructorForExceptionObject(
8609 cast<CXXRecordDecl>(RD->getFirstDecl()));
8610}
8611
8612void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8613 CXXConstructorDecl *CD) {
8614 return ABI->addCopyConstructorForExceptionObject(
8615 cast<CXXRecordDecl>(RD->getFirstDecl()),
8616 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8617}
8618
David Majnemerdfa6d202015-03-11 18:36:39 +00008619void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8620 unsigned ParmIdx, Expr *DAE) {
8621 ABI->addDefaultArgExprForConstructor(
8622 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8623}
8624
8625Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8626 unsigned ParmIdx) {
8627 return ABI->getDefaultArgExprForConstructor(
8628 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8629}
8630
David Majnemer00350522015-08-31 18:48:39 +00008631void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8632 TypedefNameDecl *DD) {
8633 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8634}
8635
8636TypedefNameDecl *
8637ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8638 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8639}
8640
8641void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8642 DeclaratorDecl *DD) {
8643 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8644}
8645
8646DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8647 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8648}
8649
Ted Kremenek540017e2011-10-06 05:00:56 +00008650void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8651 ParamIndices[D] = index;
8652}
8653
8654unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8655 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8656 assert(I != ParamIndices.end() &&
8657 "ParmIndices lacks entry set by ParmVarDecl");
8658 return I->second;
8659}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008660
Richard Smithe6c01442013-06-05 00:46:14 +00008661APValue *
8662ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8663 bool MayCreate) {
8664 assert(E && E->getStorageDuration() == SD_Static &&
8665 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008666 if (MayCreate) {
8667 APValue *&MTVI = MaterializedTemporaryValues[E];
8668 if (!MTVI)
8669 MTVI = new (*this) APValue;
8670 return MTVI;
8671 }
Richard Smithe6c01442013-06-05 00:46:14 +00008672
David Majnemer2dcef9e2015-08-13 23:50:15 +00008673 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008674}
8675
Fariborz Jahanian615de762013-05-28 17:37:39 +00008676bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8677 const llvm::Triple &T = getTargetInfo().getTriple();
8678 if (!T.isOSDarwin())
8679 return false;
8680
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008681 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8682 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8683 return false;
8684
Fariborz Jahanian615de762013-05-28 17:37:39 +00008685 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8686 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8687 uint64_t Size = sizeChars.getQuantity();
8688 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8689 unsigned Align = alignChars.getQuantity();
8690 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8691 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8692}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008693
8694namespace {
8695
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008696ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8697 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008698 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008699 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008700 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008701 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008702 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008703}
8704
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008705/// Template specializations to abstract away from pointers and TypeLocs.
8706/// @{
8707template <typename T>
8708ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8709 return ast_type_traits::DynTypedNode::create(*Node);
8710}
8711template <>
8712ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8713 return ast_type_traits::DynTypedNode::create(Node);
8714}
8715template <>
8716ast_type_traits::DynTypedNode
8717createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8718 return ast_type_traits::DynTypedNode::create(Node);
8719}
8720/// @}
8721
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008722 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8723 /// parents as defined by the \c RecursiveASTVisitor.
8724 ///
8725 /// Note that the relationship described here is purely in terms of AST
8726 /// traversal - there are other relationships (for example declaration context)
8727 /// in the AST that are better modeled by special matchers.
8728 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008729 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008730 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008731 public:
8732 /// \brief Builds and returns the translation unit's parent map.
8733 ///
8734 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008735 static std::pair<ASTContext::ParentMapPointers *,
8736 ASTContext::ParentMapOtherNodes *>
8737 buildMap(TranslationUnitDecl &TU) {
8738 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8739 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008740 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008741 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008742 }
8743
8744 private:
8745 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8746
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008747 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8748 ASTContext::ParentMapOtherNodes *OtherParents)
8749 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008750
8751 bool shouldVisitTemplateInstantiations() const {
8752 return true;
8753 }
8754 bool shouldVisitImplicitCode() const {
8755 return true;
8756 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008757
Richard Smith85838722015-11-24 03:09:01 +00008758 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8759 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008760 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00008761 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008762 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008763 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008764 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008765 // FIXME: Currently we add the same parent multiple times, but only
8766 // when no memoization data is available for the type.
8767 // For example when we visit all subexpressions of template
8768 // instantiations; this is suboptimal, but benign: the only way to
8769 // visit those is with hasAncestor / hasParent, and those do not create
8770 // new matches.
8771 // The plan is to enable DynTypedNode to be storable in a map or hash
8772 // map. The main problem there is to implement hash functions /
8773 // comparison operators for all types that DynTypedNode supports that
8774 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008775 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008776 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008777 if (const auto *D = ParentStack.back().get<Decl>())
8778 NodeOrVector = D;
8779 else if (const auto *S = ParentStack.back().get<Stmt>())
8780 NodeOrVector = S;
8781 else
8782 NodeOrVector =
8783 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008784 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008785 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8786 auto *Vector = new ASTContext::ParentVector(
8787 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008788 if (auto *Node =
8789 NodeOrVector
8790 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8791 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008792 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008793 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008794
8795 auto *Vector =
8796 NodeOrVector.template get<ASTContext::ParentVector *>();
8797 // Skip duplicates for types that have memoization data.
8798 // We must check that the type has memoization data before calling
8799 // std::find() because DynTypedNode::operator== can't compare all
8800 // types.
8801 bool Found = ParentStack.back().getMemoizationData() &&
8802 std::find(Vector->begin(), Vector->end(),
8803 ParentStack.back()) != Vector->end();
8804 if (!Found)
8805 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008806 }
8807 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008808 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00008809 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008810 ParentStack.pop_back();
8811 return Result;
8812 }
8813
8814 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00008815 return TraverseNode(DeclNode, DeclNode,
8816 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008817 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008818 }
8819
8820 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00008821 return TraverseNode(StmtNode, StmtNode,
8822 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008823 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008824 }
8825
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008826 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00008827 return TraverseNode(
8828 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
8829 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
8830 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008831 }
8832
8833 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8834 return TraverseNode(
8835 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00008836 [&] {
8837 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
8838 },
8839 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008840 }
8841
8842 ASTContext::ParentMapPointers *Parents;
8843 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008844 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8845
8846 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8847 };
8848
Eugene Zelenkod4304d22015-11-04 21:37:17 +00008849} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008850
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008851template <typename NodeTy, typename MapTy>
8852static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8853 const MapTy &Map) {
8854 auto I = Map.find(Node);
8855 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008856 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008857 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008858 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008859 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00008860 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008861 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008862}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008863
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008864ASTContext::DynTypedNodeList
8865ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8866 if (!PointerParents) {
8867 // We always need to run over the whole translation unit, as
8868 // hasAncestor can escape any subtree.
8869 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8870 PointerParents.reset(Maps.first);
8871 OtherParents.reset(Maps.second);
8872 }
8873 if (Node.getNodeKind().hasPointerIdentity())
8874 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8875 return getDynNodeFromMap(Node, *OtherParents);
8876}
8877
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008878bool
8879ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8880 const ObjCMethodDecl *MethodImpl) {
8881 // No point trying to match an unavailable/deprecated mothod.
8882 if (MethodDecl->hasAttr<UnavailableAttr>()
8883 || MethodDecl->hasAttr<DeprecatedAttr>())
8884 return false;
8885 if (MethodDecl->getObjCDeclQualifier() !=
8886 MethodImpl->getObjCDeclQualifier())
8887 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008888 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008889 return false;
8890
8891 if (MethodDecl->param_size() != MethodImpl->param_size())
8892 return false;
8893
8894 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8895 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8896 EF = MethodDecl->param_end();
8897 IM != EM && IF != EF; ++IM, ++IF) {
8898 const ParmVarDecl *DeclVar = (*IF);
8899 const ParmVarDecl *ImplVar = (*IM);
8900 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8901 return false;
8902 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8903 return false;
8904 }
8905 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8906
8907}
Richard Smith053f6c62014-05-16 23:01:30 +00008908
8909// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8910// doesn't include ASTContext.h
8911template
8912clang::LazyGenerationalUpdatePtr<
8913 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8914clang::LazyGenerationalUpdatePtr<
8915 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8916 const clang::ASTContext &Ctx, Decl *Value);