blob: 370155873c05d98134178e36fdf25cb3b5b12a04 [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"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000037#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000038#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000039#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000040#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000041#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000042#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000043#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000044
Chris Lattnerddc135e2006-11-10 06:34:16 +000045using namespace clang;
46
Douglas Gregor9672f922010-07-03 00:47:00 +000047unsigned ASTContext::NumImplicitDefaultConstructors;
48unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000049unsigned ASTContext::NumImplicitCopyConstructors;
50unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveConstructors;
52unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000053unsigned ASTContext::NumImplicitCopyAssignmentOperators;
54unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000055unsigned ASTContext::NumImplicitMoveAssignmentOperators;
56unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000057unsigned ASTContext::NumImplicitDestructors;
58unsigned ASTContext::NumImplicitDestructorsDeclared;
59
Steve Naroff0af91202007-04-27 21:51:21 +000060enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000061 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000062};
63
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000064RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000065 if (!CommentsLoaded && ExternalSource) {
66 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000067
68#ifndef NDEBUG
69 ArrayRef<RawComment *> RawComments = Comments.getComments();
70 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
71 BeforeThanCompare<RawComment>(SourceMgr)));
72#endif
73
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000074 CommentsLoaded = true;
75 }
76
77 assert(D);
78
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000079 // User can not attach documentation to implicit declarations.
80 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000081 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000082
Dmitri Gribenkob2610882012-08-14 17:17:18 +000083 // User can not attach documentation to implicit instantiations.
84 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
85 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000086 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000087 }
88
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000089 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
90 if (VD->isStaticDataMember() &&
91 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000092 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000093 }
94
95 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
96 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000097 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000098 }
99
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000100 if (const ClassTemplateSpecializationDecl *CTSD =
101 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
102 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
103 if (TSK == TSK_ImplicitInstantiation ||
104 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000105 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000106 }
107
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000108 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
109 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000110 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000111 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000112 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
113 // When tag declaration (but not definition!) is part of the
114 // decl-specifier-seq of some other declaration, it doesn't get comment
115 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000116 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000117 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000118 // TODO: handle comments for function parameters properly.
119 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000120 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000121
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000122 // TODO: we could look up template parameter documentation in the template
123 // documentation.
124 if (isa<TemplateTypeParmDecl>(D) ||
125 isa<NonTypeTemplateParmDecl>(D) ||
126 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000127 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000128
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000129 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000130
131 // If there are no comments anywhere, we won't find anything.
132 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000133 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000134
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000135 // Find declaration location.
136 // For Objective-C declarations we generally don't expect to have multiple
137 // declarators, thus use declaration starting location as the "declaration
138 // location".
139 // For all other declarations multiple declarators are used quite frequently,
140 // so we use the location of the identifier as the "declaration location".
141 SourceLocation DeclLoc;
142 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000143 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000144 isa<RedeclarableTemplateDecl>(D) ||
145 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000146 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000147 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000148 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000149 if (DeclLoc.isMacroID()) {
150 if (isa<TypedefDecl>(D)) {
151 // If location of the typedef name is in a macro, it is because being
152 // declared via a macro. Try using declaration's starting location as
153 // the "declaration location".
154 DeclLoc = D->getLocStart();
155 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
156 // If location of the tag decl is inside a macro, but the spelling of
157 // the tag name comes from a macro argument, it looks like a special
158 // macro like NS_ENUM is being used to define the tag decl. In that
159 // case, adjust the source location to the expansion loc so that we can
160 // attach the comment to the tag decl.
161 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
162 TD->isCompleteDefinition())
163 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
164 }
165 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000166 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000167
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000168 // If the declaration doesn't map directly to a location in a file, we
169 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000171 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000172
173 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000174 ArrayRef<RawComment *>::iterator Comment;
175 {
176 // When searching for comments during parsing, the comment we are looking
177 // for is usually among the last two comments we parsed -- check them
178 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000179 RawComment CommentAtDeclLoc(
180 SourceMgr, SourceRange(DeclLoc), false,
181 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000182 BeforeThanCompare<RawComment> Compare(SourceMgr);
183 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
184 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
185 if (!Found && RawComments.size() >= 2) {
186 MaybeBeforeDecl--;
187 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
188 }
189
190 if (Found) {
191 Comment = MaybeBeforeDecl + 1;
192 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
193 &CommentAtDeclLoc, Compare));
194 } else {
195 // Slow path.
196 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
197 &CommentAtDeclLoc, Compare);
198 }
199 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000200
201 // Decompose the location for the declaration and find the beginning of the
202 // file buffer.
203 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
204
205 // First check whether we have a trailing comment.
206 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000207 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000208 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000209 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000211 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212 // Check that Doxygen trailing comment comes after the declaration, starts
213 // on the same line and in the same file as the declaration.
214 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
215 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
216 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
217 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000218 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 }
220 }
221
222 // The comment just after the declaration was not a trailing comment.
223 // Let's look at the previous comment.
224 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000225 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000226 --Comment;
227
228 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000229 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000230 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000231
232 // Decompose the end of the comment.
233 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000234 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000235
236 // If the comment and the declaration aren't in the same file, then they
237 // aren't related.
238 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000239 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000240
241 // Get the corresponding buffer.
242 bool Invalid = false;
243 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
244 &Invalid).data();
245 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000246 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000247
248 // Extract text between the comment and declaration.
249 StringRef Text(Buffer + CommentEndDecomp.second,
250 DeclLocDecomp.second - CommentEndDecomp.second);
251
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000252 // There should be no other declarations or preprocessor directives between
253 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000254 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000255 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000256
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000257 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000258}
259
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000260namespace {
261/// If we have a 'templated' declaration for a template, adjust 'D' to
262/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000263/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000264const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000266 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000267 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000268 return FTD;
269
270 // Nothing to do if function is not an implicit instantiation.
271 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
272 return D;
273
274 // Function is an implicit instantiation of a function template?
275 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
276 return FTD;
277
278 // Function is instantiated from a member definition of a class template?
279 if (const FunctionDecl *MemberDecl =
280 FD->getInstantiatedFromMemberFunction())
281 return MemberDecl;
282
283 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000284 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000285 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
286 // Static data member is instantiated from a member definition of a class
287 // template?
288 if (VD->isStaticDataMember())
289 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
290 return MemberDecl;
291
292 return D;
293 }
294 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
295 // Is this class declaration part of a class template?
296 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
297 return CTD;
298
299 // Class is an implicit instantiation of a class template or partial
300 // specialization?
301 if (const ClassTemplateSpecializationDecl *CTSD =
302 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
303 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
304 return D;
305 llvm::PointerUnion<ClassTemplateDecl *,
306 ClassTemplatePartialSpecializationDecl *>
307 PU = CTSD->getSpecializedTemplateOrPartial();
308 return PU.is<ClassTemplateDecl*>() ?
309 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
310 static_cast<const Decl*>(
311 PU.get<ClassTemplatePartialSpecializationDecl *>());
312 }
313
314 // Class is instantiated from a member definition of a class template?
315 if (const MemberSpecializationInfo *Info =
316 CRD->getMemberSpecializationInfo())
317 return Info->getInstantiatedFrom();
318
319 return D;
320 }
321 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
322 // Enum is instantiated from a member definition of a class template?
323 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
324 return MemberDecl;
325
326 return D;
327 }
328 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000329 return D;
330}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000331} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000332
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000333const RawComment *ASTContext::getRawCommentForAnyRedecl(
334 const Decl *D,
335 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000336 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000337
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000338 // Check whether we have cached a comment for this declaration already.
339 {
340 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
341 RedeclComments.find(D);
342 if (Pos != RedeclComments.end()) {
343 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000344 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
345 if (OriginalDecl)
346 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000347 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000348 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000349 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000350 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000351
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000352 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000353 const RawComment *RC = nullptr;
354 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000355 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000357 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000358 if (Pos != RedeclComments.end()) {
359 const RawCommentAndCacheFlags &Raw = Pos->second;
360 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
361 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000362 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363 break;
364 }
365 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000366 RC = getRawCommentForDeclNoCache(I);
367 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000368 RawCommentAndCacheFlags Raw;
369 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000370 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
371 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000372 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000373 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000374 } else
375 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000376 Raw.setOriginalDecl(I);
377 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000378 if (RC)
379 break;
380 }
381 }
382
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000383 // If we found a comment, it should be a documentation comment.
384 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000385
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000386 if (OriginalDecl)
387 *OriginalDecl = OriginalDeclForRC;
388
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000389 // Update cache for every declaration in the redeclaration chain.
390 RawCommentAndCacheFlags Raw;
391 Raw.setRaw(RC);
392 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000393 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394
Aaron Ballman86c93902014-03-06 23:45:36 +0000395 for (auto I : D->redecls()) {
396 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
398 R = Raw;
399 }
400
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000401 return RC;
402}
403
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000404static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
405 SmallVectorImpl<const NamedDecl *> &Redeclared) {
406 const DeclContext *DC = ObjCMethod->getDeclContext();
407 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
408 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
409 if (!ID)
410 return;
411 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000412 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000414 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 ObjCMethod->isInstanceMethod()))
416 Redeclared.push_back(RedeclaredMethod);
417 }
418 }
419}
420
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000421comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
422 const Decl *D) const {
423 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
424 ThisDeclInfo->CommentDecl = D;
425 ThisDeclInfo->IsFilled = false;
426 ThisDeclInfo->fill();
427 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000428 if (!ThisDeclInfo->TemplateParameters)
429 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000430 comments::FullComment *CFC =
431 new (*this) comments::FullComment(FC->getBlocks(),
432 ThisDeclInfo);
433 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000434}
435
Richard Smithb39b9d52013-05-21 05:24:00 +0000436comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
437 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000438 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000439}
440
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000441comments::FullComment *ASTContext::getCommentForDecl(
442 const Decl *D,
443 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000444 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000445 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000448 const Decl *Canonical = D->getCanonicalDecl();
449 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
450 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000451
452 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000455 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 return CFC;
457 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000458 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000459 }
460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000463 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000464 if (!RC) {
465 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000466 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000467 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000468 if (OMD && OMD->isPropertyAccessor())
469 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
470 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
471 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000472 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000473 addRedeclaredMethods(OMD, Overridden);
474 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000475 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
476 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
477 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000478 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000479 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000480 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000481 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000482 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000483 if (const TagType *TT = QT->getAs<TagType>())
484 if (const Decl *TD = TT->getDecl())
485 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000486 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000487 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000488 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
489 while (IC->getSuperClass()) {
490 IC = IC->getSuperClass();
491 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
492 return cloneFullComment(FC, D);
493 }
494 }
495 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
496 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
497 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
498 return cloneFullComment(FC, D);
499 }
500 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
501 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000502 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000503 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000504 for (const auto &I : RD->bases()) {
505 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000507 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000508 if (Ty.isNull())
509 continue;
510 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
512 continue;
513
514 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
515 return cloneFullComment(FC, D);
516 }
517 }
518 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000519 for (const auto &I : RD->vbases()) {
520 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000521 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000522 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000523 if (Ty.isNull())
524 continue;
525 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
526 if (!(VirtualBase= VirtualBase->getDefinition()))
527 continue;
528 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
529 return cloneFullComment(FC, D);
530 }
531 }
532 }
Craig Topper36250ad2014-05-12 05:36:57 +0000533 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000534 }
535
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000536 // If the RawComment was attached to other redeclaration of this Decl, we
537 // should parse the comment in context of that other Decl. This is important
538 // because comments can contain references to parameter names which can be
539 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000542
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000543 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000544 ParsedComments[Canonical] = FC;
545 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000546}
547
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000548void
549ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
550 TemplateTemplateParmDecl *Parm) {
551 ID.AddInteger(Parm->getDepth());
552 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000553 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000554
555 TemplateParameterList *Params = Parm->getTemplateParameters();
556 ID.AddInteger(Params->size());
557 for (TemplateParameterList::const_iterator P = Params->begin(),
558 PEnd = Params->end();
559 P != PEnd; ++P) {
560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
561 ID.AddInteger(0);
562 ID.AddBoolean(TTP->isParameterPack());
563 continue;
564 }
565
566 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
567 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000568 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000569 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000570 if (NTTP->isExpandedParameterPack()) {
571 ID.AddBoolean(true);
572 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000573 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
574 QualType T = NTTP->getExpansionType(I);
575 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
576 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000577 } else
578 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000579 continue;
580 }
581
582 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
583 ID.AddInteger(2);
584 Profile(ID, TTP);
585 }
586}
587
588TemplateTemplateParmDecl *
589ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000590 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000591 // Check if we already have a canonical template template parameter.
592 llvm::FoldingSetNodeID ID;
593 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000594 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000595 CanonicalTemplateTemplateParm *Canonical
596 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
597 if (Canonical)
598 return Canonical->getParam();
599
600 // Build a canonical template parameter list.
601 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000602 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000603 CanonParams.reserve(Params->size());
604 for (TemplateParameterList::const_iterator P = Params->begin(),
605 PEnd = Params->end();
606 P != PEnd; ++P) {
607 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
608 CanonParams.push_back(
609 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000610 SourceLocation(),
611 SourceLocation(),
612 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000613 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000614 TTP->isParameterPack()));
615 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000616 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
617 QualType T = getCanonicalType(NTTP->getType());
618 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
619 NonTypeTemplateParmDecl *Param;
620 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000621 SmallVector<QualType, 2> ExpandedTypes;
622 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000623 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
624 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
625 ExpandedTInfos.push_back(
626 getTrivialTypeSourceInfo(ExpandedTypes.back()));
627 }
628
629 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000630 SourceLocation(),
631 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000633 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000634 T,
635 TInfo,
636 ExpandedTypes.data(),
637 ExpandedTypes.size(),
638 ExpandedTInfos.data());
639 } else {
640 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000641 SourceLocation(),
642 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000644 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000645 T,
646 NTTP->isParameterPack(),
647 TInfo);
648 }
649 CanonParams.push_back(Param);
650
651 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000652 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
653 cast<TemplateTemplateParmDecl>(*P)));
654 }
655
656 TemplateTemplateParmDecl *CanonTTP
657 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
658 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000659 TTP->getPosition(),
660 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000661 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000662 TemplateParameterList::Create(*this, SourceLocation(),
663 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000664 CanonParams,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000665 SourceLocation()));
666
667 // Get the new insert position for the node we care about.
668 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000669 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000670 (void)Canonical;
671
672 // Create the canonical template template parameter entry.
673 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
674 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
675 return CanonTTP;
676}
677
Charles Davis53c59df2010-08-16 03:33:14 +0000678CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000679 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000680
John McCall359b8852013-01-25 22:30:49 +0000681 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000682 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000683 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000684 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000685 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000686 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000687 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000689 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000690 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000692 return CreateMicrosoftCXXABI(*this);
693 }
David Blaikie8a40f702012-01-17 06:56:22 +0000694 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000695}
696
Douglas Gregore8bbc122011-09-02 00:18:52 +0000697static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000698 const LangOptions &LOpts) {
699 if (LOpts.FakeAddressSpaceMap) {
700 // The fake address space map must have a distinct entry for each
701 // language-specific address space.
702 static const unsigned FakeAddrSpaceMap[] = {
703 1, // opencl_global
704 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000705 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000706 4, // opencl_generic
707 5, // cuda_device
708 6, // cuda_constant
709 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000714 }
715}
716
David Tweed31d09b02013-09-13 12:04:22 +0000717static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
718 const LangOptions &LangOpts) {
719 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000720 case LangOptions::ASMM_Target:
721 return TI.useAddressSpaceMapMangling();
722 case LangOptions::ASMM_On:
723 return true;
724 case LangOptions::ASMM_Off:
725 return false;
726 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000727 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000728}
729
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000731 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000732 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000733 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
734 DependentTemplateSpecializationTypes(this_()),
735 SubstTemplateTemplateParmPacks(this_()),
736 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
737 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000738 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
739 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
740 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000741 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
742 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
743 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
744 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
745 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
746 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr), SourceMgr(SM),
747 LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000748 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000749 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
750 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
751 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
752 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000753 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000754 TUDecl = TranslationUnitDecl::Create(*this);
755}
756
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000757ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000758 ReleaseParentMapEntries();
759
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000760 // Release the DenseMaps associated with DeclContext objects.
761 // FIXME: Is this the ideal solution?
762 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000763
Manuel Klimeka7328992013-06-03 13:51:33 +0000764 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000765 for (auto &Pair : Deallocations)
766 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000767
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) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000815 Deallocations.push_back({Callback, 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
Alexey Bader954ba212016-04-08 13:40:33 +00001093 if (LangOpts.OpenCL) {
1094#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1095 InitBuiltinType(SingletonId, BuiltinType::Id);
1096#include "clang/AST/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001097
Guy Benyei61054192013-02-07 10:55:47 +00001098 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001099 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001100 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1101 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1102 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1103 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001104 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001105
1106 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001107 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1108 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001109
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001110 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001111
1112 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001113
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001114 // void * type
1115 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001116
1117 // nullptr type (C++0x 2.14.7)
1118 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001119
1120 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1121 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001122
1123 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001124 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001125}
1126
David Blaikie9c902b52011-09-25 23:23:43 +00001127DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001128 return SourceMgr.getDiagnostics();
1129}
1130
Douglas Gregor561eceb2010-08-30 16:49:28 +00001131AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1132 AttrVec *&Result = DeclAttrs[D];
1133 if (!Result) {
1134 void *Mem = Allocate(sizeof(AttrVec));
1135 Result = new (Mem) AttrVec;
1136 }
1137
1138 return *Result;
1139}
1140
1141/// \brief Erase the attributes corresponding to the given declaration.
1142void ASTContext::eraseDeclAttrs(const Decl *D) {
1143 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1144 if (Pos != DeclAttrs.end()) {
1145 Pos->second->~AttrVec();
1146 DeclAttrs.erase(Pos);
1147 }
1148}
1149
Larisse Voufo39a1e502013-08-06 01:03:05 +00001150// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001151MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001152ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001153 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001154 return getTemplateOrSpecializationInfo(Var)
1155 .dyn_cast<MemberSpecializationInfo *>();
1156}
1157
1158ASTContext::TemplateOrSpecializationInfo
1159ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1160 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1161 TemplateOrInstantiation.find(Var);
1162 if (Pos == TemplateOrInstantiation.end())
1163 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001164
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001165 return Pos->second;
1166}
1167
Mike Stump11289f42009-09-09 15:08:12 +00001168void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001169ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001170 TemplateSpecializationKind TSK,
1171 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001172 assert(Inst->isStaticDataMember() && "Not a static data member");
1173 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001174 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1175 Tmpl, TSK, PointOfInstantiation));
1176}
1177
1178void
1179ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1180 TemplateOrSpecializationInfo TSI) {
1181 assert(!TemplateOrInstantiation[Inst] &&
1182 "Already noted what the variable was instantiated from");
1183 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001184}
1185
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001186FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1187 const FunctionDecl *FD){
1188 assert(FD && "Specialization is 0");
1189 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001190 = ClassScopeSpecializationPattern.find(FD);
1191 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001192 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001193
1194 return Pos->second;
1195}
1196
1197void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1198 FunctionDecl *Pattern) {
1199 assert(FD && "Specialization is 0");
1200 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001201 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001202}
1203
John McCalle61f2ba2009-11-18 02:36:19 +00001204NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001205ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001206 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001207 = InstantiatedFromUsingDecl.find(UUD);
1208 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001209 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001210
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001211 return Pos->second;
1212}
1213
1214void
John McCallb96ec562009-12-04 22:46:56 +00001215ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1216 assert((isa<UsingDecl>(Pattern) ||
1217 isa<UnresolvedUsingValueDecl>(Pattern) ||
1218 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1219 "pattern decl is not a using decl");
1220 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1221 InstantiatedFromUsingDecl[Inst] = Pattern;
1222}
1223
1224UsingShadowDecl *
1225ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1226 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1227 = InstantiatedFromUsingShadowDecl.find(Inst);
1228 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001229 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001230
1231 return Pos->second;
1232}
1233
1234void
1235ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1236 UsingShadowDecl *Pattern) {
1237 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1238 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001239}
1240
Anders Carlsson5da84842009-09-01 04:26:58 +00001241FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1242 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1243 = InstantiatedFromUnnamedFieldDecl.find(Field);
1244 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001245 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001246
Anders Carlsson5da84842009-09-01 04:26:58 +00001247 return Pos->second;
1248}
1249
1250void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1251 FieldDecl *Tmpl) {
1252 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1253 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1254 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1255 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001256
Anders Carlsson5da84842009-09-01 04:26:58 +00001257 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1258}
1259
Douglas Gregor832940b2010-03-02 23:58:15 +00001260ASTContext::overridden_cxx_method_iterator
1261ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1262 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001263 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001264 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001265 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001266
1267 return Pos->second.begin();
1268}
1269
1270ASTContext::overridden_cxx_method_iterator
1271ASTContext::overridden_methods_end(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.end();
1278}
1279
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001280unsigned
1281ASTContext::overridden_methods_size(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());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001284 if (Pos == OverriddenMethods.end())
1285 return 0;
1286
1287 return Pos->second.size();
1288}
1289
Douglas Gregor832940b2010-03-02 23:58:15 +00001290void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1291 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001292 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001293 OverriddenMethods[Method].push_back(Overridden);
1294}
1295
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001296void ASTContext::getOverriddenMethods(
1297 const NamedDecl *D,
1298 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001299 assert(D);
1300
1301 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001302 Overridden.append(overridden_methods_begin(CXXMethod),
1303 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001304 return;
1305 }
1306
1307 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1308 if (!Method)
1309 return;
1310
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001311 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1312 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001313 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001314}
1315
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001316void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1317 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1318 assert(!Import->isFromASTFile() && "Non-local import declaration");
1319 if (!FirstLocalImport) {
1320 FirstLocalImport = Import;
1321 LastLocalImport = Import;
1322 return;
1323 }
1324
1325 LastLocalImport->NextLocalImport = Import;
1326 LastLocalImport = Import;
1327}
1328
Chris Lattner53cfe802007-07-18 17:52:12 +00001329//===----------------------------------------------------------------------===//
1330// Type Sizing and Analysis
1331//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001332
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001333/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1334/// scalar floating point type.
1335const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001336 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001337 assert(BT && "Not a floating point type!");
1338 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001339 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001340 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001341 case BuiltinType::Float: return Target->getFloatFormat();
1342 case BuiltinType::Double: return Target->getDoubleFormat();
1343 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001344 }
1345}
1346
Rafael Espindola71eccb32013-08-08 19:53:46 +00001347CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001348 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001349
John McCall94268702010-10-08 18:24:19 +00001350 bool UseAlignAttrOnly = false;
1351 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1352 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001353
John McCall94268702010-10-08 18:24:19 +00001354 // __attribute__((aligned)) can increase or decrease alignment
1355 // *except* on a struct or struct member, where it only increases
1356 // alignment unless 'packed' is also specified.
1357 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001358 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001359 // ignore that possibility; Sema should diagnose it.
1360 if (isa<FieldDecl>(D)) {
1361 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1362 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1363 } else {
1364 UseAlignAttrOnly = true;
1365 }
1366 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001367 else if (isa<FieldDecl>(D))
1368 UseAlignAttrOnly =
1369 D->hasAttr<PackedAttr>() ||
1370 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001371
John McCall4e819612011-01-20 07:57:12 +00001372 // If we're using the align attribute only, just ignore everything
1373 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001374 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001375 // do nothing
1376
John McCall94268702010-10-08 18:24:19 +00001377 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001378 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001379 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001380 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001381 T = RT->getPointeeType();
1382 else
1383 T = getPointerType(RT->getPointeeType());
1384 }
Richard Smithf6d70302014-06-10 23:34:28 +00001385 QualType BaseT = getBaseElementType(T);
1386 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001387 // Adjust alignments of declarations with array type by the
1388 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001389 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001390 unsigned MinWidth = Target->getLargeArrayMinWidth();
1391 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001392 if (isa<VariableArrayType>(arrayType))
1393 Align = std::max(Align, Target->getLargeArrayAlign());
1394 else if (isa<ConstantArrayType>(arrayType) &&
1395 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1396 Align = std::max(Align, Target->getLargeArrayAlign());
1397 }
John McCall33ddac02011-01-19 10:06:00 +00001398 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001399 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001400 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001401 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001402 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1403 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001404 }
John McCall4e819612011-01-20 07:57:12 +00001405
1406 // Fields can be subject to extra alignment constraints, like if
1407 // the field is packed, the struct is packed, or the struct has a
1408 // a max-field-alignment constraint (#pragma pack). So calculate
1409 // the actual alignment of the field within the struct, and then
1410 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001411 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1412 const RecordDecl *Parent = Field->getParent();
1413 // We can only produce a sensible answer if the record is valid.
1414 if (!Parent->isInvalidDecl()) {
1415 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001416
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001417 // Start with the record's overall alignment.
1418 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001419
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001420 // Use the GCD of that and the offset within the record.
1421 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1422 if (Offset > 0) {
1423 // Alignment is always a power of 2, so the GCD will be a power of 2,
1424 // which means we get to do this crazy thing instead of Euclid's.
1425 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1426 if (LowBitOfOffset < FieldAlign)
1427 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1428 }
1429
1430 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001431 }
Charles Davis3fc51072010-02-23 04:52:00 +00001432 }
Chris Lattner68061312009-01-24 21:53:27 +00001433 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001434
Ken Dyckcc56c542011-01-15 18:38:59 +00001435 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001436}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001437
John McCallf1249922012-08-21 04:10:00 +00001438// getTypeInfoDataSizeInChars - Return the size of a type, in
1439// chars. If the type is a record, its data size is returned. This is
1440// the size of the memcpy that's performed when assigning this type
1441// using a trivial copy/move assignment operator.
1442std::pair<CharUnits, CharUnits>
1443ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1444 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1445
1446 // In C++, objects can sometimes be allocated into the tail padding
1447 // of a base-class subobject. We decide whether that's possible
1448 // during class layout, so here we can just trust the layout results.
1449 if (getLangOpts().CPlusPlus) {
1450 if (const RecordType *RT = T->getAs<RecordType>()) {
1451 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1452 sizeAndAlign.first = layout.getDataSize();
1453 }
1454 }
1455
1456 return sizeAndAlign;
1457}
1458
Richard Trieu04d2d942013-05-14 21:59:17 +00001459/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1460/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1461std::pair<CharUnits, CharUnits>
1462static getConstantArrayInfoInChars(const ASTContext &Context,
1463 const ConstantArrayType *CAT) {
1464 std::pair<CharUnits, CharUnits> EltInfo =
1465 Context.getTypeInfoInChars(CAT->getElementType());
1466 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001467 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1468 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001469 "Overflow in array type char size evaluation");
1470 uint64_t Width = EltInfo.first.getQuantity() * Size;
1471 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001472 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1473 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001474 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001475 return std::make_pair(CharUnits::fromQuantity(Width),
1476 CharUnits::fromQuantity(Align));
1477}
1478
John McCall87fe5d52010-05-20 01:18:31 +00001479std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001480ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001481 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1482 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001483 TypeInfo Info = getTypeInfo(T);
1484 return std::make_pair(toCharUnitsFromBits(Info.Width),
1485 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001486}
1487
1488std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001489ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001490 return getTypeInfoInChars(T.getTypePtr());
1491}
1492
David Majnemer34b57492014-07-30 01:30:47 +00001493bool ASTContext::isAlignmentRequired(const Type *T) const {
1494 return getTypeInfo(T).AlignIsRequired;
1495}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001496
David Majnemer34b57492014-07-30 01:30:47 +00001497bool ASTContext::isAlignmentRequired(QualType T) const {
1498 return isAlignmentRequired(T.getTypePtr());
1499}
1500
1501TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001502 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1503 if (I != MemoizedTypeInfo.end())
1504 return I->second;
1505
1506 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1507 TypeInfo TI = getTypeInfoImpl(T);
1508 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001509 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001510}
1511
1512/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1513/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001514///
1515/// FIXME: Pointers into different addr spaces could have different sizes and
1516/// alignment requirements: getPointerInfo should take an AddrSpace, this
1517/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001518TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1519 uint64_t Width = 0;
1520 unsigned Align = 8;
1521 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001522 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001523#define TYPE(Class, Base)
1524#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001525#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001526#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001527#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1528 case Type::Class: \
1529 assert(!T->isDependentType() && "should not see dependent types here"); \
1530 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001531#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001532 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001533
Chris Lattner355332d2007-07-13 22:27:08 +00001534 case Type::FunctionNoProto:
1535 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001536 // GCC extension: alignof(function) = 32 bits
1537 Width = 0;
1538 Align = 32;
1539 break;
1540
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001541 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001542 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001543 Width = 0;
1544 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1545 break;
1546
Steve Naroff5c131802007-08-30 01:06:46 +00001547 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001548 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001549
David Majnemer34b57492014-07-30 01:30:47 +00001550 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001551 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001552 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001553 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001554 Width = EltInfo.Width * Size;
1555 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001556 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1557 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001558 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001559 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001560 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001561 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001562 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001563 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001564 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1565 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001566 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001567 // If the alignment is not a power of 2, round up to the next power of 2.
1568 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001569 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001570 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001571 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001572 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001573 // Adjust the alignment based on the target max.
1574 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1575 if (TargetVectorAlign && TargetVectorAlign < Align)
1576 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001577 break;
1578 }
Chris Lattner647fb222007-07-18 18:26:58 +00001579
Chris Lattner7570e9c2008-03-08 08:52:55 +00001580 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001581 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001582 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001583 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001584 // GCC extension: alignof(void) = 8 bits.
1585 Width = 0;
1586 Align = 8;
1587 break;
1588
Chris Lattner6a4f7452007-12-19 19:23:28 +00001589 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001590 Width = Target->getBoolWidth();
1591 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001592 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001593 case BuiltinType::Char_S:
1594 case BuiltinType::Char_U:
1595 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001596 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001597 Width = Target->getCharWidth();
1598 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001599 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001600 case BuiltinType::WChar_S:
1601 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001602 Width = Target->getWCharWidth();
1603 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001604 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001605 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001606 Width = Target->getChar16Width();
1607 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001608 break;
1609 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getChar32Width();
1611 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001612 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001613 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001614 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getShortWidth();
1616 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001617 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001618 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001619 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001620 Width = Target->getIntWidth();
1621 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001622 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001623 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001624 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001625 Width = Target->getLongWidth();
1626 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001627 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001628 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001629 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001630 Width = Target->getLongLongWidth();
1631 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001632 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001633 case BuiltinType::Int128:
1634 case BuiltinType::UInt128:
1635 Width = 128;
1636 Align = 128; // int128_t is 128-bit aligned on all targets.
1637 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001638 case BuiltinType::Half:
1639 Width = Target->getHalfWidth();
1640 Align = Target->getHalfAlign();
1641 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001642 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001643 Width = Target->getFloatWidth();
1644 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001645 break;
1646 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001647 Width = Target->getDoubleWidth();
1648 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001649 break;
1650 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001651 Width = Target->getLongDoubleWidth();
1652 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001653 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001654 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001655 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1656 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001657 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001658 case BuiltinType::ObjCId:
1659 case BuiltinType::ObjCClass:
1660 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001661 Width = Target->getPointerWidth(0);
1662 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001663 break;
Guy Benyei61054192013-02-07 10:55:47 +00001664 case BuiltinType::OCLSampler:
1665 // Samplers are modeled as integers.
1666 Width = Target->getIntWidth();
1667 Align = Target->getIntAlign();
1668 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001669 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001670 case BuiltinType::OCLClkEvent:
1671 case BuiltinType::OCLQueue:
1672 case BuiltinType::OCLNDRange:
1673 case BuiltinType::OCLReserveID:
Alexey Bader954ba212016-04-08 13:40:33 +00001674#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1675 case BuiltinType::Id:
1676#include "clang/AST/OpenCLImageTypes.def"
1677
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001678 // Currently these types are pointers to opaque types.
1679 Width = Target->getPointerWidth(0);
1680 Align = Target->getPointerAlign(0);
1681 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001682 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001683 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001684 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001685 Width = Target->getPointerWidth(0);
1686 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001687 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001688 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001689 unsigned AS = getTargetAddressSpace(
1690 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001691 Width = Target->getPointerWidth(AS);
1692 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001693 break;
1694 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001695 case Type::LValueReference:
1696 case Type::RValueReference: {
1697 // alignof and sizeof should never enter this code path here, so we go
1698 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001699 unsigned AS = getTargetAddressSpace(
1700 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001701 Width = Target->getPointerWidth(AS);
1702 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001703 break;
1704 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001705 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001706 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Width = Target->getPointerWidth(AS);
1708 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001709 break;
1710 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001711 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001712 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001713 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001714 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001715 }
Chris Lattner647fb222007-07-18 18:26:58 +00001716 case Type::Complex: {
1717 // Complex types have the same alignment as their elements, but twice the
1718 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001719 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1720 Width = EltInfo.Width * 2;
1721 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001722 break;
1723 }
John McCall8b07ec22010-05-15 11:32:37 +00001724 case Type::ObjCObject:
1725 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001726 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001727 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001728 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001729 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001730 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001731 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001732 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001733 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001734 break;
1735 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001736 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001737 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001738 const TagType *TT = cast<TagType>(T);
1739
1740 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001741 Width = 8;
1742 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001743 break;
1744 }
Mike Stump11289f42009-09-09 15:08:12 +00001745
David Majnemer475b25e2015-01-21 10:54:38 +00001746 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1747 const EnumDecl *ED = ET->getDecl();
1748 TypeInfo Info =
1749 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1750 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1751 Info.Align = AttrAlign;
1752 Info.AlignIsRequired = true;
1753 }
1754 return Info;
1755 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001756
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001757 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001758 const RecordDecl *RD = RT->getDecl();
1759 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001760 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001761 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001762 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001763 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001764 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001765
Chris Lattner63d2b362009-10-22 05:17:15 +00001766 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001767 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1768 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001769
Richard Smith30482bc2011-02-20 03:19:35 +00001770 case Type::Auto: {
1771 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001772 assert(!A->getDeducedType().isNull() &&
1773 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001774 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001775 }
1776
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001777 case Type::Paren:
1778 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1779
Douglas Gregoref462e62009-04-30 17:32:17 +00001780 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001781 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001782 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001783 // If the typedef has an aligned attribute on it, it overrides any computed
1784 // alignment we have. This violates the GCC documentation (which says that
1785 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001786 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001787 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001788 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001789 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001790 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001791 AlignIsRequired = Info.AlignIsRequired;
1792 }
David Majnemer34b57492014-07-30 01:30:47 +00001793 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001794 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001795 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001796
Abramo Bagnara6150c882010-05-11 21:36:43 +00001797 case Type::Elaborated:
1798 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001799
John McCall81904512011-01-06 01:58:22 +00001800 case Type::Attributed:
1801 return getTypeInfo(
1802 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1803
Eli Friedman0dfb8892011-10-06 23:00:33 +00001804 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001805 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001806 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1807 Width = Info.Width;
1808 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001809
1810 // If the size of the type doesn't exceed the platform's max
1811 // atomic promotion width, make the size and alignment more
1812 // favorable to atomic operations:
1813 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1814 // Round the size up to a power of 2.
1815 if (!llvm::isPowerOf2_64(Width))
1816 Width = llvm::NextPowerOf2(Width);
1817
1818 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001819 Align = static_cast<unsigned>(Width);
1820 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001821 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001822 break;
1823
1824 case Type::Pipe: {
1825 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1826 Width = Info.Width;
1827 Align = Info.Align;
1828 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001829
Douglas Gregoref462e62009-04-30 17:32:17 +00001830 }
Mike Stump11289f42009-09-09 15:08:12 +00001831
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001832 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001833 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001834}
1835
Alexey Bataev00396512015-07-02 03:40:19 +00001836unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1837 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1838 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1839 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1840 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1841 getTargetInfo().getABI() == "elfv1-qpx" &&
1842 T->isSpecificBuiltinType(BuiltinType::Double))
1843 SimdAlign = 256;
1844 return SimdAlign;
1845}
1846
Ken Dyckcc56c542011-01-15 18:38:59 +00001847/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1848CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1849 return CharUnits::fromQuantity(BitSize / getCharWidth());
1850}
1851
Ken Dyckb0fcc592011-02-11 01:54:29 +00001852/// toBits - Convert a size in characters to a size in characters.
1853int64_t ASTContext::toBits(CharUnits CharSize) const {
1854 return CharSize.getQuantity() * getCharWidth();
1855}
1856
Ken Dyck8c89d592009-12-22 14:23:30 +00001857/// getTypeSizeInChars - Return the size of the specified type, in characters.
1858/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001859CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001860 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001861}
Jay Foad39c79802011-01-12 09:06:06 +00001862CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001863 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001864}
1865
Ken Dycka6046ab2010-01-26 17:25:18 +00001866/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001867/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001868CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001869 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001870}
Jay Foad39c79802011-01-12 09:06:06 +00001871CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001872 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001873}
1874
Chris Lattnera3402cd2009-01-27 18:08:34 +00001875/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1876/// type for the current target in bits. This can be different than the ABI
1877/// alignment in cases where it is beneficial for performance to overalign
1878/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001879unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001880 TypeInfo TI = getTypeInfo(T);
1881 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001882
David Majnemere1544562015-04-24 01:25:05 +00001883 T = T->getBaseElementTypeUnsafe();
1884
1885 // The preferred alignment of member pointers is that of a pointer.
1886 if (T->isMemberPointerType())
1887 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1888
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001889 if (!Target->allowsLargerPreferedTypeAlignment())
1890 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001891
Eli Friedman7ab09572009-05-25 21:27:19 +00001892 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001893 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001894 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001895 if (const EnumType *ET = T->getAs<EnumType>())
1896 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001897 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001898 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1899 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001900 // Don't increase the alignment if an alignment attribute was specified on a
1901 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001902 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001903 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001904
Chris Lattnera3402cd2009-01-27 18:08:34 +00001905 return ABIAlign;
1906}
1907
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001908/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1909/// for __attribute__((aligned)) on this target, to be used if no alignment
1910/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001911unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001912 return getTargetInfo().getDefaultAlignForAttributeAligned();
1913}
1914
Ulrich Weigandfa806422013-05-06 16:23:57 +00001915/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1916/// to a global variable of the specified type.
1917unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1918 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1919}
1920
1921/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1922/// should be given to a global variable of the specified type.
1923CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1924 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1925}
1926
David Majnemer08ef2ba2015-06-23 20:34:18 +00001927CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1928 CharUnits Offset = CharUnits::Zero();
1929 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1930 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1931 Offset += Layout->getBaseClassOffset(Base);
1932 Layout = &getASTRecordLayout(Base);
1933 }
1934 return Offset;
1935}
1936
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001937/// DeepCollectObjCIvars -
1938/// This routine first collects all declared, but not synthesized, ivars in
1939/// super class and then collects all ivars, including those synthesized for
1940/// current class. This routine is used for implementation of current class
1941/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001942///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001943void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1944 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001945 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001946 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1947 DeepCollectObjCIvars(SuperClass, false, Ivars);
1948 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001949 for (const auto *I : OI->ivars())
1950 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001951 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001952 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001953 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001954 Iv= Iv->getNextIvar())
1955 Ivars.push_back(Iv);
1956 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001957}
1958
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001959/// CollectInheritedProtocols - Collect all protocols in current class and
1960/// those inherited by it.
1961void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001962 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001963 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001964 // We can use protocol_iterator here instead of
1965 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001966 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001967 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001968 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001969
1970 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001971 for (const auto *Cat : OI->visible_categories())
1972 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001973
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001974 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1975 while (SD) {
1976 CollectInheritedProtocols(SD, Protocols);
1977 SD = SD->getSuperClass();
1978 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001979 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001980 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001981 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001982 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001983 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001984 // Insert the protocol.
1985 if (!Protocols.insert(
1986 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1987 return;
1988
1989 for (auto *Proto : OP->protocols())
1990 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001991 }
1992}
1993
Jay Foad39c79802011-01-12 09:06:06 +00001994unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001995 unsigned count = 0;
1996 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001997 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001998 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001999
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002000 // Count ivar defined in this class's implementation. This
2001 // includes synthesized ivars.
2002 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002003 count += ImplDecl->ivar_size();
2004
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002005 return count;
2006}
2007
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002008bool ASTContext::isSentinelNullExpr(const Expr *E) {
2009 if (!E)
2010 return false;
2011
2012 // nullptr_t is always treated as null.
2013 if (E->getType()->isNullPtrType()) return true;
2014
2015 if (E->getType()->isAnyPointerType() &&
2016 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2017 Expr::NPC_ValueDependentIsNull))
2018 return true;
2019
2020 // Unfortunately, __null has type 'int'.
2021 if (isa<GNUNullExpr>(E)) return true;
2022
2023 return false;
2024}
2025
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002026/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2027ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2028 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2029 I = ObjCImpls.find(D);
2030 if (I != ObjCImpls.end())
2031 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002032 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002033}
2034/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2035ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2036 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2037 I = ObjCImpls.find(D);
2038 if (I != ObjCImpls.end())
2039 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002040 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002041}
2042
2043/// \brief Set the implementation of ObjCInterfaceDecl.
2044void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2045 ObjCImplementationDecl *ImplD) {
2046 assert(IFaceD && ImplD && "Passed null params");
2047 ObjCImpls[IFaceD] = ImplD;
2048}
2049/// \brief Set the implementation of ObjCCategoryDecl.
2050void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2051 ObjCCategoryImplDecl *ImplD) {
2052 assert(CatD && ImplD && "Passed null params");
2053 ObjCImpls[CatD] = ImplD;
2054}
2055
Chandler Carruth21c90602015-12-30 03:24:14 +00002056const ObjCMethodDecl *
2057ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2058 return ObjCMethodRedecls.lookup(MD);
2059}
2060
2061void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2062 const ObjCMethodDecl *Redecl) {
2063 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2064 ObjCMethodRedecls[MD] = Redecl;
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:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002656 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002657 return type;
2658
2659 // These types can be variably-modified. All these modifications
2660 // preserve structure except as noted by comments.
2661 // TODO: if we ever care about optimizing VLAs, there are no-op
2662 // optimizations available here.
2663 case Type::Pointer:
2664 result = getPointerType(getVariableArrayDecayedType(
2665 cast<PointerType>(ty)->getPointeeType()));
2666 break;
2667
2668 case Type::LValueReference: {
2669 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2670 result = getLValueReferenceType(
2671 getVariableArrayDecayedType(lv->getPointeeType()),
2672 lv->isSpelledAsLValue());
2673 break;
2674 }
2675
2676 case Type::RValueReference: {
2677 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2678 result = getRValueReferenceType(
2679 getVariableArrayDecayedType(lv->getPointeeType()));
2680 break;
2681 }
2682
Eli Friedman0dfb8892011-10-06 23:00:33 +00002683 case Type::Atomic: {
2684 const AtomicType *at = cast<AtomicType>(ty);
2685 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2686 break;
2687 }
2688
John McCall06549462011-01-18 08:40:38 +00002689 case Type::ConstantArray: {
2690 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2691 result = getConstantArrayType(
2692 getVariableArrayDecayedType(cat->getElementType()),
2693 cat->getSize(),
2694 cat->getSizeModifier(),
2695 cat->getIndexTypeCVRQualifiers());
2696 break;
2697 }
2698
2699 case Type::DependentSizedArray: {
2700 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2701 result = getDependentSizedArrayType(
2702 getVariableArrayDecayedType(dat->getElementType()),
2703 dat->getSizeExpr(),
2704 dat->getSizeModifier(),
2705 dat->getIndexTypeCVRQualifiers(),
2706 dat->getBracketsRange());
2707 break;
2708 }
2709
2710 // Turn incomplete types into [*] types.
2711 case Type::IncompleteArray: {
2712 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2713 result = getVariableArrayType(
2714 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002715 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002716 ArrayType::Normal,
2717 iat->getIndexTypeCVRQualifiers(),
2718 SourceRange());
2719 break;
2720 }
2721
2722 // Turn VLA types into [*] types.
2723 case Type::VariableArray: {
2724 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2725 result = getVariableArrayType(
2726 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002727 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002728 ArrayType::Star,
2729 vat->getIndexTypeCVRQualifiers(),
2730 vat->getBracketsRange());
2731 break;
2732 }
2733 }
2734
2735 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002736 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002737}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002738
Steve Naroffcadebd02007-08-30 18:14:25 +00002739/// getVariableArrayType - Returns a non-unique reference to the type for a
2740/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002741QualType ASTContext::getVariableArrayType(QualType EltTy,
2742 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002743 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002744 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002745 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002746 // Since we don't unique expressions, it isn't possible to unique VLA's
2747 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002748 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002749
John McCall33ddac02011-01-19 10:06:00 +00002750 // Be sure to pull qualifiers off the element type.
2751 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2752 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002753 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002754 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002755 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002756 }
2757
John McCall90d1c2d2009-09-24 23:30:46 +00002758 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002759 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002760
2761 VariableArrayTypes.push_back(New);
2762 Types.push_back(New);
2763 return QualType(New, 0);
2764}
2765
Douglas Gregor4619e432008-12-05 23:32:09 +00002766/// getDependentSizedArrayType - Returns a non-unique reference to
2767/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002768/// type.
John McCall33ddac02011-01-19 10:06:00 +00002769QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2770 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002771 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002772 unsigned elementTypeQuals,
2773 SourceRange brackets) const {
2774 assert((!numElements || numElements->isTypeDependent() ||
2775 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002776 "Size must be type- or value-dependent!");
2777
John McCall33ddac02011-01-19 10:06:00 +00002778 // Dependently-sized array types that do not have a specified number
2779 // of elements will have their sizes deduced from a dependent
2780 // initializer. We do no canonicalization here at all, which is okay
2781 // because they can't be used in most locations.
2782 if (!numElements) {
2783 DependentSizedArrayType *newType
2784 = new (*this, TypeAlignment)
2785 DependentSizedArrayType(*this, elementType, QualType(),
2786 numElements, ASM, elementTypeQuals,
2787 brackets);
2788 Types.push_back(newType);
2789 return QualType(newType, 0);
2790 }
2791
2792 // Otherwise, we actually build a new type every time, but we
2793 // also build a canonical type.
2794
2795 SplitQualType canonElementType = getCanonicalType(elementType).split();
2796
Craig Topper36250ad2014-05-12 05:36:57 +00002797 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002798 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002799 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002800 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002801 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002802
John McCall33ddac02011-01-19 10:06:00 +00002803 // Look for an existing type with these properties.
2804 DependentSizedArrayType *canonTy =
2805 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002806
John McCall33ddac02011-01-19 10:06:00 +00002807 // If we don't have one, build one.
2808 if (!canonTy) {
2809 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002810 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002811 QualType(), numElements, ASM, elementTypeQuals,
2812 brackets);
2813 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2814 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002815 }
2816
John McCall33ddac02011-01-19 10:06:00 +00002817 // Apply qualifiers from the element type to the array.
2818 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002819 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002820
David Majnemer16a74702015-07-24 05:54:19 +00002821 // If we didn't need extra canonicalization for the element type or the size
2822 // expression, then just use that as our result.
2823 if (QualType(canonElementType.Ty, 0) == elementType &&
2824 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002825 return canon;
2826
2827 // Otherwise, we need to build a type which follows the spelling
2828 // of the element type.
2829 DependentSizedArrayType *sugaredType
2830 = new (*this, TypeAlignment)
2831 DependentSizedArrayType(*this, elementType, canon, numElements,
2832 ASM, elementTypeQuals, brackets);
2833 Types.push_back(sugaredType);
2834 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002835}
2836
John McCall33ddac02011-01-19 10:06:00 +00002837QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002838 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002839 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002840 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002841 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002842
Craig Topper36250ad2014-05-12 05:36:57 +00002843 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002844 if (IncompleteArrayType *iat =
2845 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2846 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002847
2848 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002849 // either, so fill in the canonical type field. We also have to pull
2850 // qualifiers off the element type.
2851 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002852
John McCall33ddac02011-01-19 10:06:00 +00002853 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2854 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002855 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002856 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002857 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002858
2859 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002860 IncompleteArrayType *existing =
2861 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2862 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002863 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002864
John McCall33ddac02011-01-19 10:06:00 +00002865 IncompleteArrayType *newType = new (*this, TypeAlignment)
2866 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002867
John McCall33ddac02011-01-19 10:06:00 +00002868 IncompleteArrayTypes.InsertNode(newType, insertPos);
2869 Types.push_back(newType);
2870 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002871}
2872
Steve Naroff91fcddb2007-07-18 18:00:27 +00002873/// getVectorType - Return the unique reference to a vector type of
2874/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002875QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002876 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002877 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002878
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002879 // Check if we've already instantiated a vector of this type.
2880 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002881 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002882
Craig Topper36250ad2014-05-12 05:36:57 +00002883 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002884 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2885 return QualType(VTP, 0);
2886
2887 // If the element type isn't canonical, this won't be a canonical type either,
2888 // so fill in the canonical type field.
2889 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002890 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002891 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002893 // Get the new insert position for the node we care about.
2894 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002895 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002896 }
John McCall90d1c2d2009-09-24 23:30:46 +00002897 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002898 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002899 VectorTypes.InsertNode(New, InsertPos);
2900 Types.push_back(New);
2901 return QualType(New, 0);
2902}
2903
Nate Begemance4d7fc2008-04-18 23:10:10 +00002904/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002905/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002906QualType
2907ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002908 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002909
Steve Naroff91fcddb2007-07-18 18:00:27 +00002910 // Check if we've already instantiated a vector of this type.
2911 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002912 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002913 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002914 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002915 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2916 return QualType(VTP, 0);
2917
2918 // If the element type isn't canonical, this won't be a canonical type either,
2919 // so fill in the canonical type field.
2920 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002921 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002922 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002923
Steve Naroff91fcddb2007-07-18 18:00:27 +00002924 // Get the new insert position for the node we care about.
2925 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002926 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002927 }
John McCall90d1c2d2009-09-24 23:30:46 +00002928 ExtVectorType *New = new (*this, TypeAlignment)
2929 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002930 VectorTypes.InsertNode(New, InsertPos);
2931 Types.push_back(New);
2932 return QualType(New, 0);
2933}
2934
Jay Foad39c79802011-01-12 09:06:06 +00002935QualType
2936ASTContext::getDependentSizedExtVectorType(QualType vecType,
2937 Expr *SizeExpr,
2938 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002939 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002940 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002941 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002942
Craig Topper36250ad2014-05-12 05:36:57 +00002943 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002944 DependentSizedExtVectorType *Canon
2945 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2946 DependentSizedExtVectorType *New;
2947 if (Canon) {
2948 // We already have a canonical version of this array type; use it as
2949 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002950 New = new (*this, TypeAlignment)
2951 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2952 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002953 } else {
2954 QualType CanonVecTy = getCanonicalType(vecType);
2955 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002956 New = new (*this, TypeAlignment)
2957 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2958 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002959
2960 DependentSizedExtVectorType *CanonCheck
2961 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2962 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2963 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002964 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2965 } else {
2966 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2967 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002968 New = new (*this, TypeAlignment)
2969 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002970 }
2971 }
Mike Stump11289f42009-09-09 15:08:12 +00002972
Douglas Gregor758a8692009-06-17 21:51:59 +00002973 Types.push_back(New);
2974 return QualType(New, 0);
2975}
2976
John McCall18afab72016-03-01 00:49:02 +00002977/// \brief Determine whether \p T is canonical as the result type of a function.
2978static bool isCanonicalResultType(QualType T) {
2979 return T.isCanonical() &&
2980 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2981 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2982}
2983
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002984/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002985///
Jay Foad39c79802011-01-12 09:06:06 +00002986QualType
2987ASTContext::getFunctionNoProtoType(QualType ResultTy,
2988 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002989 // Unique functions, to guarantee there is only one function of a particular
2990 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002991 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002992 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002993
Craig Topper36250ad2014-05-12 05:36:57 +00002994 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002995 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002996 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002997 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002998
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002999 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003000 if (!isCanonicalResultType(ResultTy)) {
3001 Canonical =
3002 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003003
Chris Lattner47955de2007-01-27 08:37:20 +00003004 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003005 FunctionNoProtoType *NewIP =
3006 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003007 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003008 }
Mike Stump11289f42009-09-09 15:08:12 +00003009
John McCall90d1c2d2009-09-24 23:30:46 +00003010 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003011 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003012 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003013 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003014 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003015}
3016
Douglas Gregora602a152015-10-01 20:20:47 +00003017CanQualType
3018ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3019 CanQualType CanResultType = getCanonicalType(ResultType);
3020
3021 // Canonical result types do not have ARC lifetime qualifiers.
3022 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3023 Qualifiers Qs = CanResultType.getQualifiers();
3024 Qs.removeObjCLifetime();
3025 return CanQualType::CreateUnsafe(
3026 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3027 }
3028
3029 return CanResultType;
3030}
3031
Jay Foad39c79802011-01-12 09:06:06 +00003032QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003033ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003034 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003035 size_t NumArgs = ArgArray.size();
3036
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003037 // Unique functions, to guarantee there is only one function of a particular
3038 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003039 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003040 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3041 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003042
Craig Topper36250ad2014-05-12 05:36:57 +00003043 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003044 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003045 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003046 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003047
3048 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003049 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003050 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003051 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003052 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003053 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003054 isCanonical = false;
3055
3056 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003057 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003058 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003059 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003060 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003061 CanonicalArgs.reserve(NumArgs);
3062 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003063 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003064
John McCalldb40c7f2010-12-14 08:05:40 +00003065 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003066 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003067 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003068
Douglas Gregora602a152015-10-01 20:20:47 +00003069 // Adjust the canonical function result type.
3070 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003071 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003072
Chris Lattnerfd4de792007-01-27 01:15:32 +00003073 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003074 FunctionProtoType *NewIP =
3075 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003076 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003077 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003078
John McCall31168b02011-06-15 23:02:42 +00003079 // FunctionProtoType objects are allocated with extra bytes after
3080 // them for three variable size arrays at the end:
3081 // - parameter types
3082 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003083 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003084 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003085 // expression, or information used to resolve the exception
3086 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003087 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003088 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003089
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 }
John McCall18afab72016-03-01 00:49:02 +00003099
3100 // Put the ExtParameterInfos last. If all were equal, it would make
3101 // more sense to put these before the exception specification, because
3102 // it's much easier to skip past them compared to the elaborate switch
3103 // required to skip the exception specification. However, all is not
3104 // equal; ExtParameterInfos are used to model very uncommon features,
3105 // and it's better not to burden the more common paths.
3106 if (EPI.ExtParameterInfos) {
3107 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3108 }
John McCall31168b02011-06-15 23:02:42 +00003109
John McCalldb40c7f2010-12-14 08:05:40 +00003110 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003111 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003112 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003113 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003114 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003115 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003116}
Chris Lattneref51c202006-11-10 07:17:23 +00003117
Xiuli Pan9c14e282016-01-09 12:53:17 +00003118/// Return pipe type for the specified type.
3119QualType ASTContext::getPipeType(QualType T) const {
3120 llvm::FoldingSetNodeID ID;
3121 PipeType::Profile(ID, T);
3122
3123 void *InsertPos = 0;
3124 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3125 return QualType(PT, 0);
3126
3127 // If the pipe element type isn't canonical, this won't be a canonical type
3128 // either, so fill in the canonical type field.
3129 QualType Canonical;
3130 if (!T.isCanonical()) {
3131 Canonical = getPipeType(getCanonicalType(T));
3132
3133 // Get the new insert position for the node we care about.
3134 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3135 assert(!NewIP && "Shouldn't be in the map!");
3136 (void)NewIP;
3137 }
3138 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3139 Types.push_back(New);
3140 PipeTypes.InsertNode(New, InsertPos);
3141 return QualType(New, 0);
3142}
3143
John McCalle78aac42010-03-10 03:28:59 +00003144#ifndef NDEBUG
3145static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3146 if (!isa<CXXRecordDecl>(D)) return false;
3147 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3148 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3149 return true;
3150 if (RD->getDescribedClassTemplate() &&
3151 !isa<ClassTemplateSpecializationDecl>(RD))
3152 return true;
3153 return false;
3154}
3155#endif
3156
3157/// getInjectedClassNameType - Return the unique reference to the
3158/// injected class name type for the specified templated declaration.
3159QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003160 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003161 assert(NeedsInjectedClassNameType(Decl));
3162 if (Decl->TypeForDecl) {
3163 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003164 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003165 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3166 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3167 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3168 } else {
John McCall424cec92011-01-19 06:33:43 +00003169 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003170 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003171 Decl->TypeForDecl = newType;
3172 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003173 }
3174 return QualType(Decl->TypeForDecl, 0);
3175}
3176
Douglas Gregor83a586e2008-04-13 21:07:44 +00003177/// getTypeDeclType - Return the unique reference to the type for the
3178/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003179QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003180 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003181 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003182
Richard Smithdda56e42011-04-15 14:24:37 +00003183 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003184 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003185
John McCall96f0b5f2010-03-10 06:48:02 +00003186 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3187 "Template type parameter types are always available.");
3188
John McCall81e38502010-02-16 03:57:14 +00003189 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003190 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003191 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003192 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003193 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003194 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003195 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003196 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003197 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003198 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3199 Decl->TypeForDecl = newType;
3200 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003201 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003202 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003203
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003204 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003205}
3206
Chris Lattner32d920b2007-01-26 02:01:53 +00003207/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003208/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003209QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003210ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3211 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003212 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003213
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003214 if (Canonical.isNull())
3215 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003216 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003217 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003218 Decl->TypeForDecl = newType;
3219 Types.push_back(newType);
3220 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003221}
3222
Jay Foad39c79802011-01-12 09:06:06 +00003223QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003224 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3225
Douglas Gregorec9fd132012-01-14 16:38:05 +00003226 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003227 if (PrevDecl->TypeForDecl)
3228 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3229
John McCall424cec92011-01-19 06:33:43 +00003230 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3231 Decl->TypeForDecl = newType;
3232 Types.push_back(newType);
3233 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003234}
3235
Jay Foad39c79802011-01-12 09:06:06 +00003236QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003237 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3238
Douglas Gregorec9fd132012-01-14 16:38:05 +00003239 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003240 if (PrevDecl->TypeForDecl)
3241 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3242
John McCall424cec92011-01-19 06:33:43 +00003243 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3244 Decl->TypeForDecl = newType;
3245 Types.push_back(newType);
3246 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003247}
3248
John McCall81904512011-01-06 01:58:22 +00003249QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3250 QualType modifiedType,
3251 QualType equivalentType) {
3252 llvm::FoldingSetNodeID id;
3253 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3254
Craig Topper36250ad2014-05-12 05:36:57 +00003255 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003256 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3257 if (type) return QualType(type, 0);
3258
3259 QualType canon = getCanonicalType(equivalentType);
3260 type = new (*this, TypeAlignment)
3261 AttributedType(canon, attrKind, modifiedType, equivalentType);
3262
3263 Types.push_back(type);
3264 AttributedTypes.InsertNode(type, insertPos);
3265
3266 return QualType(type, 0);
3267}
3268
John McCallcebee162009-10-18 09:09:24 +00003269/// \brief Retrieve a substitution-result type.
3270QualType
3271ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003272 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003273 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003274 && "replacement types must always be canonical");
3275
3276 llvm::FoldingSetNodeID ID;
3277 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003278 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003279 SubstTemplateTypeParmType *SubstParm
3280 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3281
3282 if (!SubstParm) {
3283 SubstParm = new (*this, TypeAlignment)
3284 SubstTemplateTypeParmType(Parm, Replacement);
3285 Types.push_back(SubstParm);
3286 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3287 }
3288
3289 return QualType(SubstParm, 0);
3290}
3291
Douglas Gregorada4b792011-01-14 02:55:32 +00003292/// \brief Retrieve a
3293QualType ASTContext::getSubstTemplateTypeParmPackType(
3294 const TemplateTypeParmType *Parm,
3295 const TemplateArgument &ArgPack) {
3296#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003297 for (const auto &P : ArgPack.pack_elements()) {
3298 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3299 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003300 }
3301#endif
3302
3303 llvm::FoldingSetNodeID ID;
3304 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003305 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003306 if (SubstTemplateTypeParmPackType *SubstParm
3307 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3308 return QualType(SubstParm, 0);
3309
3310 QualType Canon;
3311 if (!Parm->isCanonicalUnqualified()) {
3312 Canon = getCanonicalType(QualType(Parm, 0));
3313 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3314 ArgPack);
3315 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3316 }
3317
3318 SubstTemplateTypeParmPackType *SubstParm
3319 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3320 ArgPack);
3321 Types.push_back(SubstParm);
3322 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3323 return QualType(SubstParm, 0);
3324}
3325
Douglas Gregoreff93e02009-02-05 23:33:38 +00003326/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003327/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003328/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003329QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003330 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003331 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003332 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003333 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003334 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003335 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003336 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3337
3338 if (TypeParm)
3339 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003340
Chandler Carruth08836322011-05-01 00:51:33 +00003341 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003342 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003343 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003344
3345 TemplateTypeParmType *TypeCheck
3346 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3347 assert(!TypeCheck && "Template type parameter canonical type broken");
3348 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003349 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003350 TypeParm = new (*this, TypeAlignment)
3351 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003352
3353 Types.push_back(TypeParm);
3354 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3355
3356 return QualType(TypeParm, 0);
3357}
3358
John McCalle78aac42010-03-10 03:28:59 +00003359TypeSourceInfo *
3360ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3361 SourceLocation NameLoc,
3362 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003363 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003364 assert(!Name.getAsDependentTemplateName() &&
3365 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003366 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003367
3368 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003369 TemplateSpecializationTypeLoc TL =
3370 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003371 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003372 TL.setTemplateNameLoc(NameLoc);
3373 TL.setLAngleLoc(Args.getLAngleLoc());
3374 TL.setRAngleLoc(Args.getRAngleLoc());
3375 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3376 TL.setArgLocInfo(i, Args[i].getLocInfo());
3377 return DI;
3378}
3379
Mike Stump11289f42009-09-09 15:08:12 +00003380QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003381ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003382 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003383 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003384 assert(!Template.getAsDependentTemplateName() &&
3385 "No dependent template names here!");
3386
John McCall6b51f282009-11-23 01:53:49 +00003387 unsigned NumArgs = Args.size();
3388
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003389 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003390 ArgVec.reserve(NumArgs);
3391 for (unsigned i = 0; i != NumArgs; ++i)
3392 ArgVec.push_back(Args[i].getArgument());
3393
John McCall2408e322010-04-27 00:57:59 +00003394 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003395 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003396}
3397
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003398#ifndef NDEBUG
3399static bool hasAnyPackExpansions(const TemplateArgument *Args,
3400 unsigned NumArgs) {
3401 for (unsigned I = 0; I != NumArgs; ++I)
3402 if (Args[I].isPackExpansion())
3403 return true;
3404
3405 return true;
3406}
3407#endif
3408
John McCall0ad16662009-10-29 08:12:44 +00003409QualType
3410ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003411 const TemplateArgument *Args,
3412 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003413 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003414 assert(!Template.getAsDependentTemplateName() &&
3415 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003416 // Look through qualified template names.
3417 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3418 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003419
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003420 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003421 Template.getAsTemplateDecl() &&
3422 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003423 QualType CanonType;
3424 if (!Underlying.isNull())
3425 CanonType = getCanonicalType(Underlying);
3426 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003427 // We can get here with an alias template when the specialization contains
3428 // a pack expansion that does not match up with a parameter pack.
3429 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3430 "Caller must compute aliased type");
3431 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003432 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3433 NumArgs);
3434 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003435
Douglas Gregora8e02e72009-07-28 23:00:59 +00003436 // Allocate the (non-canonical) template specialization type, but don't
3437 // try to unique it: these types typically have location information that
3438 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003439 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3440 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003441 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003442 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003443 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003444 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3445 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003446
Douglas Gregor8bf42052009-02-09 18:46:07 +00003447 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003448 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003449}
3450
Mike Stump11289f42009-09-09 15:08:12 +00003451QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003452ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3453 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003454 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003455 assert(!Template.getAsDependentTemplateName() &&
3456 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003457
Douglas Gregore29139c2011-03-03 17:04:51 +00003458 // Look through qualified template names.
3459 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3460 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003461
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003462 // Build the canonical template specialization type.
3463 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003464 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003465 CanonArgs.reserve(NumArgs);
3466 for (unsigned I = 0; I != NumArgs; ++I)
3467 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3468
3469 // Determine whether this canonical template specialization type already
3470 // exists.
3471 llvm::FoldingSetNodeID ID;
3472 TemplateSpecializationType::Profile(ID, CanonTemplate,
3473 CanonArgs.data(), NumArgs, *this);
3474
Craig Topper36250ad2014-05-12 05:36:57 +00003475 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003476 TemplateSpecializationType *Spec
3477 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3478
3479 if (!Spec) {
3480 // Allocate a new canonical template specialization type.
3481 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3482 sizeof(TemplateArgument) * NumArgs),
3483 TypeAlignment);
3484 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3485 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003486 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003487 Types.push_back(Spec);
3488 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3489 }
3490
3491 assert(Spec->isDependentType() &&
3492 "Non-dependent template-id type must have a canonical type");
3493 return QualType(Spec, 0);
3494}
3495
3496QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003497ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3498 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003499 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003500 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003501 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003502
Craig Topper36250ad2014-05-12 05:36:57 +00003503 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003504 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003505 if (T)
3506 return QualType(T, 0);
3507
Douglas Gregorc42075a2010-02-04 18:10:26 +00003508 QualType Canon = NamedType;
3509 if (!Canon.isCanonical()) {
3510 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003511 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3512 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003513 (void)CheckT;
3514 }
3515
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003516 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003517 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003518 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003519 return QualType(T, 0);
3520}
3521
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003522QualType
Jay Foad39c79802011-01-12 09:06:06 +00003523ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003524 llvm::FoldingSetNodeID ID;
3525 ParenType::Profile(ID, InnerType);
3526
Craig Topper36250ad2014-05-12 05:36:57 +00003527 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003528 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3529 if (T)
3530 return QualType(T, 0);
3531
3532 QualType Canon = InnerType;
3533 if (!Canon.isCanonical()) {
3534 Canon = getCanonicalType(InnerType);
3535 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3536 assert(!CheckT && "Paren canonical type broken");
3537 (void)CheckT;
3538 }
3539
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003540 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003541 Types.push_back(T);
3542 ParenTypes.InsertNode(T, InsertPos);
3543 return QualType(T, 0);
3544}
3545
Douglas Gregor02085352010-03-31 20:19:30 +00003546QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3547 NestedNameSpecifier *NNS,
3548 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003549 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003550 if (Canon.isNull()) {
3551 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003552 ElaboratedTypeKeyword CanonKeyword = Keyword;
3553 if (Keyword == ETK_None)
3554 CanonKeyword = ETK_Typename;
3555
3556 if (CanonNNS != NNS || CanonKeyword != Keyword)
3557 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003558 }
3559
3560 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003561 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003562
Craig Topper36250ad2014-05-12 05:36:57 +00003563 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003564 DependentNameType *T
3565 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003566 if (T)
3567 return QualType(T, 0);
3568
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003569 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003570 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003571 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003572 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003573}
3574
Mike Stump11289f42009-09-09 15:08:12 +00003575QualType
John McCallc392f372010-06-11 00:33:02 +00003576ASTContext::getDependentTemplateSpecializationType(
3577 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003578 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003579 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003580 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003581 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003582 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003583 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3584 ArgCopy.push_back(Args[I].getArgument());
3585 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3586 ArgCopy.size(),
3587 ArgCopy.data());
3588}
3589
3590QualType
3591ASTContext::getDependentTemplateSpecializationType(
3592 ElaboratedTypeKeyword Keyword,
3593 NestedNameSpecifier *NNS,
3594 const IdentifierInfo *Name,
3595 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003596 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003597 assert((!NNS || NNS->isDependent()) &&
3598 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003599
Douglas Gregorc42075a2010-02-04 18:10:26 +00003600 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003601 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3602 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003603
Craig Topper36250ad2014-05-12 05:36:57 +00003604 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003605 DependentTemplateSpecializationType *T
3606 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003607 if (T)
3608 return QualType(T, 0);
3609
John McCallc392f372010-06-11 00:33:02 +00003610 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003611
John McCallc392f372010-06-11 00:33:02 +00003612 ElaboratedTypeKeyword CanonKeyword = Keyword;
3613 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3614
3615 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003616 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003617 for (unsigned I = 0; I != NumArgs; ++I) {
3618 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3619 if (!CanonArgs[I].structurallyEquals(Args[I]))
3620 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003621 }
3622
John McCallc392f372010-06-11 00:33:02 +00003623 QualType Canon;
3624 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3625 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3626 Name, NumArgs,
3627 CanonArgs.data());
3628
3629 // Find the insert position again.
3630 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3631 }
3632
3633 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3634 sizeof(TemplateArgument) * NumArgs),
3635 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003636 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003637 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003638 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003639 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003640 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003641}
3642
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003643QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003644 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003645 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003646 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003647
3648 assert(Pattern->containsUnexpandedParameterPack() &&
3649 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003650 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003651 PackExpansionType *T
3652 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3653 if (T)
3654 return QualType(T, 0);
3655
3656 QualType Canon;
3657 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003658 Canon = getCanonicalType(Pattern);
3659 // The canonical type might not contain an unexpanded parameter pack, if it
3660 // contains an alias template specialization which ignores one of its
3661 // parameters.
3662 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003663 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003664
Richard Smith68eea502012-07-16 00:20:35 +00003665 // Find the insert position again, in case we inserted an element into
3666 // PackExpansionTypes and invalidated our insert position.
3667 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3668 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003669 }
3670
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003671 T = new (*this, TypeAlignment)
3672 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003673 Types.push_back(T);
3674 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003675 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003676}
3677
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003678/// CmpProtocolNames - Comparison predicate for sorting protocols
3679/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003680static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3681 ObjCProtocolDecl *const *RHS) {
3682 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003683}
3684
Craig Topper1f26d5b2016-01-03 19:43:23 +00003685static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3686 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003687
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003688 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3689 return false;
3690
Craig Topper1f26d5b2016-01-03 19:43:23 +00003691 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003692 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003693 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003694 return false;
3695 return true;
3696}
3697
Craig Topper6a8c1512015-10-22 01:56:18 +00003698static void
3699SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003700 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003701 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003702
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003703 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003704 for (ObjCProtocolDecl *&P : Protocols)
3705 P = P->getCanonicalDecl();
3706
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003707 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003708 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3709 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003710}
3711
John McCall8b07ec22010-05-15 11:32:37 +00003712QualType ASTContext::getObjCObjectType(QualType BaseType,
3713 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003714 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003715 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003716 llvm::makeArrayRef(Protocols, NumProtocols),
3717 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003718}
3719
3720QualType ASTContext::getObjCObjectType(
3721 QualType baseType,
3722 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003723 ArrayRef<ObjCProtocolDecl *> protocols,
3724 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003725 // If the base type is an interface and there aren't any protocols or
3726 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003727 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3728 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003729 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003730
3731 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003732 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003733 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003734 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003735 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3736 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003737
Douglas Gregore9d95f12015-07-07 03:57:35 +00003738 // Determine the type arguments to be used for canonicalization,
3739 // which may be explicitly specified here or written on the base
3740 // type.
3741 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3742 if (effectiveTypeArgs.empty()) {
3743 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3744 effectiveTypeArgs = baseObject->getTypeArgs();
3745 }
John McCallfc93cf92009-10-22 22:37:11 +00003746
Douglas Gregore9d95f12015-07-07 03:57:35 +00003747 // Build the canonical type, which has the canonical base type and a
3748 // sorted-and-uniqued list of protocols and the type arguments
3749 // canonicalized.
3750 QualType canonical;
3751 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3752 effectiveTypeArgs.end(),
3753 [&](QualType type) {
3754 return type.isCanonical();
3755 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003756 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003757 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3758 // Determine the canonical type arguments.
3759 ArrayRef<QualType> canonTypeArgs;
3760 SmallVector<QualType, 4> canonTypeArgsVec;
3761 if (!typeArgsAreCanonical) {
3762 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3763 for (auto typeArg : effectiveTypeArgs)
3764 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3765 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003766 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003767 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003768 }
3769
Douglas Gregore9d95f12015-07-07 03:57:35 +00003770 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3771 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3772 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003773 canonProtocolsVec.append(protocols.begin(), protocols.end());
3774 SortAndUniqueProtocols(canonProtocolsVec);
3775 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003776 } else {
3777 canonProtocols = protocols;
3778 }
3779
3780 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003781 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003782
John McCallfc93cf92009-10-22 22:37:11 +00003783 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003784 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3785 }
3786
Douglas Gregore9d95f12015-07-07 03:57:35 +00003787 unsigned size = sizeof(ObjCObjectTypeImpl);
3788 size += typeArgs.size() * sizeof(QualType);
3789 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3790 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003791 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003792 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3793 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003794
3795 Types.push_back(T);
3796 ObjCObjectTypes.InsertNode(T, InsertPos);
3797 return QualType(T, 0);
3798}
3799
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003800/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3801/// protocol list adopt all protocols in QT's qualified-id protocol
3802/// list.
3803bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3804 ObjCInterfaceDecl *IC) {
3805 if (!QT->isObjCQualifiedIdType())
3806 return false;
3807
3808 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3809 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003810 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003811 if (!IC->ClassImplementsProtocol(Proto, false))
3812 return false;
3813 }
3814 return true;
3815 }
3816 return false;
3817}
3818
3819/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3820/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3821/// of protocols.
3822bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3823 ObjCInterfaceDecl *IDecl) {
3824 if (!QT->isObjCQualifiedIdType())
3825 return false;
3826 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3827 if (!OPT)
3828 return false;
3829 if (!IDecl->hasDefinition())
3830 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003831 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3832 CollectInheritedProtocols(IDecl, InheritedProtocols);
3833 if (InheritedProtocols.empty())
3834 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003835 // Check that if every protocol in list of id<plist> conforms to a protcol
3836 // of IDecl's, then bridge casting is ok.
3837 bool Conforms = false;
3838 for (auto *Proto : OPT->quals()) {
3839 Conforms = false;
3840 for (auto *PI : InheritedProtocols) {
3841 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3842 Conforms = true;
3843 break;
3844 }
3845 }
3846 if (!Conforms)
3847 break;
3848 }
3849 if (Conforms)
3850 return true;
3851
Aaron Ballman83731462014-03-17 16:14:00 +00003852 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003853 // If both the right and left sides have qualifiers.
3854 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003855 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003856 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003857 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003858 break;
3859 }
3860 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003861 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003862 }
3863 return true;
3864}
3865
John McCall8b07ec22010-05-15 11:32:37 +00003866/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3867/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003868QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003869 llvm::FoldingSetNodeID ID;
3870 ObjCObjectPointerType::Profile(ID, ObjectT);
3871
Craig Topper36250ad2014-05-12 05:36:57 +00003872 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003873 if (ObjCObjectPointerType *QT =
3874 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3875 return QualType(QT, 0);
3876
3877 // Find the canonical object type.
3878 QualType Canonical;
3879 if (!ObjectT.isCanonical()) {
3880 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3881
3882 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003883 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3884 }
3885
Douglas Gregorf85bee62010-02-08 22:59:26 +00003886 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003887 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3888 ObjCObjectPointerType *QType =
3889 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003890
Steve Narofffb4330f2009-06-17 22:40:22 +00003891 Types.push_back(QType);
3892 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003893 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003894}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003895
Douglas Gregor1c283312010-08-11 12:19:30 +00003896/// getObjCInterfaceType - Return the unique reference to the type for the
3897/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003898QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3899 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003900 if (Decl->TypeForDecl)
3901 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003902
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003903 if (PrevDecl) {
3904 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3905 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3906 return QualType(PrevDecl->TypeForDecl, 0);
3907 }
3908
Douglas Gregor7671e532011-12-16 16:34:57 +00003909 // Prefer the definition, if there is one.
3910 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3911 Decl = Def;
3912
Douglas Gregor1c283312010-08-11 12:19:30 +00003913 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3914 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3915 Decl->TypeForDecl = T;
3916 Types.push_back(T);
3917 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003918}
3919
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003920/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3921/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003922/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003923/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003924/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003925QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003926 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003927 if (tofExpr->isTypeDependent()) {
3928 llvm::FoldingSetNodeID ID;
3929 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003930
Craig Topper36250ad2014-05-12 05:36:57 +00003931 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003932 DependentTypeOfExprType *Canon
3933 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3934 if (Canon) {
3935 // We already have a "canonical" version of an identical, dependent
3936 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003937 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003938 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003939 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003940 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003941 Canon
3942 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003943 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3944 toe = Canon;
3945 }
3946 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003947 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003948 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003949 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003950 Types.push_back(toe);
3951 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003952}
3953
Steve Naroffa773cd52007-08-01 18:02:17 +00003954/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003955/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003956/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003957/// an issue. This doesn't affect the type checker, since it operates
3958/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003959QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003960 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003961 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003962 Types.push_back(tot);
3963 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003964}
3965
Richard Smith8eb1d322014-06-05 20:13:13 +00003966/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3967/// nodes. This would never be helpful, since each such type has its own
3968/// expression, and would not give a significant memory saving, since there
3969/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003970QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003971 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003972
3973 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003974 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003975 // unique dependent type. Two such decltype-specifiers refer to the same
3976 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003977 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003978 llvm::FoldingSetNodeID ID;
3979 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003980
Craig Topper36250ad2014-05-12 05:36:57 +00003981 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003982 DependentDecltypeType *Canon
3983 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003984 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003985 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003986 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003987 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003988 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003989 dt = new (*this, TypeAlignment)
3990 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003991 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003992 dt = new (*this, TypeAlignment)
3993 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003994 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003995 Types.push_back(dt);
3996 return QualType(dt, 0);
3997}
3998
Alexis Hunte852b102011-05-24 22:41:36 +00003999/// getUnaryTransformationType - We don't unique these, since the memory
4000/// savings are minimal and these are rare.
4001QualType ASTContext::getUnaryTransformType(QualType BaseType,
4002 QualType UnderlyingType,
4003 UnaryTransformType::UTTKind Kind)
4004 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004005 UnaryTransformType *ut = nullptr;
4006
4007 if (BaseType->isDependentType()) {
4008 // Look in the folding set for an existing type.
4009 llvm::FoldingSetNodeID ID;
4010 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4011
4012 void *InsertPos = nullptr;
4013 DependentUnaryTransformType *Canon
4014 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4015
4016 if (!Canon) {
4017 // Build a new, canonical __underlying_type(type) type.
4018 Canon = new (*this, TypeAlignment)
4019 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4020 Kind);
4021 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4022 }
4023 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4024 QualType(), Kind,
4025 QualType(Canon, 0));
4026 } else {
4027 QualType CanonType = getCanonicalType(UnderlyingType);
4028 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4029 UnderlyingType, Kind,
4030 CanonType);
4031 }
4032 Types.push_back(ut);
4033 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004034}
4035
Richard Smith2a7d4812013-05-04 07:00:32 +00004036/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4037/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4038/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004039QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004040 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004041 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004042 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004043
Richard Smith2a7d4812013-05-04 07:00:32 +00004044 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004045 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004046 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004047 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004048 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4049 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004050
Richard Smith74aeef52013-04-26 16:15:35 +00004051 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004052 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004053 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004054 Types.push_back(AT);
4055 if (InsertPos)
4056 AutoTypes.InsertNode(AT, InsertPos);
4057 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004058}
4059
Eli Friedman0dfb8892011-10-06 23:00:33 +00004060/// getAtomicType - Return the uniqued reference to the atomic type for
4061/// the given value type.
4062QualType ASTContext::getAtomicType(QualType T) const {
4063 // Unique pointers, to guarantee there is only one pointer of a particular
4064 // structure.
4065 llvm::FoldingSetNodeID ID;
4066 AtomicType::Profile(ID, T);
4067
Craig Topper36250ad2014-05-12 05:36:57 +00004068 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004069 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4070 return QualType(AT, 0);
4071
4072 // If the atomic value type isn't canonical, this won't be a canonical type
4073 // either, so fill in the canonical type field.
4074 QualType Canonical;
4075 if (!T.isCanonical()) {
4076 Canonical = getAtomicType(getCanonicalType(T));
4077
4078 // Get the new insert position for the node we care about.
4079 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004080 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004081 }
4082 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4083 Types.push_back(New);
4084 AtomicTypes.InsertNode(New, InsertPos);
4085 return QualType(New, 0);
4086}
4087
Richard Smith02e85f32011-04-14 22:09:26 +00004088/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4089QualType ASTContext::getAutoDeductType() const {
4090 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004091 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004092 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004093 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004094 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004095 return AutoDeductTy;
4096}
4097
4098/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4099QualType ASTContext::getAutoRRefDeductType() const {
4100 if (AutoRRefDeductTy.isNull())
4101 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4102 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4103 return AutoRRefDeductTy;
4104}
4105
Chris Lattnerfb072462007-01-23 05:45:31 +00004106/// getTagDeclType - Return the unique reference to the type for the
4107/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004108QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004109 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004110 // FIXME: What is the design on getTagDeclType when it requires casting
4111 // away const? mutable?
4112 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004113}
4114
Mike Stump11289f42009-09-09 15:08:12 +00004115/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4116/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4117/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004118CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004119 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004120}
Chris Lattnerfb072462007-01-23 05:45:31 +00004121
Hans Wennborg27541db2011-10-27 08:29:09 +00004122/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4123CanQualType ASTContext::getIntMaxType() const {
4124 return getFromTargetType(Target->getIntMaxType());
4125}
4126
4127/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4128CanQualType ASTContext::getUIntMaxType() const {
4129 return getFromTargetType(Target->getUIntMaxType());
4130}
4131
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004132/// getSignedWCharType - Return the type of "signed wchar_t".
4133/// Used when in C++, as a GCC extension.
4134QualType ASTContext::getSignedWCharType() const {
4135 // FIXME: derive from "Target" ?
4136 return WCharTy;
4137}
4138
4139/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4140/// Used when in C++, as a GCC extension.
4141QualType ASTContext::getUnsignedWCharType() const {
4142 // FIXME: derive from "Target" ?
4143 return UnsignedIntTy;
4144}
4145
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004146QualType ASTContext::getIntPtrType() const {
4147 return getFromTargetType(Target->getIntPtrType());
4148}
4149
4150QualType ASTContext::getUIntPtrType() const {
4151 return getCorrespondingUnsignedType(getIntPtrType());
4152}
4153
Hans Wennborg27541db2011-10-27 08:29:09 +00004154/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004155/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4156QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004157 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004158}
4159
Eli Friedman4e91899e2012-11-27 02:58:24 +00004160/// \brief Return the unique type for "pid_t" defined in
4161/// <sys/types.h>. We need this to compute the correct type for vfork().
4162QualType ASTContext::getProcessIDType() const {
4163 return getFromTargetType(Target->getProcessIDType());
4164}
4165
Chris Lattnera21ad802008-04-02 05:18:44 +00004166//===----------------------------------------------------------------------===//
4167// Type Operators
4168//===----------------------------------------------------------------------===//
4169
Jay Foad39c79802011-01-12 09:06:06 +00004170CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004171 // Push qualifiers into arrays, and then discard any remaining
4172 // qualifiers.
4173 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004174 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004175 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004176 QualType Result;
4177 if (isa<ArrayType>(Ty)) {
4178 Result = getArrayDecayedType(QualType(Ty,0));
4179 } else if (isa<FunctionType>(Ty)) {
4180 Result = getPointerType(QualType(Ty, 0));
4181 } else {
4182 Result = QualType(Ty, 0);
4183 }
4184
4185 return CanQualType::CreateUnsafe(Result);
4186}
4187
John McCall6c9dd522011-01-18 07:41:22 +00004188QualType ASTContext::getUnqualifiedArrayType(QualType type,
4189 Qualifiers &quals) {
4190 SplitQualType splitType = type.getSplitUnqualifiedType();
4191
4192 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4193 // the unqualified desugared type and then drops it on the floor.
4194 // We then have to strip that sugar back off with
4195 // getUnqualifiedDesugaredType(), which is silly.
4196 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004197 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004198
4199 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004200 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004201 quals = splitType.Quals;
4202 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004203 }
4204
John McCall6c9dd522011-01-18 07:41:22 +00004205 // Otherwise, recurse on the array's element type.
4206 QualType elementType = AT->getElementType();
4207 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4208
4209 // If that didn't change the element type, AT has no qualifiers, so we
4210 // can just use the results in splitType.
4211 if (elementType == unqualElementType) {
4212 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004213 quals = splitType.Quals;
4214 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004215 }
4216
4217 // Otherwise, add in the qualifiers from the outermost type, then
4218 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004219 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004220
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004221 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004222 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004223 CAT->getSizeModifier(), 0);
4224 }
4225
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004226 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004227 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004228 }
4229
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004230 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004231 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004232 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004233 VAT->getSizeModifier(),
4234 VAT->getIndexTypeCVRQualifiers(),
4235 VAT->getBracketsRange());
4236 }
4237
4238 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004239 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004240 DSAT->getSizeModifier(), 0,
4241 SourceRange());
4242}
4243
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004244/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4245/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4246/// they point to and return true. If T1 and T2 aren't pointer types
4247/// or pointer-to-member types, or if they are not similar at this
4248/// level, returns false and leaves T1 and T2 unchanged. Top-level
4249/// qualifiers on T1 and T2 are ignored. This function will typically
4250/// be called in a loop that successively "unwraps" pointer and
4251/// pointer-to-member types to compare them at each level.
4252bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4253 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4254 *T2PtrType = T2->getAs<PointerType>();
4255 if (T1PtrType && T2PtrType) {
4256 T1 = T1PtrType->getPointeeType();
4257 T2 = T2PtrType->getPointeeType();
4258 return true;
4259 }
4260
4261 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4262 *T2MPType = T2->getAs<MemberPointerType>();
4263 if (T1MPType && T2MPType &&
4264 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4265 QualType(T2MPType->getClass(), 0))) {
4266 T1 = T1MPType->getPointeeType();
4267 T2 = T2MPType->getPointeeType();
4268 return true;
4269 }
4270
David Blaikiebbafb8a2012-03-11 07:00:24 +00004271 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004272 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4273 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4274 if (T1OPType && T2OPType) {
4275 T1 = T1OPType->getPointeeType();
4276 T2 = T2OPType->getPointeeType();
4277 return true;
4278 }
4279 }
4280
4281 // FIXME: Block pointers, too?
4282
4283 return false;
4284}
4285
Jay Foad39c79802011-01-12 09:06:06 +00004286DeclarationNameInfo
4287ASTContext::getNameForTemplate(TemplateName Name,
4288 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004289 switch (Name.getKind()) {
4290 case TemplateName::QualifiedTemplate:
4291 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004292 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004293 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4294 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004295
John McCalld9dfe3a2011-06-30 08:33:18 +00004296 case TemplateName::OverloadedTemplate: {
4297 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4298 // DNInfo work in progress: CHECKME: what about DNLoc?
4299 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4300 }
4301
4302 case TemplateName::DependentTemplate: {
4303 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004304 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004305 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004306 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4307 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004308 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004309 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4310 // DNInfo work in progress: FIXME: source locations?
4311 DeclarationNameLoc DNLoc;
4312 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4313 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4314 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004315 }
4316 }
4317
John McCalld9dfe3a2011-06-30 08:33:18 +00004318 case TemplateName::SubstTemplateTemplateParm: {
4319 SubstTemplateTemplateParmStorage *subst
4320 = Name.getAsSubstTemplateTemplateParm();
4321 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4322 NameLoc);
4323 }
4324
4325 case TemplateName::SubstTemplateTemplateParmPack: {
4326 SubstTemplateTemplateParmPackStorage *subst
4327 = Name.getAsSubstTemplateTemplateParmPack();
4328 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4329 NameLoc);
4330 }
4331 }
4332
4333 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004334}
4335
Jay Foad39c79802011-01-12 09:06:06 +00004336TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004337 switch (Name.getKind()) {
4338 case TemplateName::QualifiedTemplate:
4339 case TemplateName::Template: {
4340 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004341 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004342 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004343 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4344
4345 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004346 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004347 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004348
John McCalld9dfe3a2011-06-30 08:33:18 +00004349 case TemplateName::OverloadedTemplate:
4350 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004351
John McCalld9dfe3a2011-06-30 08:33:18 +00004352 case TemplateName::DependentTemplate: {
4353 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4354 assert(DTN && "Non-dependent template names must refer to template decls.");
4355 return DTN->CanonicalTemplateName;
4356 }
4357
4358 case TemplateName::SubstTemplateTemplateParm: {
4359 SubstTemplateTemplateParmStorage *subst
4360 = Name.getAsSubstTemplateTemplateParm();
4361 return getCanonicalTemplateName(subst->getReplacement());
4362 }
4363
4364 case TemplateName::SubstTemplateTemplateParmPack: {
4365 SubstTemplateTemplateParmPackStorage *subst
4366 = Name.getAsSubstTemplateTemplateParmPack();
4367 TemplateTemplateParmDecl *canonParameter
4368 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4369 TemplateArgument canonArgPack
4370 = getCanonicalTemplateArgument(subst->getArgumentPack());
4371 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4372 }
4373 }
4374
4375 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004376}
4377
Douglas Gregoradee3e32009-11-11 23:06:43 +00004378bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4379 X = getCanonicalTemplateName(X);
4380 Y = getCanonicalTemplateName(Y);
4381 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4382}
4383
Mike Stump11289f42009-09-09 15:08:12 +00004384TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004385ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004386 switch (Arg.getKind()) {
4387 case TemplateArgument::Null:
4388 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004389
Douglas Gregora8e02e72009-07-28 23:00:59 +00004390 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004391 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004392
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004393 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004394 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004395 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004396 }
Mike Stump11289f42009-09-09 15:08:12 +00004397
Eli Friedmanb826a002012-09-26 02:36:12 +00004398 case TemplateArgument::NullPtr:
4399 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4400 /*isNullPtr*/true);
4401
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004402 case TemplateArgument::Template:
4403 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004404
4405 case TemplateArgument::TemplateExpansion:
4406 return TemplateArgument(getCanonicalTemplateName(
4407 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004408 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004409
Douglas Gregora8e02e72009-07-28 23:00:59 +00004410 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004411 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004412
Douglas Gregora8e02e72009-07-28 23:00:59 +00004413 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004414 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004415
Douglas Gregora8e02e72009-07-28 23:00:59 +00004416 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004417 if (Arg.pack_size() == 0)
4418 return Arg;
4419
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004420 TemplateArgument *CanonArgs
4421 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004422 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004423 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004424 AEnd = Arg.pack_end();
4425 A != AEnd; (void)++A, ++Idx)
4426 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004427
Benjamin Kramercce63472015-08-05 09:40:22 +00004428 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004429 }
4430 }
4431
4432 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004433 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004434}
4435
Douglas Gregor333489b2009-03-27 23:10:48 +00004436NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004437ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004438 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004439 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004440
4441 switch (NNS->getKind()) {
4442 case NestedNameSpecifier::Identifier:
4443 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004444 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004445 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4446 NNS->getAsIdentifier());
4447
4448 case NestedNameSpecifier::Namespace:
4449 // A namespace is canonical; build a nested-name-specifier with
4450 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004451 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004452 NNS->getAsNamespace()->getOriginalNamespace());
4453
4454 case NestedNameSpecifier::NamespaceAlias:
4455 // A namespace is canonical; build a nested-name-specifier with
4456 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004457 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004458 NNS->getAsNamespaceAlias()->getNamespace()
4459 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004460
4461 case NestedNameSpecifier::TypeSpec:
4462 case NestedNameSpecifier::TypeSpecWithTemplate: {
4463 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004464
4465 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4466 // break it apart into its prefix and identifier, then reconsititute those
4467 // as the canonical nested-name-specifier. This is required to canonicalize
4468 // a dependent nested-name-specifier involving typedefs of dependent-name
4469 // types, e.g.,
4470 // typedef typename T::type T1;
4471 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004472 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4473 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004474 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004475
Eli Friedman5358a0a2012-03-03 04:09:56 +00004476 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4477 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4478 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004479 return NestedNameSpecifier::Create(*this, nullptr, false,
4480 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004481 }
4482
4483 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004484 case NestedNameSpecifier::Super:
4485 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004486 return NNS;
4487 }
4488
David Blaikie8a40f702012-01-17 06:56:22 +00004489 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004490}
4491
Jay Foad39c79802011-01-12 09:06:06 +00004492const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004493 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004494 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004495 // Handle the common positive case fast.
4496 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4497 return AT;
4498 }
Mike Stump11289f42009-09-09 15:08:12 +00004499
John McCall8ccfcb52009-09-24 19:53:00 +00004500 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004501 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004502 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004503
John McCall8ccfcb52009-09-24 19:53:00 +00004504 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004505 // implements C99 6.7.3p8: "If the specification of an array type includes
4506 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004507
Chris Lattner7adf0762008-08-04 07:31:14 +00004508 // If we get here, we either have type qualifiers on the type, or we have
4509 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004510 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004511
John McCall33ddac02011-01-19 10:06:00 +00004512 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004513 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004514
Chris Lattner7adf0762008-08-04 07:31:14 +00004515 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004516 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004517 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004518 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004519
Chris Lattner7adf0762008-08-04 07:31:14 +00004520 // Otherwise, we have an array and we have qualifiers on it. Push the
4521 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004522 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004523
Chris Lattner7adf0762008-08-04 07:31:14 +00004524 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4525 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4526 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004527 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004528 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4529 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4530 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004531 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004532
Mike Stump11289f42009-09-09 15:08:12 +00004533 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004534 = dyn_cast<DependentSizedArrayType>(ATy))
4535 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004536 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004537 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004538 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004539 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004540 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004541
Chris Lattner7adf0762008-08-04 07:31:14 +00004542 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004543 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004544 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004545 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004546 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004547 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004548}
4549
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004550QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004551 if (T->isArrayType() || T->isFunctionType())
4552 return getDecayedType(T);
4553 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004554}
4555
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004556QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004557 T = getVariableArrayDecayedType(T);
4558 T = getAdjustedParameterType(T);
4559 return T.getUnqualifiedType();
4560}
4561
David Majnemerd09a51c2015-03-03 01:50:05 +00004562QualType ASTContext::getExceptionObjectType(QualType T) const {
4563 // C++ [except.throw]p3:
4564 // A throw-expression initializes a temporary object, called the exception
4565 // object, the type of which is determined by removing any top-level
4566 // cv-qualifiers from the static type of the operand of throw and adjusting
4567 // the type from "array of T" or "function returning T" to "pointer to T"
4568 // or "pointer to function returning T", [...]
4569 T = getVariableArrayDecayedType(T);
4570 if (T->isArrayType() || T->isFunctionType())
4571 T = getDecayedType(T);
4572 return T.getUnqualifiedType();
4573}
4574
Chris Lattnera21ad802008-04-02 05:18:44 +00004575/// getArrayDecayedType - Return the properly qualified result of decaying the
4576/// specified array type to a pointer. This operation is non-trivial when
4577/// handling typedefs etc. The canonical type of "T" must be an array type,
4578/// this returns a pointer to a properly qualified element of the array.
4579///
4580/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004581QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004582 // Get the element type with 'getAsArrayType' so that we don't lose any
4583 // typedefs in the element type of the array. This also handles propagation
4584 // of type qualifiers from the array type into the element type if present
4585 // (C99 6.7.3p8).
4586 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4587 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004588
Chris Lattner7adf0762008-08-04 07:31:14 +00004589 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004590
4591 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004592 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004593}
4594
John McCall33ddac02011-01-19 10:06:00 +00004595QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4596 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004597}
4598
John McCall33ddac02011-01-19 10:06:00 +00004599QualType ASTContext::getBaseElementType(QualType type) const {
4600 Qualifiers qs;
4601 while (true) {
4602 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004603 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004604 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004605
John McCall33ddac02011-01-19 10:06:00 +00004606 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004607 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004608 }
Mike Stump11289f42009-09-09 15:08:12 +00004609
John McCall33ddac02011-01-19 10:06:00 +00004610 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004611}
4612
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004613/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004614uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004615ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4616 uint64_t ElementCount = 1;
4617 do {
4618 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004619 CA = dyn_cast_or_null<ConstantArrayType>(
4620 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004621 } while (CA);
4622 return ElementCount;
4623}
4624
Steve Naroff0af91202007-04-27 21:51:21 +00004625/// getFloatingRank - Return a relative rank for floating point types.
4626/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004627static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004628 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004629 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004630
John McCall9dd450b2009-09-21 23:43:11 +00004631 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4632 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004633 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004634 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004635 case BuiltinType::Float: return FloatRank;
4636 case BuiltinType::Double: return DoubleRank;
4637 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004638 }
4639}
4640
Mike Stump11289f42009-09-09 15:08:12 +00004641/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4642/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004643/// 'typeDomain' is a real floating point or complex type.
4644/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004645QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4646 QualType Domain) const {
4647 FloatingRank EltRank = getFloatingRank(Size);
4648 if (Domain->isComplexType()) {
4649 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004650 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004651 case FloatRank: return FloatComplexTy;
4652 case DoubleRank: return DoubleComplexTy;
4653 case LongDoubleRank: return LongDoubleComplexTy;
4654 }
Steve Naroff0af91202007-04-27 21:51:21 +00004655 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004656
4657 assert(Domain->isRealFloatingType() && "Unknown domain!");
4658 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004659 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004660 case FloatRank: return FloatTy;
4661 case DoubleRank: return DoubleTy;
4662 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004663 }
David Blaikief47fa302012-01-17 02:30:50 +00004664 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004665}
4666
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004667/// getFloatingTypeOrder - Compare the rank of the two specified floating
4668/// point types, ignoring the domain of the type (i.e. 'double' ==
4669/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004670/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004671int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004672 FloatingRank LHSR = getFloatingRank(LHS);
4673 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004674
Chris Lattnerb90739d2008-04-06 23:38:49 +00004675 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004676 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004677 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004678 return 1;
4679 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004680}
4681
Chris Lattner76a00cf2008-04-06 22:59:24 +00004682/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4683/// routine will assert if passed a built-in type that isn't an integer or enum,
4684/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004685unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004686 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004687
Chris Lattner76a00cf2008-04-06 22:59:24 +00004688 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004689 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004690 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004691 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004692 case BuiltinType::Char_S:
4693 case BuiltinType::Char_U:
4694 case BuiltinType::SChar:
4695 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004696 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004697 case BuiltinType::Short:
4698 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004699 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004700 case BuiltinType::Int:
4701 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004702 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004703 case BuiltinType::Long:
4704 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004705 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004706 case BuiltinType::LongLong:
4707 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004708 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004709 case BuiltinType::Int128:
4710 case BuiltinType::UInt128:
4711 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004712 }
4713}
4714
Eli Friedman629ffb92009-08-20 04:21:42 +00004715/// \brief Whether this is a promotable bitfield reference according
4716/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4717///
4718/// \returns the type this bit-field will promote to, or NULL if no
4719/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004720QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004721 if (E->isTypeDependent() || E->isValueDependent())
4722 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004723
4724 // FIXME: We should not do this unless E->refersToBitField() is true. This
4725 // matters in C where getSourceBitField() will find bit-fields for various
4726 // cases where the source expression is not a bit-field designator.
4727
John McCalld25db7e2013-05-06 21:39:12 +00004728 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004729 if (!Field)
4730 return QualType();
4731
4732 QualType FT = Field->getType();
4733
Richard Smithcaf33902011-10-10 18:28:20 +00004734 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004735 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004736 // C++ [conv.prom]p5:
4737 // A prvalue for an integral bit-field can be converted to a prvalue of type
4738 // int if int can represent all the values of the bit-field; otherwise, it
4739 // can be converted to unsigned int if unsigned int can represent all the
4740 // values of the bit-field. If the bit-field is larger yet, no integral
4741 // promotion applies to it.
4742 // C11 6.3.1.1/2:
4743 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4744 // If an int can represent all values of the original type (as restricted by
4745 // the width, for a bit-field), the value is converted to an int; otherwise,
4746 // it is converted to an unsigned int.
4747 //
4748 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4749 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004750 if (BitWidth < IntSize)
4751 return IntTy;
4752
4753 if (BitWidth == IntSize)
4754 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4755
4756 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004757 // like the base type. GCC has some weird bugs in this area that we
4758 // deliberately do not follow (GCC follows a pre-standard resolution to
4759 // C's DR315 which treats bit-width as being part of the type, and this leaks
4760 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004761 return QualType();
4762}
4763
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004764/// getPromotedIntegerType - Returns the type that Promotable will
4765/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4766/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004767QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004768 assert(!Promotable.isNull());
4769 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004770 if (const EnumType *ET = Promotable->getAs<EnumType>())
4771 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004772
4773 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4774 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4775 // (3.9.1) can be converted to a prvalue of the first of the following
4776 // types that can represent all the values of its underlying type:
4777 // int, unsigned int, long int, unsigned long int, long long int, or
4778 // unsigned long long int [...]
4779 // FIXME: Is there some better way to compute this?
4780 if (BT->getKind() == BuiltinType::WChar_S ||
4781 BT->getKind() == BuiltinType::WChar_U ||
4782 BT->getKind() == BuiltinType::Char16 ||
4783 BT->getKind() == BuiltinType::Char32) {
4784 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4785 uint64_t FromSize = getTypeSize(BT);
4786 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4787 LongLongTy, UnsignedLongLongTy };
4788 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4789 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4790 if (FromSize < ToSize ||
4791 (FromSize == ToSize &&
4792 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4793 return PromoteTypes[Idx];
4794 }
4795 llvm_unreachable("char type should fit into long long");
4796 }
4797 }
4798
4799 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004800 if (Promotable->isSignedIntegerType())
4801 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004802 uint64_t PromotableSize = getIntWidth(Promotable);
4803 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004804 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4805 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4806}
4807
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004808/// \brief Recurses in pointer/array types until it finds an objc retainable
4809/// type and returns its ownership.
4810Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4811 while (!T.isNull()) {
4812 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4813 return T.getObjCLifetime();
4814 if (T->isArrayType())
4815 T = getBaseElementType(T);
4816 else if (const PointerType *PT = T->getAs<PointerType>())
4817 T = PT->getPointeeType();
4818 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004819 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004820 else
4821 break;
4822 }
4823
4824 return Qualifiers::OCL_None;
4825}
4826
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004827static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4828 // Incomplete enum types are not treated as integer types.
4829 // FIXME: In C++, enum types are never integer types.
4830 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4831 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004832 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004833}
4834
Mike Stump11289f42009-09-09 15:08:12 +00004835/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004836/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004837/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004838int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004839 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4840 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004841
4842 // Unwrap enums to their underlying type.
4843 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4844 LHSC = getIntegerTypeForEnum(ET);
4845 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4846 RHSC = getIntegerTypeForEnum(ET);
4847
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004848 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004849
Chris Lattner76a00cf2008-04-06 22:59:24 +00004850 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4851 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004852
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004853 unsigned LHSRank = getIntegerRank(LHSC);
4854 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004855
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004856 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4857 if (LHSRank == RHSRank) return 0;
4858 return LHSRank > RHSRank ? 1 : -1;
4859 }
Mike Stump11289f42009-09-09 15:08:12 +00004860
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004861 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4862 if (LHSUnsigned) {
4863 // If the unsigned [LHS] type is larger, return it.
4864 if (LHSRank >= RHSRank)
4865 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004866
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004867 // If the signed type can represent all values of the unsigned type, it
4868 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004869 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004870 return -1;
4871 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004872
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004873 // If the unsigned [RHS] type is larger, return it.
4874 if (RHSRank >= LHSRank)
4875 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004876
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004877 // If the signed type can represent all values of the unsigned type, it
4878 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004879 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004880 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004881}
Anders Carlsson98f07902007-08-17 05:31:46 +00004882
Ben Langmuirf5416742016-02-04 00:55:24 +00004883TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004884 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004885 assert(!CFConstantStringTagDecl &&
4886 "tag and typedef should be initialized together");
4887 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4888 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004889
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004890 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00004891 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00004892
Anders Carlsson98f07902007-08-17 05:31:46 +00004893 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004894 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004895 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004896 // int flags;
4897 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004898 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00004899 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004900 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004901 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00004902 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004903 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004904 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00004905
Anders Carlsson98f07902007-08-17 05:31:46 +00004906 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004907 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004908 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004909 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00004910 SourceLocation(),
4911 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00004912 FieldTypes[i], /*TInfo=*/nullptr,
4913 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004914 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004915 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004916 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00004917 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004918 }
4919
Ben Langmuirf5416742016-02-04 00:55:24 +00004920 CFConstantStringTagDecl->completeDefinition();
4921 // This type is designed to be compatible with NSConstantString, but cannot
4922 // use the same name, since NSConstantString is an interface.
4923 auto tagType = getTagDeclType(CFConstantStringTagDecl);
4924 CFConstantStringTypeDecl =
4925 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00004926 }
Mike Stump11289f42009-09-09 15:08:12 +00004927
Quentin Colombet043406b2016-02-03 22:41:00 +00004928 return CFConstantStringTypeDecl;
4929}
4930
Ben Langmuirf5416742016-02-04 00:55:24 +00004931RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4932 if (!CFConstantStringTagDecl)
4933 getCFConstantStringDecl(); // Build the tag and the typedef.
4934 return CFConstantStringTagDecl;
4935}
4936
Quentin Colombet043406b2016-02-03 22:41:00 +00004937// getCFConstantStringType - Return the type used for constant CFStrings.
4938QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00004939 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00004940}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004941
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004942QualType ASTContext::getObjCSuperType() const {
4943 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004944 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004945 TUDecl->addDecl(ObjCSuperTypeDecl);
4946 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4947 }
4948 return ObjCSuperType;
4949}
4950
Douglas Gregor512b0772009-04-23 22:29:11 +00004951void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004952 const TypedefType *TD = T->getAs<TypedefType>();
4953 assert(TD && "Invalid CFConstantStringType");
4954 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
4955 auto TagType =
4956 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
4957 assert(TagType && "Invalid CFConstantStringType");
4958 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00004959}
4960
Jay Foad39c79802011-01-12 09:06:06 +00004961QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004962 if (BlockDescriptorType)
4963 return getTagDeclType(BlockDescriptorType);
4964
Alp Toker2dea15b2013-12-17 01:22:38 +00004965 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004966 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004967 RD = buildImplicitRecord("__block_descriptor");
4968 RD->startDefinition();
4969
Mike Stumpd0153282009-10-20 02:12:22 +00004970 QualType FieldTypes[] = {
4971 UnsignedLongTy,
4972 UnsignedLongTy,
4973 };
4974
Craig Topperd6d31ac2013-07-15 08:24:27 +00004975 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004976 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004977 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004978 };
4979
4980 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004981 FieldDecl *Field = FieldDecl::Create(
4982 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004983 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4984 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004985 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004986 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004987 }
4988
Alp Toker2dea15b2013-12-17 01:22:38 +00004989 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004990
Alp Toker2dea15b2013-12-17 01:22:38 +00004991 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004992
4993 return getTagDeclType(BlockDescriptorType);
4994}
4995
Jay Foad39c79802011-01-12 09:06:06 +00004996QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004997 if (BlockDescriptorExtendedType)
4998 return getTagDeclType(BlockDescriptorExtendedType);
4999
Alp Toker2dea15b2013-12-17 01:22:38 +00005000 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005001 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005002 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5003 RD->startDefinition();
5004
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005005 QualType FieldTypes[] = {
5006 UnsignedLongTy,
5007 UnsignedLongTy,
5008 getPointerType(VoidPtrTy),
5009 getPointerType(VoidPtrTy)
5010 };
5011
Craig Topperd6d31ac2013-07-15 08:24:27 +00005012 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005013 "reserved",
5014 "Size",
5015 "CopyFuncPtr",
5016 "DestroyFuncPtr"
5017 };
5018
5019 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005020 FieldDecl *Field = FieldDecl::Create(
5021 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005022 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5023 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005024 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005025 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005026 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005027 }
5028
Alp Toker2dea15b2013-12-17 01:22:38 +00005029 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005030
Alp Toker2dea15b2013-12-17 01:22:38 +00005031 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005032 return getTagDeclType(BlockDescriptorExtendedType);
5033}
5034
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005035/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5036/// requires copy/dispose. Note that this must match the logic
5037/// in buildByrefHelpers.
5038bool ASTContext::BlockRequiresCopying(QualType Ty,
5039 const VarDecl *D) {
5040 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5041 const Expr *copyExpr = getBlockVarCopyInits(D);
5042 if (!copyExpr && record->hasTrivialDestructor()) return false;
5043
Mike Stump94967902009-10-21 18:16:27 +00005044 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005045 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005046
5047 if (!Ty->isObjCRetainableType()) return false;
5048
5049 Qualifiers qs = Ty.getQualifiers();
5050
5051 // If we have lifetime, that dominates.
5052 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005053 switch (lifetime) {
5054 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5055
5056 // These are just bits as far as the runtime is concerned.
5057 case Qualifiers::OCL_ExplicitNone:
5058 case Qualifiers::OCL_Autoreleasing:
5059 return false;
5060
5061 // Tell the runtime that this is ARC __weak, called by the
5062 // byref routines.
5063 case Qualifiers::OCL_Weak:
5064 // ARC __strong __block variables need to be retained.
5065 case Qualifiers::OCL_Strong:
5066 return true;
5067 }
5068 llvm_unreachable("fell out of lifetime switch!");
5069 }
5070 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5071 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005072}
5073
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005074bool ASTContext::getByrefLifetime(QualType Ty,
5075 Qualifiers::ObjCLifetime &LifeTime,
5076 bool &HasByrefExtendedLayout) const {
5077
5078 if (!getLangOpts().ObjC1 ||
5079 getLangOpts().getGC() != LangOptions::NonGC)
5080 return false;
5081
5082 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005083 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005084 HasByrefExtendedLayout = true;
5085 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005086 } else if ((LifeTime = Ty.getObjCLifetime())) {
5087 // Honor the ARC qualifiers.
5088 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5089 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005090 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005091 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005092 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005093 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005094 return true;
5095}
5096
Douglas Gregorbab8a962011-09-08 01:46:34 +00005097TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5098 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005099 ObjCInstanceTypeDecl =
5100 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005101 return ObjCInstanceTypeDecl;
5102}
5103
Anders Carlsson18acd442007-10-29 06:33:42 +00005104// This returns true if a type has been typedefed to BOOL:
5105// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005106static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005107 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005108 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5109 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005110
Anders Carlssond8499822007-10-29 05:01:08 +00005111 return false;
5112}
5113
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005114/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005115/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005116CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005117 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5118 return CharUnits::Zero();
5119
Ken Dyck40775002010-01-11 17:06:35 +00005120 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005121
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005122 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005123 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005124 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005125 // Treat arrays as pointers, since that's how they're passed in.
5126 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005127 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005128 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005129}
5130
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005131bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005132 return getTargetInfo().getCXXABI().isMicrosoft() &&
5133 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005134 VD->getType()->isIntegralOrEnumerationType() &&
5135 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005136}
5137
Ken Dyck40775002010-01-11 17:06:35 +00005138static inline
5139std::string charUnitsToString(const CharUnits &CU) {
5140 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005141}
5142
John McCall351762c2011-02-07 10:33:21 +00005143/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005144/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005145std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5146 std::string S;
5147
David Chisnall950a9512009-11-17 19:33:30 +00005148 const BlockDecl *Decl = Expr->getBlockDecl();
5149 QualType BlockTy =
5150 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5151 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005152 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005153 getObjCEncodingForMethodParameter(
5154 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5155 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005156 else
Alp Toker314cc812014-01-25 16:55:45 +00005157 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005158 // Compute size of all parameters.
5159 // Start with computing size of a pointer in number of bytes.
5160 // FIXME: There might(should) be a better way of doing this computation!
5161 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005162 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5163 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005164 for (auto PI : Decl->params()) {
5165 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005166 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005167 if (sz.isZero())
5168 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005169 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005170 ParmOffset += sz;
5171 }
5172 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005173 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005174 // Block pointer and offset.
5175 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005176
5177 // Argument types.
5178 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005179 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005180 QualType PType = PVDecl->getOriginalType();
5181 if (const ArrayType *AT =
5182 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5183 // Use array's original type only if it has known number of
5184 // elements.
5185 if (!isa<ConstantArrayType>(AT))
5186 PType = PVDecl->getType();
5187 } else if (PType->isFunctionType())
5188 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005189 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005190 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5191 S, true /*Extended*/);
5192 else
5193 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005194 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005195 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005196 }
John McCall351762c2011-02-07 10:33:21 +00005197
5198 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005199}
5200
Douglas Gregora9d84932011-05-27 01:19:52 +00005201bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005202 std::string& S) {
5203 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005204 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005205 CharUnits ParmOffset;
5206 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005207 for (auto PI : Decl->params()) {
5208 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005209 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005210 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005211 continue;
5212
David Chisnall50e4eba2010-12-30 14:05:53 +00005213 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005214 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005215 ParmOffset += sz;
5216 }
5217 S += charUnitsToString(ParmOffset);
5218 ParmOffset = CharUnits::Zero();
5219
5220 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005221 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005222 QualType PType = PVDecl->getOriginalType();
5223 if (const ArrayType *AT =
5224 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5225 // Use array's original type only if it has known number of
5226 // elements.
5227 if (!isa<ConstantArrayType>(AT))
5228 PType = PVDecl->getType();
5229 } else if (PType->isFunctionType())
5230 PType = PVDecl->getType();
5231 getObjCEncodingForType(PType, S);
5232 S += charUnitsToString(ParmOffset);
5233 ParmOffset += getObjCEncodingTypeSize(PType);
5234 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005235
5236 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005237}
5238
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005239/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5240/// method parameter or return type. If Extended, include class names and
5241/// block object types.
5242void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5243 QualType T, std::string& S,
5244 bool Extended) const {
5245 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5246 getObjCEncodingForTypeQualifier(QT, S);
5247 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005248 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005249 true /*OutermostType*/,
5250 false /*EncodingProperty*/,
5251 false /*StructField*/,
5252 Extended /*EncodeBlockParameters*/,
5253 Extended /*EncodeClassNames*/);
5254}
5255
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005256/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005257/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005258bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005259 std::string& S,
5260 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005261 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005262 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005263 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5264 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005265 // Compute size of all parameters.
5266 // Start with computing size of a pointer in number of bytes.
5267 // FIXME: There might(should) be a better way of doing this computation!
5268 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005269 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005270 // The first two arguments (self and _cmd) are pointers; account for
5271 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005272 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005273 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005274 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005275 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005276 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005277 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005278 continue;
5279
Ken Dyck40775002010-01-11 17:06:35 +00005280 assert (sz.isPositive() &&
5281 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005282 ParmOffset += sz;
5283 }
Ken Dyck40775002010-01-11 17:06:35 +00005284 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005285 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005286 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005287
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005288 // Argument types.
5289 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005290 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005291 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005292 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005293 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005294 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005295 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5296 // Use array's original type only if it has known number of
5297 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005298 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005299 PType = PVDecl->getType();
5300 } else if (PType->isFunctionType())
5301 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005302 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5303 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005304 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005305 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005306 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005307
5308 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005309}
5310
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005311ObjCPropertyImplDecl *
5312ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5313 const ObjCPropertyDecl *PD,
5314 const Decl *Container) const {
5315 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005316 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005317 if (const ObjCCategoryImplDecl *CID =
5318 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005319 for (auto *PID : CID->property_impls())
5320 if (PID->getPropertyDecl() == PD)
5321 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005322 } else {
5323 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5324 for (auto *PID : OID->property_impls())
5325 if (PID->getPropertyDecl() == PD)
5326 return PID;
5327 }
5328 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005329}
5330
Daniel Dunbar4932b362008-08-28 04:38:10 +00005331/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005332/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005333/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5334/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005335/// Property attributes are stored as a comma-delimited C string. The simple
5336/// attributes readonly and bycopy are encoded as single characters. The
5337/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5338/// encoded as single characters, followed by an identifier. Property types
5339/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005340/// these attributes are defined by the following enumeration:
5341/// @code
5342/// enum PropertyAttributes {
5343/// kPropertyReadOnly = 'R', // property is read-only.
5344/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5345/// kPropertyByref = '&', // property is a reference to the value last assigned
5346/// kPropertyDynamic = 'D', // property is dynamic
5347/// kPropertyGetter = 'G', // followed by getter selector name
5348/// kPropertySetter = 'S', // followed by setter selector name
5349/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005350/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005351/// kPropertyWeak = 'W' // 'weak' property
5352/// kPropertyStrong = 'P' // property GC'able
5353/// kPropertyNonAtomic = 'N' // property non-atomic
5354/// };
5355/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005356void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005357 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005358 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005359 // Collect information from the property implementation decl(s).
5360 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005361 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005362
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005363 if (ObjCPropertyImplDecl *PropertyImpDecl =
5364 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5365 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5366 Dynamic = true;
5367 else
5368 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005369 }
5370
5371 // FIXME: This is not very efficient.
5372 S = "T";
5373
5374 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005375 // GCC has some special rules regarding encoding of properties which
5376 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005377 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005378
5379 if (PD->isReadOnly()) {
5380 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005381 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5382 S += ",C";
5383 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5384 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005385 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5386 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005387 } else {
5388 switch (PD->getSetterKind()) {
5389 case ObjCPropertyDecl::Assign: break;
5390 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005391 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005392 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005393 }
5394 }
5395
5396 // It really isn't clear at all what this means, since properties
5397 // are "dynamic by default".
5398 if (Dynamic)
5399 S += ",D";
5400
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005401 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5402 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005403
Daniel Dunbar4932b362008-08-28 04:38:10 +00005404 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5405 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005406 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005407 }
5408
5409 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5410 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005411 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005412 }
5413
5414 if (SynthesizePID) {
5415 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5416 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005417 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005418 }
5419
5420 // FIXME: OBJCGC: weak & strong
5421}
5422
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005423/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005424/// Another legacy compatibility encoding: 32-bit longs are encoded as
5425/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005426/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5427///
5428void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005429 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005430 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005431 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005432 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005433 else
Jay Foad39c79802011-01-12 09:06:06 +00005434 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005435 PointeeTy = IntTy;
5436 }
5437 }
5438}
5439
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005440void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005441 const FieldDecl *Field,
5442 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005443 // We follow the behavior of gcc, expanding structures which are
5444 // directly pointed to, and expanding embedded structures. Note that
5445 // these rules are sufficient to prevent recursive encoding of the
5446 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005447 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005448 true /* outermost type */, false, false,
5449 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005450}
5451
Joe Groff98ac7d22014-07-07 22:25:15 +00005452void ASTContext::getObjCEncodingForPropertyType(QualType T,
5453 std::string& S) const {
5454 // Encode result type.
5455 // GCC has some special rules regarding encoding of properties which
5456 // closely resembles encoding of ivars.
5457 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5458 true /* outermost type */,
5459 true /* encoding property */);
5460}
5461
John McCall393a78d2012-12-20 02:45:14 +00005462static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5463 BuiltinType::Kind kind) {
5464 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005465 case BuiltinType::Void: return 'v';
5466 case BuiltinType::Bool: return 'B';
5467 case BuiltinType::Char_U:
5468 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005469 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005470 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005471 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005472 case BuiltinType::UInt: return 'I';
5473 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005474 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005475 case BuiltinType::UInt128: return 'T';
5476 case BuiltinType::ULongLong: return 'Q';
5477 case BuiltinType::Char_S:
5478 case BuiltinType::SChar: return 'c';
5479 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005480 case BuiltinType::WChar_S:
5481 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005482 case BuiltinType::Int: return 'i';
5483 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005484 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005485 case BuiltinType::LongLong: return 'q';
5486 case BuiltinType::Int128: return 't';
5487 case BuiltinType::Float: return 'f';
5488 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005489 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005490 case BuiltinType::NullPtr: return '*'; // like char*
5491
5492 case BuiltinType::Half:
5493 // FIXME: potentially need @encodes for these!
5494 return ' ';
5495
5496 case BuiltinType::ObjCId:
5497 case BuiltinType::ObjCClass:
5498 case BuiltinType::ObjCSel:
5499 llvm_unreachable("@encoding ObjC primitive type");
5500
5501 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005502#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5503 case BuiltinType::Id:
5504#include "clang/AST/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005505 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005506 case BuiltinType::OCLClkEvent:
5507 case BuiltinType::OCLQueue:
5508 case BuiltinType::OCLNDRange:
5509 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005510 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005511 case BuiltinType::Dependent:
5512#define BUILTIN_TYPE(KIND, ID)
5513#define PLACEHOLDER_TYPE(KIND, ID) \
5514 case BuiltinType::KIND:
5515#include "clang/AST/BuiltinTypes.def"
5516 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005517 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005518 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005519}
5520
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005521static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5522 EnumDecl *Enum = ET->getDecl();
5523
5524 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5525 if (!Enum->isFixed())
5526 return 'i';
5527
5528 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005529 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5530 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005531}
5532
Jay Foad39c79802011-01-12 09:06:06 +00005533static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005534 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005535 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005536 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005537 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5538 // The GNU runtime requires more information; bitfields are encoded as b,
5539 // then the offset (in bits) of the first element, then the type of the
5540 // bitfield, then the size in bits. For example, in this structure:
5541 //
5542 // struct
5543 // {
5544 // int integer;
5545 // int flags:2;
5546 // };
5547 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5548 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5549 // information is not especially sensible, but we're stuck with it for
5550 // compatibility with GCC, although providing it breaks anything that
5551 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005552 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005553 const RecordDecl *RD = FD->getParent();
5554 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005555 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005556 if (const EnumType *ET = T->getAs<EnumType>())
5557 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005558 else {
5559 const BuiltinType *BT = T->castAs<BuiltinType>();
5560 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5561 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005562 }
Richard Smithcaf33902011-10-10 18:28:20 +00005563 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005564}
5565
Daniel Dunbar07d07852009-10-18 21:17:35 +00005566// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005567void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5568 bool ExpandPointedToStructures,
5569 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005570 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005571 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005572 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005573 bool StructField,
5574 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005575 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005576 bool EncodePointerToObjCTypedef,
5577 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005578 CanQualType CT = getCanonicalType(T);
5579 switch (CT->getTypeClass()) {
5580 case Type::Builtin:
5581 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005582 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005583 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005584 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5585 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5586 else
5587 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005588 return;
Mike Stump11289f42009-09-09 15:08:12 +00005589
John McCall393a78d2012-12-20 02:45:14 +00005590 case Type::Complex: {
5591 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005592 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005593 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005594 return;
5595 }
John McCall393a78d2012-12-20 02:45:14 +00005596
5597 case Type::Atomic: {
5598 const AtomicType *AT = T->castAs<AtomicType>();
5599 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005600 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005601 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005602 }
John McCall393a78d2012-12-20 02:45:14 +00005603
5604 // encoding for pointer or reference types.
5605 case Type::Pointer:
5606 case Type::LValueReference:
5607 case Type::RValueReference: {
5608 QualType PointeeTy;
5609 if (isa<PointerType>(CT)) {
5610 const PointerType *PT = T->castAs<PointerType>();
5611 if (PT->isObjCSelType()) {
5612 S += ':';
5613 return;
5614 }
5615 PointeeTy = PT->getPointeeType();
5616 } else {
5617 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5618 }
5619
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005620 bool isReadOnly = false;
5621 // For historical/compatibility reasons, the read-only qualifier of the
5622 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5623 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005624 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005625 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005626 if (OutermostType && T.isConstQualified()) {
5627 isReadOnly = true;
5628 S += 'r';
5629 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005630 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005631 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005632 while (P->getAs<PointerType>())
5633 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005634 if (P.isConstQualified()) {
5635 isReadOnly = true;
5636 S += 'r';
5637 }
5638 }
5639 if (isReadOnly) {
5640 // Another legacy compatibility encoding. Some ObjC qualifier and type
5641 // combinations need to be rearranged.
5642 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005643 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005644 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005645 }
Mike Stump11289f42009-09-09 15:08:12 +00005646
Anders Carlssond8499822007-10-29 05:01:08 +00005647 if (PointeeTy->isCharType()) {
5648 // char pointer types should be encoded as '*' unless it is a
5649 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005650 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005651 S += '*';
5652 return;
5653 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005654 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005655 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5656 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5657 S += '#';
5658 return;
5659 }
5660 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5661 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5662 S += '@';
5663 return;
5664 }
5665 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005666 }
Anders Carlssond8499822007-10-29 05:01:08 +00005667 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005668 getLegacyIntegralTypeEncoding(PointeeTy);
5669
Mike Stump11289f42009-09-09 15:08:12 +00005670 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005671 nullptr, false, false, false, false, false, false,
5672 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005673 return;
5674 }
John McCall393a78d2012-12-20 02:45:14 +00005675
5676 case Type::ConstantArray:
5677 case Type::IncompleteArray:
5678 case Type::VariableArray: {
5679 const ArrayType *AT = cast<ArrayType>(CT);
5680
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005681 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005682 // Incomplete arrays are encoded as a pointer to the array element.
5683 S += '^';
5684
Mike Stump11289f42009-09-09 15:08:12 +00005685 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005686 false, ExpandStructures, FD);
5687 } else {
5688 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005689
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005690 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5691 S += llvm::utostr(CAT->getSize().getZExtValue());
5692 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005693 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005694 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5695 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005696 S += '0';
5697 }
Mike Stump11289f42009-09-09 15:08:12 +00005698
5699 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005700 false, ExpandStructures, FD,
5701 false, false, false, false, false, false,
5702 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005703 S += ']';
5704 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005705 return;
5706 }
Mike Stump11289f42009-09-09 15:08:12 +00005707
John McCall393a78d2012-12-20 02:45:14 +00005708 case Type::FunctionNoProto:
5709 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005710 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005711 return;
Mike Stump11289f42009-09-09 15:08:12 +00005712
John McCall393a78d2012-12-20 02:45:14 +00005713 case Type::Record: {
5714 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005715 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005716 // Anonymous structures print as '?'
5717 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5718 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005719 if (ClassTemplateSpecializationDecl *Spec
5720 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5721 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005722 llvm::raw_string_ostream OS(S);
5723 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005724 TemplateArgs.data(),
5725 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005726 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005727 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005728 } else {
5729 S += '?';
5730 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005731 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005732 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005733 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005734 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005735 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005736 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005737 if (FD) {
5738 S += '"';
5739 S += Field->getNameAsString();
5740 S += '"';
5741 }
Mike Stump11289f42009-09-09 15:08:12 +00005742
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005743 // Special case bit-fields.
5744 if (Field->isBitField()) {
5745 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005746 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005747 } else {
5748 QualType qt = Field->getType();
5749 getLegacyIntegralTypeEncoding(qt);
5750 getObjCEncodingForTypeImpl(qt, S, false, true,
5751 FD, /*OutermostType*/false,
5752 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005753 /*StructField*/true,
5754 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005755 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005756 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005757 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005758 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005759 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005760 return;
5761 }
Mike Stump11289f42009-09-09 15:08:12 +00005762
John McCall393a78d2012-12-20 02:45:14 +00005763 case Type::BlockPointer: {
5764 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005765 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005766 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005767 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005768
5769 S += '<';
5770 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005771 getObjCEncodingForTypeImpl(
5772 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5773 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005774 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5775 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005776 // Block self
5777 S += "@?";
5778 // Block parameters
5779 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005780 for (const auto &I : FPT->param_types())
5781 getObjCEncodingForTypeImpl(
5782 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5783 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005784 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5785 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005786 }
5787 S += '>';
5788 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005789 return;
5790 }
Mike Stump11289f42009-09-09 15:08:12 +00005791
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005792 case Type::ObjCObject: {
5793 // hack to match legacy encoding of *id and *Class
5794 QualType Ty = getObjCObjectPointerType(CT);
5795 if (Ty->isObjCIdType()) {
5796 S += "{objc_object=}";
5797 return;
5798 }
5799 else if (Ty->isObjCClassType()) {
5800 S += "{objc_class=}";
5801 return;
5802 }
5803 }
5804
John McCall393a78d2012-12-20 02:45:14 +00005805 case Type::ObjCInterface: {
5806 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005807 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005808 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005809 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005810 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005811 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005812 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005813 DeepCollectObjCIvars(OI, true, Ivars);
5814 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005815 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005816 if (Field->isBitField())
5817 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005818 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005819 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5820 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005821 EncodePointerToObjCTypedef,
5822 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005823 }
5824 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005825 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005826 }
Mike Stump11289f42009-09-09 15:08:12 +00005827
John McCall393a78d2012-12-20 02:45:14 +00005828 case Type::ObjCObjectPointer: {
5829 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005830 if (OPT->isObjCIdType()) {
5831 S += '@';
5832 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005833 }
Mike Stump11289f42009-09-09 15:08:12 +00005834
Steve Narofff0c86112009-10-28 22:03:49 +00005835 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5836 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5837 // Since this is a binary compatibility issue, need to consult with runtime
5838 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005839 S += '#';
5840 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005841 }
Mike Stump11289f42009-09-09 15:08:12 +00005842
Chris Lattnere7cabb92009-07-13 00:10:46 +00005843 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005844 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005845 ExpandPointedToStructures,
5846 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005847 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005848 // Note that we do extended encoding of protocol qualifer list
5849 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005850 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005851 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005852 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005853 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005854 S += '>';
5855 }
5856 S += '"';
5857 }
5858 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005859 }
Mike Stump11289f42009-09-09 15:08:12 +00005860
Chris Lattnere7cabb92009-07-13 00:10:46 +00005861 QualType PointeeTy = OPT->getPointeeType();
5862 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005863 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5864 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005865 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005866 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005867 // {...};
5868 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005869 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005870 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005871 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5872 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5873 DeepCollectObjCIvars(OI, true, Ivars);
5874 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5875 if (cast<FieldDecl>(Ivars[i]) == FD) {
5876 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005877 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005878 S += '}';
5879 return;
5880 }
5881 }
5882 }
Mike Stump11289f42009-09-09 15:08:12 +00005883 getObjCEncodingForTypeImpl(PointeeTy, S,
5884 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005885 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005886 false, false, false, false, false,
5887 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005888 return;
5889 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005890
5891 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005892 if (OPT->getInterfaceDecl() &&
5893 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005894 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005895 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005896 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005897 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005898 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005899 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005900 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005901 S += '"';
5902 }
5903 return;
5904 }
Mike Stump11289f42009-09-09 15:08:12 +00005905
John McCalla9e6e8d2010-05-17 23:56:34 +00005906 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005907 // FIXME: we shoul do better than that. 'M' is available.
5908 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005909 // This matches gcc's encoding, even though technically it is insufficient.
5910 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005911 case Type::Vector:
5912 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005913 // Until we have a coherent encoding of these three types, issue warning.
5914 { if (NotEncodedT)
5915 *NotEncodedT = T;
5916 return;
5917 }
5918
5919 // We could see an undeduced auto type here during error recovery.
5920 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005921 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005922 return;
5923
Xiuli Pan9c14e282016-01-09 12:53:17 +00005924 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00005925#define ABSTRACT_TYPE(KIND, BASE)
5926#define TYPE(KIND, BASE)
5927#define DEPENDENT_TYPE(KIND, BASE) \
5928 case Type::KIND:
5929#define NON_CANONICAL_TYPE(KIND, BASE) \
5930 case Type::KIND:
5931#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5932 case Type::KIND:
5933#include "clang/AST/TypeNodes.def"
5934 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005935 }
John McCall393a78d2012-12-20 02:45:14 +00005936 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005937}
5938
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005939void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5940 std::string &S,
5941 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005942 bool includeVBases,
5943 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005944 assert(RDecl && "Expected non-null RecordDecl");
5945 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00005946 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005947 return;
5948
5949 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5950 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5951 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5952
5953 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005954 for (const auto &BI : CXXRec->bases()) {
5955 if (!BI.isVirtual()) {
5956 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005957 if (base->isEmpty())
5958 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005959 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005960 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5961 std::make_pair(offs, base));
5962 }
5963 }
5964 }
5965
5966 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005967 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005968 uint64_t offs = layout.getFieldOffset(i);
5969 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005970 std::make_pair(offs, Field));
5971 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005972 }
5973
5974 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005975 for (const auto &BI : CXXRec->vbases()) {
5976 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005977 if (base->isEmpty())
5978 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005979 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005980 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5981 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005982 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5983 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005984 }
5985 }
5986
5987 CharUnits size;
5988 if (CXXRec) {
5989 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5990 } else {
5991 size = layout.getSize();
5992 }
5993
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005994#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005995 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005996#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005997 std::multimap<uint64_t, NamedDecl *>::iterator
5998 CurLayObj = FieldOrBaseOffsets.begin();
5999
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006000 if (CXXRec && CXXRec->isDynamicClass() &&
6001 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006002 if (FD) {
6003 S += "\"_vptr$";
6004 std::string recname = CXXRec->getNameAsString();
6005 if (recname.empty()) recname = "?";
6006 S += recname;
6007 S += '"';
6008 }
6009 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006010#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006011 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006012#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006013 }
6014
6015 if (!RDecl->hasFlexibleArrayMember()) {
6016 // Mark the end of the structure.
6017 uint64_t offs = toBits(size);
6018 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006019 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006020 }
6021
6022 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006023#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006024 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006025 if (CurOffs < CurLayObj->first) {
6026 uint64_t padding = CurLayObj->first - CurOffs;
6027 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6028 // packing/alignment of members is different that normal, in which case
6029 // the encoding will be out-of-sync with the real layout.
6030 // If the runtime switches to just consider the size of types without
6031 // taking into account alignment, we could make padding explicit in the
6032 // encoding (e.g. using arrays of chars). The encoding strings would be
6033 // longer then though.
6034 CurOffs += padding;
6035 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006036#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006037
6038 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006039 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006040 break; // reached end of structure.
6041
6042 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6043 // We expand the bases without their virtual bases since those are going
6044 // in the initial structure. Note that this differs from gcc which
6045 // expands virtual bases each time one is encountered in the hierarchy,
6046 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006047 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6048 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006049 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006050#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006051 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006052#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006053 } else {
6054 FieldDecl *field = cast<FieldDecl>(dcl);
6055 if (FD) {
6056 S += '"';
6057 S += field->getNameAsString();
6058 S += '"';
6059 }
6060
6061 if (field->isBitField()) {
6062 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006063#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006064 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006065#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006066 } else {
6067 QualType qt = field->getType();
6068 getLegacyIntegralTypeEncoding(qt);
6069 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6070 /*OutermostType*/false,
6071 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006072 /*StructField*/true,
6073 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006074#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006075 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006076#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006077 }
6078 }
6079 }
6080}
6081
Mike Stump11289f42009-09-09 15:08:12 +00006082void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006083 std::string& S) const {
6084 if (QT & Decl::OBJC_TQ_In)
6085 S += 'n';
6086 if (QT & Decl::OBJC_TQ_Inout)
6087 S += 'N';
6088 if (QT & Decl::OBJC_TQ_Out)
6089 S += 'o';
6090 if (QT & Decl::OBJC_TQ_Bycopy)
6091 S += 'O';
6092 if (QT & Decl::OBJC_TQ_Byref)
6093 S += 'R';
6094 if (QT & Decl::OBJC_TQ_Oneway)
6095 S += 'V';
6096}
6097
Douglas Gregor3ea72692011-08-12 05:46:01 +00006098TypedefDecl *ASTContext::getObjCIdDecl() const {
6099 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006100 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006101 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006102 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006103 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006104 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006105}
6106
Douglas Gregor52e02802011-08-12 06:17:30 +00006107TypedefDecl *ASTContext::getObjCSelDecl() const {
6108 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006109 QualType T = getPointerType(ObjCBuiltinSelTy);
6110 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006111 }
6112 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006113}
6114
Douglas Gregor0a586182011-08-12 05:59:41 +00006115TypedefDecl *ASTContext::getObjCClassDecl() const {
6116 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006117 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006118 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006119 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006120 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006121 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006122}
6123
Douglas Gregord53ae832012-01-17 18:09:05 +00006124ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6125 if (!ObjCProtocolClassDecl) {
6126 ObjCProtocolClassDecl
6127 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6128 SourceLocation(),
6129 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006130 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006131 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006132 SourceLocation(), true);
6133 }
6134
6135 return ObjCProtocolClassDecl;
6136}
6137
Meador Inge5d3fb222012-06-16 03:34:49 +00006138//===----------------------------------------------------------------------===//
6139// __builtin_va_list Construction Functions
6140//===----------------------------------------------------------------------===//
6141
Charles Davisc7d5c942015-09-17 20:55:33 +00006142static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6143 StringRef Name) {
6144 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006145 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006146 return Context->buildImplicitTypedef(T, Name);
6147}
6148
6149static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6150 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6151}
6152
6153static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6154 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006155}
6156
6157static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6158 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006159 QualType T = Context->getPointerType(Context->VoidTy);
6160 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006161}
6162
Tim Northover9bb857a2013-01-31 12:13:10 +00006163static TypedefDecl *
6164CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006165 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006166 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006167 if (Context->getLangOpts().CPlusPlus) {
6168 // namespace std { struct __va_list {
6169 NamespaceDecl *NS;
6170 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6171 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006172 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006173 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006174 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006175 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006176 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006177 }
6178
6179 VaListTagDecl->startDefinition();
6180
6181 const size_t NumFields = 5;
6182 QualType FieldTypes[NumFields];
6183 const char *FieldNames[NumFields];
6184
6185 // void *__stack;
6186 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6187 FieldNames[0] = "__stack";
6188
6189 // void *__gr_top;
6190 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6191 FieldNames[1] = "__gr_top";
6192
6193 // void *__vr_top;
6194 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6195 FieldNames[2] = "__vr_top";
6196
6197 // int __gr_offs;
6198 FieldTypes[3] = Context->IntTy;
6199 FieldNames[3] = "__gr_offs";
6200
6201 // int __vr_offs;
6202 FieldTypes[4] = Context->IntTy;
6203 FieldNames[4] = "__vr_offs";
6204
6205 // Create fields
6206 for (unsigned i = 0; i < NumFields; ++i) {
6207 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6208 VaListTagDecl,
6209 SourceLocation(),
6210 SourceLocation(),
6211 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006212 FieldTypes[i], /*TInfo=*/nullptr,
6213 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006214 /*Mutable=*/false,
6215 ICIS_NoInit);
6216 Field->setAccess(AS_public);
6217 VaListTagDecl->addDecl(Field);
6218 }
6219 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006220 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006221 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006222
6223 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006224 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006225}
6226
Meador Inge5d3fb222012-06-16 03:34:49 +00006227static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6228 // typedef struct __va_list_tag {
6229 RecordDecl *VaListTagDecl;
6230
Alp Toker2dea15b2013-12-17 01:22:38 +00006231 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006232 VaListTagDecl->startDefinition();
6233
6234 const size_t NumFields = 5;
6235 QualType FieldTypes[NumFields];
6236 const char *FieldNames[NumFields];
6237
6238 // unsigned char gpr;
6239 FieldTypes[0] = Context->UnsignedCharTy;
6240 FieldNames[0] = "gpr";
6241
6242 // unsigned char fpr;
6243 FieldTypes[1] = Context->UnsignedCharTy;
6244 FieldNames[1] = "fpr";
6245
6246 // unsigned short reserved;
6247 FieldTypes[2] = Context->UnsignedShortTy;
6248 FieldNames[2] = "reserved";
6249
6250 // void* overflow_arg_area;
6251 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6252 FieldNames[3] = "overflow_arg_area";
6253
6254 // void* reg_save_area;
6255 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6256 FieldNames[4] = "reg_save_area";
6257
6258 // Create fields
6259 for (unsigned i = 0; i < NumFields; ++i) {
6260 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6261 SourceLocation(),
6262 SourceLocation(),
6263 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006264 FieldTypes[i], /*TInfo=*/nullptr,
6265 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006266 /*Mutable=*/false,
6267 ICIS_NoInit);
6268 Field->setAccess(AS_public);
6269 VaListTagDecl->addDecl(Field);
6270 }
6271 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006272 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006273 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6274
6275 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006276 TypedefDecl *VaListTagTypedefDecl =
6277 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6278
Meador Inge5d3fb222012-06-16 03:34:49 +00006279 QualType VaListTagTypedefType =
6280 Context->getTypedefType(VaListTagTypedefDecl);
6281
6282 // typedef __va_list_tag __builtin_va_list[1];
6283 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6284 QualType VaListTagArrayType
6285 = Context->getConstantArrayType(VaListTagTypedefType,
6286 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006287 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006288}
6289
6290static TypedefDecl *
6291CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006292 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006293 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006294 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006295 VaListTagDecl->startDefinition();
6296
6297 const size_t NumFields = 4;
6298 QualType FieldTypes[NumFields];
6299 const char *FieldNames[NumFields];
6300
6301 // unsigned gp_offset;
6302 FieldTypes[0] = Context->UnsignedIntTy;
6303 FieldNames[0] = "gp_offset";
6304
6305 // unsigned fp_offset;
6306 FieldTypes[1] = Context->UnsignedIntTy;
6307 FieldNames[1] = "fp_offset";
6308
6309 // void* overflow_arg_area;
6310 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6311 FieldNames[2] = "overflow_arg_area";
6312
6313 // void* reg_save_area;
6314 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6315 FieldNames[3] = "reg_save_area";
6316
6317 // Create fields
6318 for (unsigned i = 0; i < NumFields; ++i) {
6319 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6320 VaListTagDecl,
6321 SourceLocation(),
6322 SourceLocation(),
6323 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006324 FieldTypes[i], /*TInfo=*/nullptr,
6325 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006326 /*Mutable=*/false,
6327 ICIS_NoInit);
6328 Field->setAccess(AS_public);
6329 VaListTagDecl->addDecl(Field);
6330 }
6331 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006332 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006333 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6334
Richard Smith9b88a4c2015-07-27 05:40:23 +00006335 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006336
Richard Smith9b88a4c2015-07-27 05:40:23 +00006337 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006338 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006339 QualType VaListTagArrayType =
6340 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006341 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006342}
6343
6344static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6345 // typedef int __builtin_va_list[4];
6346 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6347 QualType IntArrayType
6348 = Context->getConstantArrayType(Context->IntTy,
6349 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006350 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006351}
6352
Logan Chien57086ce2012-10-10 06:56:20 +00006353static TypedefDecl *
6354CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006355 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006356 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006357 if (Context->getLangOpts().CPlusPlus) {
6358 // namespace std { struct __va_list {
6359 NamespaceDecl *NS;
6360 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6361 Context->getTranslationUnitDecl(),
6362 /*Inline*/false, SourceLocation(),
6363 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006364 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006365 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006366 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006367 }
6368
6369 VaListDecl->startDefinition();
6370
6371 // void * __ap;
6372 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6373 VaListDecl,
6374 SourceLocation(),
6375 SourceLocation(),
6376 &Context->Idents.get("__ap"),
6377 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006378 /*TInfo=*/nullptr,
6379 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006380 /*Mutable=*/false,
6381 ICIS_NoInit);
6382 Field->setAccess(AS_public);
6383 VaListDecl->addDecl(Field);
6384
6385 // };
6386 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006387 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006388
6389 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006390 QualType T = Context->getRecordType(VaListDecl);
6391 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006392}
6393
Ulrich Weigand47445072013-05-06 16:26:41 +00006394static TypedefDecl *
6395CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006396 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006397 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006398 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006399 VaListTagDecl->startDefinition();
6400
6401 const size_t NumFields = 4;
6402 QualType FieldTypes[NumFields];
6403 const char *FieldNames[NumFields];
6404
6405 // long __gpr;
6406 FieldTypes[0] = Context->LongTy;
6407 FieldNames[0] = "__gpr";
6408
6409 // long __fpr;
6410 FieldTypes[1] = Context->LongTy;
6411 FieldNames[1] = "__fpr";
6412
6413 // void *__overflow_arg_area;
6414 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6415 FieldNames[2] = "__overflow_arg_area";
6416
6417 // void *__reg_save_area;
6418 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6419 FieldNames[3] = "__reg_save_area";
6420
6421 // Create fields
6422 for (unsigned i = 0; i < NumFields; ++i) {
6423 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6424 VaListTagDecl,
6425 SourceLocation(),
6426 SourceLocation(),
6427 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006428 FieldTypes[i], /*TInfo=*/nullptr,
6429 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006430 /*Mutable=*/false,
6431 ICIS_NoInit);
6432 Field->setAccess(AS_public);
6433 VaListTagDecl->addDecl(Field);
6434 }
6435 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006436 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006437 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006438
Richard Smith9b88a4c2015-07-27 05:40:23 +00006439 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006440
6441 // typedef __va_list_tag __builtin_va_list[1];
6442 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006443 QualType VaListTagArrayType =
6444 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006445
Alp Toker56b5cc92013-12-15 10:36:26 +00006446 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006447}
6448
Meador Inge5d3fb222012-06-16 03:34:49 +00006449static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6450 TargetInfo::BuiltinVaListKind Kind) {
6451 switch (Kind) {
6452 case TargetInfo::CharPtrBuiltinVaList:
6453 return CreateCharPtrBuiltinVaListDecl(Context);
6454 case TargetInfo::VoidPtrBuiltinVaList:
6455 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006456 case TargetInfo::AArch64ABIBuiltinVaList:
6457 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006458 case TargetInfo::PowerABIBuiltinVaList:
6459 return CreatePowerABIBuiltinVaListDecl(Context);
6460 case TargetInfo::X86_64ABIBuiltinVaList:
6461 return CreateX86_64ABIBuiltinVaListDecl(Context);
6462 case TargetInfo::PNaClABIBuiltinVaList:
6463 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006464 case TargetInfo::AAPCSABIBuiltinVaList:
6465 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006466 case TargetInfo::SystemZBuiltinVaList:
6467 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006468 }
6469
6470 llvm_unreachable("Unhandled __builtin_va_list type kind");
6471}
6472
6473TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006474 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006475 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006476 assert(BuiltinVaListDecl->isImplicit());
6477 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006478
6479 return BuiltinVaListDecl;
6480}
6481
Richard Smith9b88a4c2015-07-27 05:40:23 +00006482Decl *ASTContext::getVaListTagDecl() const {
6483 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006484 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006485 if (!VaListTagDecl)
6486 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006487
Richard Smith9b88a4c2015-07-27 05:40:23 +00006488 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006489}
6490
Charles Davisc7d5c942015-09-17 20:55:33 +00006491TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6492 if (!BuiltinMSVaListDecl)
6493 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6494
6495 return BuiltinMSVaListDecl;
6496}
6497
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006498void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006499 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006500 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006501
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006502 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006503}
6504
John McCalld28ae272009-12-02 08:04:21 +00006505/// \brief Retrieve the template name that corresponds to a non-empty
6506/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006507TemplateName
6508ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6509 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006510 unsigned size = End - Begin;
6511 assert(size > 1 && "set is not overloaded!");
6512
6513 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6514 size * sizeof(FunctionTemplateDecl*));
6515 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6516
6517 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006518 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006519 NamedDecl *D = *I;
6520 assert(isa<FunctionTemplateDecl>(D) ||
6521 (isa<UsingShadowDecl>(D) &&
6522 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6523 *Storage++ = D;
6524 }
6525
6526 return TemplateName(OT);
6527}
6528
Douglas Gregordc572a32009-03-30 22:58:21 +00006529/// \brief Retrieve the template name that represents a qualified
6530/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006531TemplateName
6532ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6533 bool TemplateKeyword,
6534 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006535 assert(NNS && "Missing nested-name-specifier in qualified template name");
6536
Douglas Gregorc42075a2010-02-04 18:10:26 +00006537 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006538 llvm::FoldingSetNodeID ID;
6539 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6540
Craig Topper36250ad2014-05-12 05:36:57 +00006541 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006542 QualifiedTemplateName *QTN =
6543 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6544 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006545 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6546 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006547 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6548 }
6549
6550 return TemplateName(QTN);
6551}
6552
6553/// \brief Retrieve the template name that represents a dependent
6554/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006555TemplateName
6556ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6557 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006558 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006559 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006560
6561 llvm::FoldingSetNodeID ID;
6562 DependentTemplateName::Profile(ID, NNS, Name);
6563
Craig Topper36250ad2014-05-12 05:36:57 +00006564 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006565 DependentTemplateName *QTN =
6566 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6567
6568 if (QTN)
6569 return TemplateName(QTN);
6570
6571 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6572 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006573 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6574 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006575 } else {
6576 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006577 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6578 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006579 DependentTemplateName *CheckQTN =
6580 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6581 assert(!CheckQTN && "Dependent type name canonicalization broken");
6582 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006583 }
6584
6585 DependentTemplateNames.InsertNode(QTN, InsertPos);
6586 return TemplateName(QTN);
6587}
6588
Douglas Gregor71395fa2009-11-04 00:56:37 +00006589/// \brief Retrieve the template name that represents a dependent
6590/// template name such as \c MetaFun::template operator+.
6591TemplateName
6592ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006593 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006594 assert((!NNS || NNS->isDependent()) &&
6595 "Nested name specifier must be dependent");
6596
6597 llvm::FoldingSetNodeID ID;
6598 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006599
6600 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006601 DependentTemplateName *QTN
6602 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006603
6604 if (QTN)
6605 return TemplateName(QTN);
6606
6607 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6608 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006609 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6610 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006611 } else {
6612 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006613 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6614 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006615
6616 DependentTemplateName *CheckQTN
6617 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6618 assert(!CheckQTN && "Dependent template name canonicalization broken");
6619 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006620 }
6621
6622 DependentTemplateNames.InsertNode(QTN, InsertPos);
6623 return TemplateName(QTN);
6624}
6625
Douglas Gregor5590be02011-01-15 06:45:20 +00006626TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006627ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6628 TemplateName replacement) const {
6629 llvm::FoldingSetNodeID ID;
6630 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006631
6632 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006633 SubstTemplateTemplateParmStorage *subst
6634 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6635
6636 if (!subst) {
6637 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6638 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6639 }
6640
6641 return TemplateName(subst);
6642}
6643
6644TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006645ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6646 const TemplateArgument &ArgPack) const {
6647 ASTContext &Self = const_cast<ASTContext &>(*this);
6648 llvm::FoldingSetNodeID ID;
6649 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006650
6651 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006652 SubstTemplateTemplateParmPackStorage *Subst
6653 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6654
6655 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006656 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006657 ArgPack.pack_size(),
6658 ArgPack.pack_begin());
6659 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6660 }
6661
6662 return TemplateName(Subst);
6663}
6664
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006665/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006666/// TargetInfo, produce the corresponding type. The unsigned @p Type
6667/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006668CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006669 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006670 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006671 case TargetInfo::SignedChar: return SignedCharTy;
6672 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006673 case TargetInfo::SignedShort: return ShortTy;
6674 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6675 case TargetInfo::SignedInt: return IntTy;
6676 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6677 case TargetInfo::SignedLong: return LongTy;
6678 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6679 case TargetInfo::SignedLongLong: return LongLongTy;
6680 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6681 }
6682
David Blaikie83d382b2011-09-23 05:06:16 +00006683 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006684}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006685
6686//===----------------------------------------------------------------------===//
6687// Type Predicates.
6688//===----------------------------------------------------------------------===//
6689
Fariborz Jahanian96207692009-02-18 21:49:28 +00006690/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6691/// garbage collection attribute.
6692///
John McCall553d45a2011-01-12 00:34:59 +00006693Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006694 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006695 return Qualifiers::GCNone;
6696
David Blaikiebbafb8a2012-03-11 07:00:24 +00006697 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006698 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6699
6700 // Default behaviour under objective-C's gc is for ObjC pointers
6701 // (or pointers to them) be treated as though they were declared
6702 // as __strong.
6703 if (GCAttrs == Qualifiers::GCNone) {
6704 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6705 return Qualifiers::Strong;
6706 else if (Ty->isPointerType())
6707 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6708 } else {
6709 // It's not valid to set GC attributes on anything that isn't a
6710 // pointer.
6711#ifndef NDEBUG
6712 QualType CT = Ty->getCanonicalTypeInternal();
6713 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6714 CT = AT->getElementType();
6715 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6716#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006717 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006718 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006719}
6720
Chris Lattner49af6a42008-04-07 06:51:04 +00006721//===----------------------------------------------------------------------===//
6722// Type Compatibility Testing
6723//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006724
Mike Stump11289f42009-09-09 15:08:12 +00006725/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006726/// compatible.
6727static bool areCompatVectorTypes(const VectorType *LHS,
6728 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006729 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006730 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006731 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006732}
6733
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006734bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6735 QualType SecondVec) {
6736 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6737 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6738
6739 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6740 return true;
6741
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006742 // Treat Neon vector types and most AltiVec vector types as if they are the
6743 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006744 const VectorType *First = FirstVec->getAs<VectorType>();
6745 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006746 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006747 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006748 First->getVectorKind() != VectorType::AltiVecPixel &&
6749 First->getVectorKind() != VectorType::AltiVecBool &&
6750 Second->getVectorKind() != VectorType::AltiVecPixel &&
6751 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006752 return true;
6753
6754 return false;
6755}
6756
Steve Naroff8e6aee52009-07-23 01:01:38 +00006757//===----------------------------------------------------------------------===//
6758// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6759//===----------------------------------------------------------------------===//
6760
6761/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6762/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006763bool
6764ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6765 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006766 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006767 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006768 for (auto *PI : rProto->protocols())
6769 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006770 return true;
6771 return false;
6772}
6773
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006774/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6775/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006776bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6777 QualType rhs) {
6778 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6779 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6780 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6781
Aaron Ballman83731462014-03-17 16:14:00 +00006782 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006783 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006784 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006785 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6786 match = true;
6787 break;
6788 }
6789 }
6790 if (!match)
6791 return false;
6792 }
6793 return true;
6794}
6795
Steve Naroff8e6aee52009-07-23 01:01:38 +00006796/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6797/// ObjCQualifiedIDType.
6798bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6799 bool compare) {
6800 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006801 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006802 lhs->isObjCIdType() || lhs->isObjCClassType())
6803 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006804 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006805 rhs->isObjCIdType() || rhs->isObjCClassType())
6806 return true;
6807
6808 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006809 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006810
Steve Naroff8e6aee52009-07-23 01:01:38 +00006811 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006812
Steve Naroff8e6aee52009-07-23 01:01:38 +00006813 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006814 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006815 // make sure we check the class hierarchy.
6816 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006817 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006818 // when comparing an id<P> on lhs with a static type on rhs,
6819 // see if static class implements all of id's protocols, directly or
6820 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006821 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006822 return false;
6823 }
6824 }
6825 // If there are no qualifiers and no interface, we have an 'id'.
6826 return true;
6827 }
Mike Stump11289f42009-09-09 15:08:12 +00006828 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006829 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006830 bool match = false;
6831
6832 // when comparing an id<P> on lhs with a static type on rhs,
6833 // see if static class implements all of id's protocols, directly or
6834 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006835 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006836 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6837 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6838 match = true;
6839 break;
6840 }
6841 }
Mike Stump11289f42009-09-09 15:08:12 +00006842 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006843 // make sure we check the class hierarchy.
6844 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006845 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006846 // when comparing an id<P> on lhs with a static type on rhs,
6847 // see if static class implements all of id's protocols, directly or
6848 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006849 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006850 match = true;
6851 break;
6852 }
6853 }
6854 }
6855 if (!match)
6856 return false;
6857 }
Mike Stump11289f42009-09-09 15:08:12 +00006858
Steve Naroff8e6aee52009-07-23 01:01:38 +00006859 return true;
6860 }
Mike Stump11289f42009-09-09 15:08:12 +00006861
Steve Naroff8e6aee52009-07-23 01:01:38 +00006862 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6863 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6864
Mike Stump11289f42009-09-09 15:08:12 +00006865 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006866 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006867 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006868 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006869 bool match = false;
6870
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006871 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006872 // see if static class implements all of id's protocols, directly or
6873 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006874 // First, lhs protocols in the qualifier list must be found, direct
6875 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006876 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006877 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6878 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6879 match = true;
6880 break;
6881 }
6882 }
6883 if (!match)
6884 return false;
6885 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006886
6887 // Static class's protocols, or its super class or category protocols
6888 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6889 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6890 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6891 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6892 // This is rather dubious but matches gcc's behavior. If lhs has
6893 // no type qualifier and its class has no static protocol(s)
6894 // assume that it is mismatch.
6895 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6896 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006897 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006898 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006899 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006900 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6901 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6902 match = true;
6903 break;
6904 }
6905 }
6906 if (!match)
6907 return false;
6908 }
6909 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006910 return true;
6911 }
6912 return false;
6913}
6914
Eli Friedman47f77112008-08-22 00:56:42 +00006915/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006916/// compatible for assignment from RHS to LHS. This handles validation of any
6917/// protocol qualifiers on the LHS or RHS.
6918///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006919bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6920 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006921 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6922 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6923
Steve Naroff1329fa02009-07-15 18:40:39 +00006924 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006925 if (LHS->isObjCUnqualifiedIdOrClass() ||
6926 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006927 return true;
6928
Douglas Gregorab209d82015-07-07 03:58:42 +00006929 // Function object that propagates a successful result or handles
6930 // __kindof types.
6931 auto finish = [&](bool succeeded) -> bool {
6932 if (succeeded)
6933 return true;
6934
6935 if (!RHS->isKindOfType())
6936 return false;
6937
6938 // Strip off __kindof and protocol qualifiers, then check whether
6939 // we can assign the other way.
6940 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6941 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6942 };
6943
6944 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6945 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6946 QualType(RHSOPT,0),
6947 false));
6948 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006949
Douglas Gregorab209d82015-07-07 03:58:42 +00006950 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6951 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6952 QualType(RHSOPT,0)));
6953 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006954
John McCall8b07ec22010-05-15 11:32:37 +00006955 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006956 if (LHS->getInterface() && RHS->getInterface()) {
6957 return finish(canAssignObjCInterfaces(LHS, RHS));
6958 }
Mike Stump11289f42009-09-09 15:08:12 +00006959
Steve Naroff8e6aee52009-07-23 01:01:38 +00006960 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006961}
6962
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006963/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006964/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006965/// arguments in block literals. When passed as arguments, passing 'A*' where
6966/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6967/// not OK. For the return type, the opposite is not OK.
6968bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6969 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006970 const ObjCObjectPointerType *RHSOPT,
6971 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006972
6973 // Function object that propagates a successful result or handles
6974 // __kindof types.
6975 auto finish = [&](bool succeeded) -> bool {
6976 if (succeeded)
6977 return true;
6978
6979 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6980 if (!Expected->isKindOfType())
6981 return false;
6982
6983 // Strip off __kindof and protocol qualifiers, then check whether
6984 // we can assign the other way.
6985 return canAssignObjCInterfacesInBlockPointer(
6986 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6987 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6988 BlockReturnType);
6989 };
6990
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006991 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006992 return true;
6993
6994 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006995 return finish(RHSOPT->isObjCBuiltinType() ||
6996 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006997 }
6998
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006999 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007000 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7001 QualType(RHSOPT,0),
7002 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007003
7004 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7005 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7006 if (LHS && RHS) { // We have 2 user-defined types.
7007 if (LHS != RHS) {
7008 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007009 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007010 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007011 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007012 }
7013 else
7014 return true;
7015 }
7016 return false;
7017}
7018
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007019/// Comparison routine for Objective-C protocols to be used with
7020/// llvm::array_pod_sort.
7021static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7022 ObjCProtocolDecl * const *rhs) {
7023 return (*lhs)->getName().compare((*rhs)->getName());
7024
7025}
7026
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007027/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007028/// of protocols inherited from two distinct objective-c pointer objects with
7029/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007030/// It is used to build composite qualifier list of the composite type of
7031/// the conditional expression involving two objective-c pointer objects.
7032static
7033void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007034 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007035 const ObjCObjectPointerType *LHSOPT,
7036 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007037 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007038
John McCall8b07ec22010-05-15 11:32:37 +00007039 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7040 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7041 assert(LHS->getInterface() && "LHS must have an interface base");
7042 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007043
7044 // Add all of the protocols for the LHS.
7045 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7046
7047 // Start with the protocol qualifiers.
7048 for (auto proto : LHS->quals()) {
7049 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007050 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007051
7052 // Also add the protocols associated with the LHS interface.
7053 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7054
7055 // Add all of the protocls for the RHS.
7056 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7057
7058 // Start with the protocol qualifiers.
7059 for (auto proto : RHS->quals()) {
7060 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007061 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007062
7063 // Also add the protocols associated with the RHS interface.
7064 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7065
7066 // Compute the intersection of the collected protocol sets.
7067 for (auto proto : LHSProtocolSet) {
7068 if (RHSProtocolSet.count(proto))
7069 IntersectionSet.push_back(proto);
7070 }
7071
7072 // Compute the set of protocols that is implied by either the common type or
7073 // the protocols within the intersection.
7074 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7075 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7076
7077 // Remove any implied protocols from the list of inherited protocols.
7078 if (!ImpliedProtocols.empty()) {
7079 IntersectionSet.erase(
7080 std::remove_if(IntersectionSet.begin(),
7081 IntersectionSet.end(),
7082 [&](ObjCProtocolDecl *proto) -> bool {
7083 return ImpliedProtocols.count(proto) > 0;
7084 }),
7085 IntersectionSet.end());
7086 }
7087
7088 // Sort the remaining protocols by name.
7089 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7090 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007091}
7092
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007093/// Determine whether the first type is a subtype of the second.
7094static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7095 QualType rhs) {
7096 // Common case: two object pointers.
7097 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7098 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7099 if (lhsOPT && rhsOPT)
7100 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7101
7102 // Two block pointers.
7103 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7104 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7105 if (lhsBlock && rhsBlock)
7106 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7107
7108 // If either is an unqualified 'id' and the other is a block, it's
7109 // acceptable.
7110 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7111 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7112 return true;
7113
7114 return false;
7115}
7116
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007117// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007118static bool sameObjCTypeArgs(ASTContext &ctx,
7119 const ObjCInterfaceDecl *iface,
7120 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007121 ArrayRef<QualType> rhsArgs,
7122 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007123 if (lhsArgs.size() != rhsArgs.size())
7124 return false;
7125
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007126 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007127 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007128 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7129 continue;
7130
7131 switch (typeParams->begin()[i]->getVariance()) {
7132 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007133 if (!stripKindOf ||
7134 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7135 rhsArgs[i].stripObjCKindOfType(ctx))) {
7136 return false;
7137 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007138 break;
7139
7140 case ObjCTypeParamVariance::Covariant:
7141 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7142 return false;
7143 break;
7144
7145 case ObjCTypeParamVariance::Contravariant:
7146 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7147 return false;
7148 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007149 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007150 }
7151
7152 return true;
7153}
7154
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007155QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007156 const ObjCObjectPointerType *Lptr,
7157 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007158 const ObjCObjectType *LHS = Lptr->getObjectType();
7159 const ObjCObjectType *RHS = Rptr->getObjectType();
7160 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7161 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007162
7163 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007164 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007165
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007166 // Follow the left-hand side up the class hierarchy until we either hit a
7167 // root or find the RHS. Record the ancestors in case we don't find it.
7168 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7169 LHSAncestors;
7170 while (true) {
7171 // Record this ancestor. We'll need this if the common type isn't in the
7172 // path from the LHS to the root.
7173 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007174
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007175 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7176 // Get the type arguments.
7177 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7178 bool anyChanges = false;
7179 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7180 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007181 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7182 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007183 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007184 return QualType();
7185 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7186 // If only one has type arguments, the result will not have type
7187 // arguments.
7188 LHSTypeArgs = { };
7189 anyChanges = true;
7190 }
7191
7192 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007193 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007194 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7195 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007196 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007197 anyChanges = true;
7198
7199 // If anything in the LHS will have changed, build a new result type.
7200 if (anyChanges) {
7201 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007202 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7203 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007204 return getObjCObjectPointerType(Result);
7205 }
7206
7207 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007208 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007209
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007210 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007211 QualType LHSSuperType = LHS->getSuperClassType();
7212 if (LHSSuperType.isNull())
7213 break;
7214
7215 LHS = LHSSuperType->castAs<ObjCObjectType>();
7216 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007217
7218 // We didn't find anything by following the LHS to its root; now check
7219 // the RHS against the cached set of ancestors.
7220 while (true) {
7221 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7222 if (KnownLHS != LHSAncestors.end()) {
7223 LHS = KnownLHS->second;
7224
7225 // Get the type arguments.
7226 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7227 bool anyChanges = false;
7228 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7229 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007230 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7231 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007232 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007233 return QualType();
7234 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7235 // If only one has type arguments, the result will not have type
7236 // arguments.
7237 RHSTypeArgs = { };
7238 anyChanges = true;
7239 }
7240
7241 // Compute the intersection of protocols.
7242 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7243 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7244 Protocols);
7245 if (!Protocols.empty())
7246 anyChanges = true;
7247
7248 if (anyChanges) {
7249 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007250 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7251 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007252 return getObjCObjectPointerType(Result);
7253 }
7254
7255 return getObjCObjectPointerType(QualType(RHS, 0));
7256 }
7257
7258 // Find the superclass of the RHS.
7259 QualType RHSSuperType = RHS->getSuperClassType();
7260 if (RHSSuperType.isNull())
7261 break;
7262
7263 RHS = RHSSuperType->castAs<ObjCObjectType>();
7264 }
7265
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007266 return QualType();
7267}
7268
John McCall8b07ec22010-05-15 11:32:37 +00007269bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7270 const ObjCObjectType *RHS) {
7271 assert(LHS->getInterface() && "LHS is not an interface type");
7272 assert(RHS->getInterface() && "RHS is not an interface type");
7273
Chris Lattner49af6a42008-04-07 06:51:04 +00007274 // Verify that the base decls are compatible: the RHS must be a subclass of
7275 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007276 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7277 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7278 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007280
Douglas Gregore83b9562015-07-07 03:57:53 +00007281 // If the LHS has protocol qualifiers, determine whether all of them are
7282 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7283 // LHS).
7284 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007285 // OK if conversion of LHS to SuperClass results in narrowing of types
7286 // ; i.e., SuperClass may implement at least one of the protocols
7287 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7288 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7289 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7290 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7291 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7292 // qualifiers.
7293 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007294 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007295 // If there is no protocols associated with RHS, it is not a match.
7296 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007297 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007298
7299 for (const auto *LHSProto : LHS->quals()) {
7300 bool SuperImplementsProtocol = false;
7301 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7302 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7303 SuperImplementsProtocol = true;
7304 break;
7305 }
7306 if (!SuperImplementsProtocol)
7307 return false;
7308 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007309 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007310
7311 // If the LHS is specialized, we may need to check type arguments.
7312 if (LHS->isSpecialized()) {
7313 // Follow the superclass chain until we've matched the LHS class in the
7314 // hierarchy. This substitutes type arguments through.
7315 const ObjCObjectType *RHSSuper = RHS;
7316 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7317 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7318
7319 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007320 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007321 !sameObjCTypeArgs(*this, LHS->getInterface(),
7322 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007323 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007324 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007325 }
7326 }
7327
7328 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007329}
7330
Steve Naroffb7605152009-02-12 17:52:19 +00007331bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7332 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007333 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7334 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007335
Steve Naroff7cae42b2009-07-10 23:34:53 +00007336 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007337 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007338
7339 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7340 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007341}
7342
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007343bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7344 return canAssignObjCInterfaces(
7345 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7346 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7347}
7348
Mike Stump11289f42009-09-09 15:08:12 +00007349/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007350/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007351/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007352/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007353bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7354 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007355 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007356 return hasSameType(LHS, RHS);
7357
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007358 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007359}
7360
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007361bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007362 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007363}
7364
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007365bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7366 return !mergeTypes(LHS, RHS, true).isNull();
7367}
7368
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007369/// mergeTransparentUnionType - if T is a transparent union type and a member
7370/// of T is compatible with SubType, return the merged type, else return
7371/// QualType()
7372QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7373 bool OfBlockPointer,
7374 bool Unqualified) {
7375 if (const RecordType *UT = T->getAsUnionType()) {
7376 RecordDecl *UD = UT->getDecl();
7377 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007378 for (const auto *I : UD->fields()) {
7379 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007380 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7381 if (!MT.isNull())
7382 return MT;
7383 }
7384 }
7385 }
7386
7387 return QualType();
7388}
7389
Alp Toker9cacbab2014-01-20 20:26:09 +00007390/// mergeFunctionParameterTypes - merge two types which appear as function
7391/// parameter types
7392QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7393 bool OfBlockPointer,
7394 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007395 // GNU extension: two types are compatible if they appear as a function
7396 // argument, one of the types is a transparent union type and the other
7397 // type is compatible with a union member
7398 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7399 Unqualified);
7400 if (!lmerge.isNull())
7401 return lmerge;
7402
7403 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7404 Unqualified);
7405 if (!rmerge.isNull())
7406 return rmerge;
7407
7408 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7409}
7410
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007411QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007412 bool OfBlockPointer,
7413 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007414 const FunctionType *lbase = lhs->getAs<FunctionType>();
7415 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007416 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7417 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007418 bool allLTypes = true;
7419 bool allRTypes = true;
7420
7421 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007422 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007423 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007424 QualType RHS = rbase->getReturnType();
7425 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007426 bool UnqualifiedResult = Unqualified;
7427 if (!UnqualifiedResult)
7428 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007429 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007430 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007431 else
Alp Toker314cc812014-01-25 16:55:45 +00007432 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007433 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007434 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007435
7436 if (Unqualified)
7437 retType = retType.getUnqualifiedType();
7438
Alp Toker314cc812014-01-25 16:55:45 +00007439 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7440 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007441 if (Unqualified) {
7442 LRetType = LRetType.getUnqualifiedType();
7443 RRetType = RRetType.getUnqualifiedType();
7444 }
7445
7446 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007447 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007448 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007449 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007450
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007451 // FIXME: double check this
7452 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7453 // rbase->getRegParmAttr() != 0 &&
7454 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007455 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7456 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007457
Douglas Gregor8c940862010-01-18 17:14:39 +00007458 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007459 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007460 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007461
John McCall8c6b56f2010-12-15 01:06:38 +00007462 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007463 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7464 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007465 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7466 return QualType();
7467
John McCall31168b02011-06-15 23:02:42 +00007468 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7469 return QualType();
7470
John McCall8c6b56f2010-12-15 01:06:38 +00007471 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7472 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007473
Rafael Espindola8778c282012-11-29 16:09:03 +00007474 if (lbaseInfo.getNoReturn() != NoReturn)
7475 allLTypes = false;
7476 if (rbaseInfo.getNoReturn() != NoReturn)
7477 allRTypes = false;
7478
John McCall31168b02011-06-15 23:02:42 +00007479 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007480
Eli Friedman47f77112008-08-22 00:56:42 +00007481 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007482 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7483 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007484 // Compatible functions must have the same number of parameters
7485 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007486 return QualType();
7487
7488 // Variadic and non-variadic functions aren't compatible
7489 if (lproto->isVariadic() != rproto->isVariadic())
7490 return QualType();
7491
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007492 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7493 return QualType();
7494
John McCall18afab72016-03-01 00:49:02 +00007495 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007496 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007497
7498 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007499 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007500 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7501 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7502 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7503 QualType paramType = mergeFunctionParameterTypes(
7504 lParamType, rParamType, OfBlockPointer, Unqualified);
7505 if (paramType.isNull())
7506 return QualType();
7507
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007508 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007509 paramType = paramType.getUnqualifiedType();
7510
7511 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007512 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007513 lParamType = lParamType.getUnqualifiedType();
7514 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007515 }
Alp Toker601b22c2014-01-21 23:35:24 +00007516
7517 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007518 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007519 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007520 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007521 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007522
Eli Friedman47f77112008-08-22 00:56:42 +00007523 if (allLTypes) return lhs;
7524 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007525
7526 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7527 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007528 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007529 }
7530
7531 if (lproto) allRTypes = false;
7532 if (rproto) allLTypes = false;
7533
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007534 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007535 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007536 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007537 if (proto->isVariadic()) return QualType();
7538 // Check that the types are compatible with the types that
7539 // would result from default argument promotions (C99 6.7.5.3p15).
7540 // The only types actually affected are promotable integer
7541 // types and floats, which would be passed as a different
7542 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007543 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7544 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007545
Eli Friedman448ce402012-08-30 00:44:15 +00007546 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007547 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007548 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7549 paramTy = Enum->getDecl()->getIntegerType();
7550 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007551 return QualType();
7552 }
Alp Toker601b22c2014-01-21 23:35:24 +00007553
7554 if (paramTy->isPromotableIntegerType() ||
7555 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007556 return QualType();
7557 }
7558
7559 if (allLTypes) return lhs;
7560 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007561
7562 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7563 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007564 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007565 }
7566
7567 if (allLTypes) return lhs;
7568 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007569 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007570}
7571
John McCall433c2e62013-03-21 00:10:07 +00007572/// Given that we have an enum type and a non-enum type, try to merge them.
7573static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7574 QualType other, bool isBlockReturnType) {
7575 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7576 // a signed integer type, or an unsigned integer type.
7577 // Compatibility is based on the underlying type, not the promotion
7578 // type.
7579 QualType underlyingType = ET->getDecl()->getIntegerType();
7580 if (underlyingType.isNull()) return QualType();
7581 if (Context.hasSameType(underlyingType, other))
7582 return other;
7583
7584 // In block return types, we're more permissive and accept any
7585 // integral type of the same size.
7586 if (isBlockReturnType && other->isIntegerType() &&
7587 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7588 return other;
7589
7590 return QualType();
7591}
7592
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007593QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007594 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007595 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007596 // C++ [expr]: If an expression initially has the type "reference to T", the
7597 // type is adjusted to "T" prior to any further analysis, the expression
7598 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007599 // expression is an lvalue unless the reference is an rvalue reference and
7600 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007601 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7602 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007603
7604 if (Unqualified) {
7605 LHS = LHS.getUnqualifiedType();
7606 RHS = RHS.getUnqualifiedType();
7607 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007608
Eli Friedman47f77112008-08-22 00:56:42 +00007609 QualType LHSCan = getCanonicalType(LHS),
7610 RHSCan = getCanonicalType(RHS);
7611
7612 // If two types are identical, they are compatible.
7613 if (LHSCan == RHSCan)
7614 return LHS;
7615
John McCall8ccfcb52009-09-24 19:53:00 +00007616 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007617 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7618 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007619 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007620 if (getLangOpts().OpenCL) {
7621 if (LHS.getUnqualifiedType() != RHS.getUnqualifiedType() ||
7622 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7623 return QualType();
7624 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7625 return LHS;
7626 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7627 return RHS;
7628 }
John McCall8ccfcb52009-09-24 19:53:00 +00007629 // If any of these qualifiers are different, we have a type
7630 // mismatch.
7631 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007632 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7633 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007634 return QualType();
7635
7636 // Exactly one GC qualifier difference is allowed: __strong is
7637 // okay if the other type has no GC qualifier but is an Objective
7638 // C object pointer (i.e. implicitly strong by default). We fix
7639 // this by pretending that the unqualified type was actually
7640 // qualified __strong.
7641 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7642 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7643 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7644
7645 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7646 return QualType();
7647
7648 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7649 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7650 }
7651 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7652 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7653 }
Eli Friedman47f77112008-08-22 00:56:42 +00007654 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007655 }
7656
7657 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007658
Eli Friedmandcca6332009-06-01 01:22:52 +00007659 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7660 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007661
Chris Lattnerfd652912008-01-14 05:45:46 +00007662 // We want to consider the two function types to be the same for these
7663 // comparisons, just force one to the other.
7664 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7665 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007666
7667 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007668 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7669 LHSClass = Type::ConstantArray;
7670 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7671 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007672
John McCall8b07ec22010-05-15 11:32:37 +00007673 // ObjCInterfaces are just specialized ObjCObjects.
7674 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7675 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7676
Nate Begemance4d7fc2008-04-18 23:10:10 +00007677 // Canonicalize ExtVector -> Vector.
7678 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7679 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007680
Chris Lattner95554662008-04-07 05:43:21 +00007681 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007682 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007683 // Note that we only have special rules for turning block enum
7684 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007685 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007686 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007687 }
John McCall9dd450b2009-09-21 23:43:11 +00007688 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007689 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007690 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007691 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007692 if (OfBlockPointer && !BlockReturnType) {
7693 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7694 return LHS;
7695 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7696 return RHS;
7697 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007698
Eli Friedman47f77112008-08-22 00:56:42 +00007699 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007700 }
Eli Friedman47f77112008-08-22 00:56:42 +00007701
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007702 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007703 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007704#define TYPE(Class, Base)
7705#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007706#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007707#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7708#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7709#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007710 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007711
Richard Smith27d807c2013-04-30 13:56:41 +00007712 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007713 case Type::LValueReference:
7714 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007715 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007716 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007717
John McCall8b07ec22010-05-15 11:32:37 +00007718 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007719 case Type::IncompleteArray:
7720 case Type::VariableArray:
7721 case Type::FunctionProto:
7722 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007723 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007724
Chris Lattnerfd652912008-01-14 05:45:46 +00007725 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007726 {
7727 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007728 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7729 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007730 if (Unqualified) {
7731 LHSPointee = LHSPointee.getUnqualifiedType();
7732 RHSPointee = RHSPointee.getUnqualifiedType();
7733 }
7734 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7735 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007736 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007737 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007738 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007739 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007740 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007741 return getPointerType(ResultType);
7742 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007743 case Type::BlockPointer:
7744 {
7745 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007746 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7747 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007748 if (Unqualified) {
7749 LHSPointee = LHSPointee.getUnqualifiedType();
7750 RHSPointee = RHSPointee.getUnqualifiedType();
7751 }
7752 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7753 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007754 if (ResultType.isNull()) return QualType();
7755 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7756 return LHS;
7757 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7758 return RHS;
7759 return getBlockPointerType(ResultType);
7760 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007761 case Type::Atomic:
7762 {
7763 // Merge two pointer types, while trying to preserve typedef info
7764 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7765 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7766 if (Unqualified) {
7767 LHSValue = LHSValue.getUnqualifiedType();
7768 RHSValue = RHSValue.getUnqualifiedType();
7769 }
7770 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7771 Unqualified);
7772 if (ResultType.isNull()) return QualType();
7773 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7774 return LHS;
7775 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7776 return RHS;
7777 return getAtomicType(ResultType);
7778 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007779 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007780 {
7781 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7782 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7783 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7784 return QualType();
7785
7786 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7787 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007788 if (Unqualified) {
7789 LHSElem = LHSElem.getUnqualifiedType();
7790 RHSElem = RHSElem.getUnqualifiedType();
7791 }
7792
7793 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007794 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007795 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7796 return LHS;
7797 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7798 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007799 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7800 ArrayType::ArraySizeModifier(), 0);
7801 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7802 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007803 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7804 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007805 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7806 return LHS;
7807 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7808 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007809 if (LVAT) {
7810 // FIXME: This isn't correct! But tricky to implement because
7811 // the array's size has to be the size of LHS, but the type
7812 // has to be different.
7813 return LHS;
7814 }
7815 if (RVAT) {
7816 // FIXME: This isn't correct! But tricky to implement because
7817 // the array's size has to be the size of RHS, but the type
7818 // has to be different.
7819 return RHS;
7820 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007821 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7822 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007823 return getIncompleteArrayType(ResultType,
7824 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007825 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007826 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007827 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007828 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007829 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007830 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007831 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007832 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007833 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007834 case Type::Complex:
7835 // Distinct complex types are incompatible.
7836 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007837 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007838 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007839 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7840 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007841 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007842 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007843 case Type::ObjCObject: {
7844 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007845 // FIXME: This should be type compatibility, e.g. whether
7846 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007847 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7848 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7849 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007850 return LHS;
7851
Eli Friedman47f77112008-08-22 00:56:42 +00007852 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007853 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007854 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007855 if (OfBlockPointer) {
7856 if (canAssignObjCInterfacesInBlockPointer(
7857 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007858 RHS->getAs<ObjCObjectPointerType>(),
7859 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007860 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007861 return QualType();
7862 }
John McCall9dd450b2009-09-21 23:43:11 +00007863 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7864 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007865 return LHS;
7866
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007867 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007868 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00007869 case Type::Pipe:
7870 {
7871 // Merge two pointer types, while trying to preserve typedef info
7872 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7873 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7874 if (Unqualified) {
7875 LHSValue = LHSValue.getUnqualifiedType();
7876 RHSValue = RHSValue.getUnqualifiedType();
7877 }
7878 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7879 Unqualified);
7880 if (ResultType.isNull()) return QualType();
7881 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7882 return LHS;
7883 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7884 return RHS;
7885 return getPipeType(ResultType);
7886 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007887 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007888
David Blaikie8a40f702012-01-17 06:56:22 +00007889 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007890}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007891
John McCall18afab72016-03-01 00:49:02 +00007892bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7893 const FunctionProtoType *firstFnType,
7894 const FunctionProtoType *secondFnType) {
7895 // Fast path: if the first type doesn't have ext parameter infos,
7896 // we match if and only if they second type also doesn't have them.
7897 if (!firstFnType->hasExtParameterInfos())
7898 return !secondFnType->hasExtParameterInfos();
7899
7900 // Otherwise, we can only match if the second type has them.
7901 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007902 return false;
John McCall18afab72016-03-01 00:49:02 +00007903
7904 auto firstEPI = firstFnType->getExtParameterInfos();
7905 auto secondEPI = secondFnType->getExtParameterInfos();
7906 assert(firstEPI.size() == secondEPI.size());
7907
7908 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
7909 if (firstEPI[i] != secondEPI[i])
7910 return false;
7911 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007912 return true;
7913}
7914
Chandler Carruth21c90602015-12-30 03:24:14 +00007915void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7916 ObjCLayouts[CD] = nullptr;
7917}
7918
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007919/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7920/// 'RHS' attributes and returns the merged version; including for function
7921/// return types.
7922QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7923 QualType LHSCan = getCanonicalType(LHS),
7924 RHSCan = getCanonicalType(RHS);
7925 // If two types are identical, they are compatible.
7926 if (LHSCan == RHSCan)
7927 return LHS;
7928 if (RHSCan->isFunctionType()) {
7929 if (!LHSCan->isFunctionType())
7930 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007931 QualType OldReturnType =
7932 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007933 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007934 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007935 QualType ResReturnType =
7936 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7937 if (ResReturnType.isNull())
7938 return QualType();
7939 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7940 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7941 // In either case, use OldReturnType to build the new function type.
7942 const FunctionType *F = LHS->getAs<FunctionType>();
7943 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007944 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7945 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007946 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007947 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007948 return ResultType;
7949 }
7950 }
7951 return QualType();
7952 }
7953
7954 // If the qualifiers are different, the types can still be merged.
7955 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7956 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7957 if (LQuals != RQuals) {
7958 // If any of these qualifiers are different, we have a type mismatch.
7959 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7960 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7961 return QualType();
7962
7963 // Exactly one GC qualifier difference is allowed: __strong is
7964 // okay if the other type has no GC qualifier but is an Objective
7965 // C object pointer (i.e. implicitly strong by default). We fix
7966 // this by pretending that the unqualified type was actually
7967 // qualified __strong.
7968 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7969 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7970 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7971
7972 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7973 return QualType();
7974
7975 if (GC_L == Qualifiers::Strong)
7976 return LHS;
7977 if (GC_R == Qualifiers::Strong)
7978 return RHS;
7979 return QualType();
7980 }
7981
7982 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7983 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7984 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7985 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7986 if (ResQT == LHSBaseQT)
7987 return LHS;
7988 if (ResQT == RHSBaseQT)
7989 return RHS;
7990 }
7991 return QualType();
7992}
7993
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007994//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007995// Integer Predicates
7996//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007997
Jay Foad39c79802011-01-12 09:06:06 +00007998unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007999 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008000 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008001 if (T->isBooleanType())
8002 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008003 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008004 return (unsigned)getTypeSize(T);
8005}
8006
Abramo Bagnara13640492012-09-09 10:21:24 +00008007QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008008 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008009
8010 // Turn <4 x signed int> -> <4 x unsigned int>
8011 if (const VectorType *VTy = T->getAs<VectorType>())
8012 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008013 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008014
8015 // For enums, we return the unsigned version of the base type.
8016 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008017 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008018
8019 const BuiltinType *BTy = T->getAs<BuiltinType>();
8020 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008021 switch (BTy->getKind()) {
8022 case BuiltinType::Char_S:
8023 case BuiltinType::SChar:
8024 return UnsignedCharTy;
8025 case BuiltinType::Short:
8026 return UnsignedShortTy;
8027 case BuiltinType::Int:
8028 return UnsignedIntTy;
8029 case BuiltinType::Long:
8030 return UnsignedLongTy;
8031 case BuiltinType::LongLong:
8032 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008033 case BuiltinType::Int128:
8034 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008035 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008036 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008037 }
8038}
8039
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008040ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008041
Richard Smith1fa5d642013-05-11 05:45:24 +00008042void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8043 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008044
8045//===----------------------------------------------------------------------===//
8046// Builtin Type Computation
8047//===----------------------------------------------------------------------===//
8048
8049/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008050/// pointer over the consumed characters. This returns the resultant type. If
8051/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8052/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8053/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008054///
8055/// RequiresICE is filled in on return to indicate whether the value is required
8056/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008057static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008058 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008059 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008060 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008061 // Modifiers.
8062 int HowLong = 0;
8063 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008064 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008065
Chris Lattnerdc226c22010-10-01 22:42:38 +00008066 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008067 bool Done = false;
8068 while (!Done) {
8069 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008070 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008071 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008072 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008073 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008074 case 'S':
8075 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8076 assert(!Signed && "Can't use 'S' modifier multiple times!");
8077 Signed = true;
8078 break;
8079 case 'U':
8080 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008081 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008082 Unsigned = true;
8083 break;
8084 case 'L':
8085 assert(HowLong <= 2 && "Can't have LLLL modifier");
8086 ++HowLong;
8087 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008088 case 'W':
8089 // This modifier represents int64 type.
8090 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8091 switch (Context.getTargetInfo().getInt64Type()) {
8092 default:
8093 llvm_unreachable("Unexpected integer type");
8094 case TargetInfo::SignedLong:
8095 HowLong = 1;
8096 break;
8097 case TargetInfo::SignedLongLong:
8098 HowLong = 2;
8099 break;
8100 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008101 }
8102 }
8103
8104 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008105
Chris Lattnerecd79c62009-06-14 00:45:47 +00008106 // Read the base type.
8107 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008108 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008109 case 'v':
8110 assert(HowLong == 0 && !Signed && !Unsigned &&
8111 "Bad modifiers used with 'v'!");
8112 Type = Context.VoidTy;
8113 break;
Jack Carter24bef982013-08-15 15:16:57 +00008114 case 'h':
8115 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008116 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008117 Type = Context.HalfTy;
8118 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008119 case 'f':
8120 assert(HowLong == 0 && !Signed && !Unsigned &&
8121 "Bad modifiers used with 'f'!");
8122 Type = Context.FloatTy;
8123 break;
8124 case 'd':
8125 assert(HowLong < 2 && !Signed && !Unsigned &&
8126 "Bad modifiers used with 'd'!");
8127 if (HowLong)
8128 Type = Context.LongDoubleTy;
8129 else
8130 Type = Context.DoubleTy;
8131 break;
8132 case 's':
8133 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8134 if (Unsigned)
8135 Type = Context.UnsignedShortTy;
8136 else
8137 Type = Context.ShortTy;
8138 break;
8139 case 'i':
8140 if (HowLong == 3)
8141 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8142 else if (HowLong == 2)
8143 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8144 else if (HowLong == 1)
8145 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8146 else
8147 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8148 break;
8149 case 'c':
8150 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8151 if (Signed)
8152 Type = Context.SignedCharTy;
8153 else if (Unsigned)
8154 Type = Context.UnsignedCharTy;
8155 else
8156 Type = Context.CharTy;
8157 break;
8158 case 'b': // boolean
8159 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8160 Type = Context.BoolTy;
8161 break;
8162 case 'z': // size_t.
8163 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8164 Type = Context.getSizeType();
8165 break;
8166 case 'F':
8167 Type = Context.getCFConstantStringType();
8168 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008169 case 'G':
8170 Type = Context.getObjCIdType();
8171 break;
8172 case 'H':
8173 Type = Context.getObjCSelType();
8174 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008175 case 'M':
8176 Type = Context.getObjCSuperType();
8177 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008178 case 'a':
8179 Type = Context.getBuiltinVaListType();
8180 assert(!Type.isNull() && "builtin va list type not initialized!");
8181 break;
8182 case 'A':
8183 // This is a "reference" to a va_list; however, what exactly
8184 // this means depends on how va_list is defined. There are two
8185 // different kinds of va_list: ones passed by value, and ones
8186 // passed by reference. An example of a by-value va_list is
8187 // x86, where va_list is a char*. An example of by-ref va_list
8188 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8189 // we want this argument to be a char*&; for x86-64, we want
8190 // it to be a __va_list_tag*.
8191 Type = Context.getBuiltinVaListType();
8192 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008193 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008194 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008195 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008196 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008197 break;
8198 case 'V': {
8199 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008200 unsigned NumElements = strtoul(Str, &End, 10);
8201 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008202 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008203
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008204 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8205 RequiresICE, false);
8206 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008207
8208 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008209 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008210 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008211 break;
8212 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008213 case 'E': {
8214 char *End;
8215
8216 unsigned NumElements = strtoul(Str, &End, 10);
8217 assert(End != Str && "Missing vector size");
8218
8219 Str = End;
8220
8221 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8222 false);
8223 Type = Context.getExtVectorType(ElementType, NumElements);
8224 break;
8225 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008226 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008227 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8228 false);
8229 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008230 Type = Context.getComplexType(ElementType);
8231 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008232 }
8233 case 'Y' : {
8234 Type = Context.getPointerDiffType();
8235 break;
8236 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008237 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008238 Type = Context.getFILEType();
8239 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008240 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008241 return QualType();
8242 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008243 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008244 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008245 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008246 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008247 else
8248 Type = Context.getjmp_bufType();
8249
Mike Stump2adb4da2009-07-28 23:47:15 +00008250 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008251 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008252 return QualType();
8253 }
8254 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008255 case 'K':
8256 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8257 Type = Context.getucontext_tType();
8258
8259 if (Type.isNull()) {
8260 Error = ASTContext::GE_Missing_ucontext;
8261 return QualType();
8262 }
8263 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008264 case 'p':
8265 Type = Context.getProcessIDType();
8266 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008267 }
Mike Stump11289f42009-09-09 15:08:12 +00008268
Chris Lattnerdc226c22010-10-01 22:42:38 +00008269 // If there are modifiers and if we're allowed to parse them, go for it.
8270 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008271 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008272 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008273 default: Done = true; --Str; break;
8274 case '*':
8275 case '&': {
8276 // Both pointers and references can have their pointee types
8277 // qualified with an address space.
8278 char *End;
8279 unsigned AddrSpace = strtoul(Str, &End, 10);
8280 if (End != Str && AddrSpace != 0) {
8281 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8282 Str = End;
8283 }
8284 if (c == '*')
8285 Type = Context.getPointerType(Type);
8286 else
8287 Type = Context.getLValueReferenceType(Type);
8288 break;
8289 }
8290 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8291 case 'C':
8292 Type = Type.withConst();
8293 break;
8294 case 'D':
8295 Type = Context.getVolatileType(Type);
8296 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008297 case 'R':
8298 Type = Type.withRestrict();
8299 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008300 }
8301 }
Chris Lattner84733392010-10-01 07:13:18 +00008302
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008303 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008304 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008305
Chris Lattnerecd79c62009-06-14 00:45:47 +00008306 return Type;
8307}
8308
8309/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008310QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008311 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008312 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008313 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008314
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008315 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008316
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008317 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008318 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008319 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8320 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008321 if (Error != GE_None)
8322 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008323
8324 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8325
Chris Lattnerecd79c62009-06-14 00:45:47 +00008326 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008327 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008328 if (Error != GE_None)
8329 return QualType();
8330
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008331 // If this argument is required to be an IntegerConstantExpression and the
8332 // caller cares, fill in the bitmask we return.
8333 if (RequiresICE && IntegerConstantArgs)
8334 *IntegerConstantArgs |= 1 << ArgTypes.size();
8335
Chris Lattnerecd79c62009-06-14 00:45:47 +00008336 // Do array -> pointer decay. The builtin should use the decayed type.
8337 if (Ty->isArrayType())
8338 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008339
Chris Lattnerecd79c62009-06-14 00:45:47 +00008340 ArgTypes.push_back(Ty);
8341 }
8342
David Majnemerba3e5ec2015-03-13 18:26:17 +00008343 if (Id == Builtin::BI__GetExceptionInfo)
8344 return QualType();
8345
Chris Lattnerecd79c62009-06-14 00:45:47 +00008346 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8347 "'.' should only occur at end of builtin type list!");
8348
Reid Kleckner78af0702013-08-27 23:08:25 +00008349 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008350 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8351
8352 bool Variadic = (TypeStr[0] == '.');
8353
8354 // We really shouldn't be making a no-proto type here, especially in C++.
8355 if (ArgTypes.empty() && Variadic)
8356 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008357
John McCalldb40c7f2010-12-14 08:05:40 +00008358 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008359 EPI.ExtInfo = EI;
8360 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008361
Jordan Rose5c382722013-03-08 21:51:21 +00008362 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008363}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008364
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008365static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8366 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008367 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008368 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008369
Rafael Espindola3ae00052013-05-13 00:12:11 +00008370 GVALinkage External = GVA_StrongExternal;
8371 switch (FD->getTemplateSpecializationKind()) {
8372 case TSK_Undeclared:
8373 case TSK_ExplicitSpecialization:
8374 External = GVA_StrongExternal;
8375 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008376
Rafael Espindola3ae00052013-05-13 00:12:11 +00008377 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008378 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008379
David Majnemerc3d07332014-05-15 06:25:57 +00008380 // C++11 [temp.explicit]p10:
8381 // [ Note: The intent is that an inline function that is the subject of
8382 // an explicit instantiation declaration will still be implicitly
8383 // instantiated when used so that the body can be considered for
8384 // inlining, but that no out-of-line copy of the inline function would be
8385 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008386 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008387 return GVA_AvailableExternally;
8388
Rafael Espindola3ae00052013-05-13 00:12:11 +00008389 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008390 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008391 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008392 }
8393
8394 if (!FD->isInlined())
8395 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008396
David Majnemer3f021502015-10-08 04:53:31 +00008397 if ((!Context.getLangOpts().CPlusPlus &&
8398 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008399 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008400 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008401 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8402
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008403 // GNU or C99 inline semantics. Determine whether this symbol should be
8404 // externally visible.
8405 if (FD->isInlineDefinitionExternallyVisible())
8406 return External;
8407
8408 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008409 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008410 }
8411
David Majnemer54e3ba52014-04-02 23:17:29 +00008412 // Functions specified with extern and inline in -fms-compatibility mode
8413 // forcibly get emitted. While the body of the function cannot be later
8414 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008415 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008416 return GVA_StrongODR;
8417
David Majnemer27d69db2014-04-28 22:17:59 +00008418 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008419}
8420
Artem Belevich7b41f702015-09-23 17:44:53 +00008421static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008422 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8423 // dllexport/dllimport on inline functions.
8424 if (D->hasAttr<DLLImportAttr>()) {
8425 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8426 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008427 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008428 if (L == GVA_DiscardableODR)
8429 return GVA_StrongODR;
8430 }
8431 return L;
8432}
8433
8434GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008435 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8436 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008437}
8438
8439static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8440 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008441 if (!VD->isExternallyVisible())
8442 return GVA_Internal;
8443
David Majnemer27d69db2014-04-28 22:17:59 +00008444 if (VD->isStaticLocal()) {
8445 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8446 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8447 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8448 LexicalContext = LexicalContext->getLexicalParent();
8449
Richard Smith9e2341d2015-03-23 03:25:59 +00008450 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008451 // enclosing function.
8452 if (LexicalContext)
8453 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008454 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008455
8456 // GVA_StrongODR function linkage is stronger than what we need,
8457 // downgrade to GVA_DiscardableODR.
8458 // This allows us to discard the variable if we never end up needing it.
8459 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8460 : StaticLocalLinkage;
8461 }
8462
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008463 // MSVC treats in-class initialized static data members as definitions.
8464 // By giving them non-strong linkage, out-of-line definitions won't
8465 // cause link errors.
8466 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8467 return GVA_DiscardableODR;
8468
Richard Smith8809a0c2013-09-27 20:14:12 +00008469 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008470 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008471 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008472
David Majnemer6d1780c2015-07-17 23:36:49 +00008473 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008474 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8475 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008476 ? GVA_StrongODR
8477 : GVA_StrongExternal;
8478
Rafael Espindola3ae00052013-05-13 00:12:11 +00008479 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008480 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008481
David Majnemer27d69db2014-04-28 22:17:59 +00008482 case TSK_ExplicitInstantiationDeclaration:
8483 return GVA_AvailableExternally;
8484
Rafael Espindola3ae00052013-05-13 00:12:11 +00008485 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008486 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008487 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008488
8489 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008490}
8491
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008492GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008493 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8494 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008495}
8496
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008497bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008498 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8499 if (!VD->isFileVarDecl())
8500 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008501 // Global named register variables (GNU extension) are never emitted.
8502 if (VD->getStorageClass() == SC_Register)
8503 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008504 if (VD->getDescribedVarTemplate() ||
8505 isa<VarTemplatePartialSpecializationDecl>(VD))
8506 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008507 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8508 // We never need to emit an uninstantiated function template.
8509 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8510 return false;
Nico Weber66220292016-03-02 17:28:48 +00008511 } else if (isa<PragmaCommentDecl>(D))
8512 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008513 else if (isa<OMPThreadPrivateDecl>(D) ||
8514 D->hasAttr<OMPDeclareTargetDeclAttr>())
8515 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008516 else if (isa<PragmaDetectMismatchDecl>(D))
8517 return true;
Nico Weber66220292016-03-02 17:28:48 +00008518 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008519 return !D->getDeclContext()->isDependentContext();
8520 else if (isa<OMPDeclareReductionDecl>(D))
8521 return !D->getDeclContext()->isDependentContext();
Alexey Bataev97720002014-11-11 04:05:39 +00008522 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008523 return false;
8524
8525 // If this is a member of a class template, we do not need to emit it.
8526 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008527 return false;
8528
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008529 // Weak references don't produce any output by themselves.
8530 if (D->hasAttr<WeakRefAttr>())
8531 return false;
8532
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008533 // Aliases and used decls are required.
8534 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8535 return true;
8536
8537 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8538 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008539 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008540 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008541
8542 // Constructors and destructors are required.
8543 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8544 return true;
8545
John McCall6bd2a892013-01-25 22:31:03 +00008546 // The key function for a class is required. This rule only comes
8547 // into play when inline functions can be key functions, though.
8548 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8549 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8550 const CXXRecordDecl *RD = MD->getParent();
8551 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8552 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8553 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8554 return true;
8555 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008556 }
8557 }
8558
8559 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8560
8561 // static, static inline, always_inline, and extern inline functions can
8562 // always be deferred. Normal inline functions can be deferred in C99/C++.
8563 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008564 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8565 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008566 return false;
8567 return true;
8568 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008569
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008570 const VarDecl *VD = cast<VarDecl>(D);
8571 assert(VD->isFileVarDecl() && "Expected file scoped var");
8572
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008573 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8574 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008575 return false;
8576
Richard Smitha0e5e542012-11-12 21:38:00 +00008577 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008578 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008579 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8580 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008581 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008582
Richard Smitha0e5e542012-11-12 21:38:00 +00008583 // Variables that have destruction with side-effects are required.
8584 if (VD->getType().isDestructedType())
8585 return true;
8586
8587 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008588 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8589 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008590 return true;
8591
8592 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008593}
Charles Davis53c59df2010-08-16 03:33:14 +00008594
Reid Kleckner78af0702013-08-27 23:08:25 +00008595CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8596 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008597 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008598 if (IsCXXMethod)
8599 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008600
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008601 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8602
8603 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008604}
8605
Jay Foad39c79802011-01-12 09:06:06 +00008606bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008607 // Pass through to the C++ ABI object
8608 return ABI->isNearlyEmpty(RD);
8609}
8610
Reid Kleckner96f8f932014-02-05 17:27:08 +00008611VTableContextBase *ASTContext::getVTableContext() {
8612 if (!VTContext.get()) {
8613 if (Target->getCXXABI().isMicrosoft())
8614 VTContext.reset(new MicrosoftVTableContext(*this));
8615 else
8616 VTContext.reset(new ItaniumVTableContext(*this));
8617 }
8618 return VTContext.get();
8619}
8620
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008621MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008622 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008623 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008624 case TargetCXXABI::GenericItanium:
8625 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008626 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008627 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008628 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008629 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008630 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008631 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008632 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008633 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008634 }
David Blaikie83d382b2011-09-23 05:06:16 +00008635 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008636}
8637
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008638CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008639
8640size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008641 return ASTRecordLayouts.getMemorySize() +
8642 llvm::capacity_in_bytes(ObjCLayouts) +
8643 llvm::capacity_in_bytes(KeyFunctions) +
8644 llvm::capacity_in_bytes(ObjCImpls) +
8645 llvm::capacity_in_bytes(BlockVarCopyInits) +
8646 llvm::capacity_in_bytes(DeclAttrs) +
8647 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8648 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8649 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8650 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8651 llvm::capacity_in_bytes(OverriddenMethods) +
8652 llvm::capacity_in_bytes(Types) +
8653 llvm::capacity_in_bytes(VariableArrayTypes) +
8654 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008655}
Ted Kremenek540017e2011-10-06 05:00:56 +00008656
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008657/// getIntTypeForBitwidth -
8658/// sets integer QualTy according to specified details:
8659/// bitwidth, signed/unsigned.
8660/// Returns empty type if there is no appropriate target types.
8661QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8662 unsigned Signed) const {
8663 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8664 CanQualType QualTy = getFromTargetType(Ty);
8665 if (!QualTy && DestWidth == 128)
8666 return Signed ? Int128Ty : UnsignedInt128Ty;
8667 return QualTy;
8668}
8669
8670/// getRealTypeForBitwidth -
8671/// sets floating point QualTy according to specified bitwidth.
8672/// Returns empty type if there is no appropriate target types.
8673QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8674 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8675 switch (Ty) {
8676 case TargetInfo::Float:
8677 return FloatTy;
8678 case TargetInfo::Double:
8679 return DoubleTy;
8680 case TargetInfo::LongDouble:
8681 return LongDoubleTy;
8682 case TargetInfo::NoFloat:
8683 return QualType();
8684 }
8685
8686 llvm_unreachable("Unhandled TargetInfo::RealType value");
8687}
8688
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008689void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8690 if (Number > 1)
8691 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008692}
8693
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008694unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008695 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008696 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008697}
8698
David Majnemer2206bf52014-03-05 08:57:59 +00008699void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8700 if (Number > 1)
8701 StaticLocalNumbers[VD] = Number;
8702}
8703
8704unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008705 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00008706 return I != StaticLocalNumbers.end() ? I->second : 1;
8707}
8708
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008709MangleNumberingContext &
8710ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008711 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8712 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8713 if (!MCtx)
8714 MCtx = createMangleNumberingContext();
8715 return *MCtx;
8716}
8717
8718MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8719 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008720}
8721
David Majnemere7a818f2015-03-06 18:53:55 +00008722const CXXConstructorDecl *
8723ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8724 return ABI->getCopyConstructorForExceptionObject(
8725 cast<CXXRecordDecl>(RD->getFirstDecl()));
8726}
8727
8728void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8729 CXXConstructorDecl *CD) {
8730 return ABI->addCopyConstructorForExceptionObject(
8731 cast<CXXRecordDecl>(RD->getFirstDecl()),
8732 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8733}
8734
David Majnemerdfa6d202015-03-11 18:36:39 +00008735void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8736 unsigned ParmIdx, Expr *DAE) {
8737 ABI->addDefaultArgExprForConstructor(
8738 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8739}
8740
8741Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8742 unsigned ParmIdx) {
8743 return ABI->getDefaultArgExprForConstructor(
8744 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8745}
8746
David Majnemer00350522015-08-31 18:48:39 +00008747void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8748 TypedefNameDecl *DD) {
8749 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8750}
8751
8752TypedefNameDecl *
8753ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8754 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8755}
8756
8757void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8758 DeclaratorDecl *DD) {
8759 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8760}
8761
8762DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8763 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8764}
8765
Ted Kremenek540017e2011-10-06 05:00:56 +00008766void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8767 ParamIndices[D] = index;
8768}
8769
8770unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8771 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8772 assert(I != ParamIndices.end() &&
8773 "ParmIndices lacks entry set by ParmVarDecl");
8774 return I->second;
8775}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008776
Richard Smithe6c01442013-06-05 00:46:14 +00008777APValue *
8778ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8779 bool MayCreate) {
8780 assert(E && E->getStorageDuration() == SD_Static &&
8781 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008782 if (MayCreate) {
8783 APValue *&MTVI = MaterializedTemporaryValues[E];
8784 if (!MTVI)
8785 MTVI = new (*this) APValue;
8786 return MTVI;
8787 }
Richard Smithe6c01442013-06-05 00:46:14 +00008788
David Majnemer2dcef9e2015-08-13 23:50:15 +00008789 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008790}
8791
Fariborz Jahanian615de762013-05-28 17:37:39 +00008792bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8793 const llvm::Triple &T = getTargetInfo().getTriple();
8794 if (!T.isOSDarwin())
8795 return false;
8796
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008797 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8798 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8799 return false;
8800
Fariborz Jahanian615de762013-05-28 17:37:39 +00008801 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8802 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8803 uint64_t Size = sizeChars.getQuantity();
8804 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8805 unsigned Align = alignChars.getQuantity();
8806 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8807 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8808}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008809
8810namespace {
8811
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008812ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8813 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008814 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008815 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008816 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008817 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008818 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008819}
8820
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008821/// Template specializations to abstract away from pointers and TypeLocs.
8822/// @{
8823template <typename T>
8824ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8825 return ast_type_traits::DynTypedNode::create(*Node);
8826}
8827template <>
8828ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8829 return ast_type_traits::DynTypedNode::create(Node);
8830}
8831template <>
8832ast_type_traits::DynTypedNode
8833createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8834 return ast_type_traits::DynTypedNode::create(Node);
8835}
8836/// @}
8837
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008838 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8839 /// parents as defined by the \c RecursiveASTVisitor.
8840 ///
8841 /// Note that the relationship described here is purely in terms of AST
8842 /// traversal - there are other relationships (for example declaration context)
8843 /// in the AST that are better modeled by special matchers.
8844 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008845 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008846 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008847 public:
8848 /// \brief Builds and returns the translation unit's parent map.
8849 ///
8850 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008851 static std::pair<ASTContext::ParentMapPointers *,
8852 ASTContext::ParentMapOtherNodes *>
8853 buildMap(TranslationUnitDecl &TU) {
8854 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8855 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008856 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008857 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008858 }
8859
8860 private:
8861 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8862
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008863 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8864 ASTContext::ParentMapOtherNodes *OtherParents)
8865 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008866
8867 bool shouldVisitTemplateInstantiations() const {
8868 return true;
8869 }
8870 bool shouldVisitImplicitCode() const {
8871 return true;
8872 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008873
Richard Smith85838722015-11-24 03:09:01 +00008874 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8875 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008876 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00008877 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008878 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008879 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008880 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008881 // FIXME: Currently we add the same parent multiple times, but only
8882 // when no memoization data is available for the type.
8883 // For example when we visit all subexpressions of template
8884 // instantiations; this is suboptimal, but benign: the only way to
8885 // visit those is with hasAncestor / hasParent, and those do not create
8886 // new matches.
8887 // The plan is to enable DynTypedNode to be storable in a map or hash
8888 // map. The main problem there is to implement hash functions /
8889 // comparison operators for all types that DynTypedNode supports that
8890 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008891 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008892 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008893 if (const auto *D = ParentStack.back().get<Decl>())
8894 NodeOrVector = D;
8895 else if (const auto *S = ParentStack.back().get<Stmt>())
8896 NodeOrVector = S;
8897 else
8898 NodeOrVector =
8899 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008900 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008901 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8902 auto *Vector = new ASTContext::ParentVector(
8903 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008904 if (auto *Node =
8905 NodeOrVector
8906 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8907 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008908 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008909 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008910
8911 auto *Vector =
8912 NodeOrVector.template get<ASTContext::ParentVector *>();
8913 // Skip duplicates for types that have memoization data.
8914 // We must check that the type has memoization data before calling
8915 // std::find() because DynTypedNode::operator== can't compare all
8916 // types.
8917 bool Found = ParentStack.back().getMemoizationData() &&
8918 std::find(Vector->begin(), Vector->end(),
8919 ParentStack.back()) != Vector->end();
8920 if (!Found)
8921 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008922 }
8923 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008924 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00008925 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008926 ParentStack.pop_back();
8927 return Result;
8928 }
8929
8930 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00008931 return TraverseNode(DeclNode, DeclNode,
8932 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008933 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008934 }
8935
8936 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00008937 return TraverseNode(StmtNode, StmtNode,
8938 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008939 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008940 }
8941
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008942 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00008943 return TraverseNode(
8944 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
8945 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
8946 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008947 }
8948
8949 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8950 return TraverseNode(
8951 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00008952 [&] {
8953 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
8954 },
8955 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008956 }
8957
8958 ASTContext::ParentMapPointers *Parents;
8959 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008960 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8961
8962 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8963 };
8964
Eugene Zelenkod4304d22015-11-04 21:37:17 +00008965} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008966
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008967template <typename NodeTy, typename MapTy>
8968static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8969 const MapTy &Map) {
8970 auto I = Map.find(Node);
8971 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008972 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008973 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008974 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008975 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00008976 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008977 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008978}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008979
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008980ASTContext::DynTypedNodeList
8981ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8982 if (!PointerParents) {
8983 // We always need to run over the whole translation unit, as
8984 // hasAncestor can escape any subtree.
8985 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8986 PointerParents.reset(Maps.first);
8987 OtherParents.reset(Maps.second);
8988 }
8989 if (Node.getNodeKind().hasPointerIdentity())
8990 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8991 return getDynNodeFromMap(Node, *OtherParents);
8992}
8993
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008994bool
8995ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8996 const ObjCMethodDecl *MethodImpl) {
8997 // No point trying to match an unavailable/deprecated mothod.
8998 if (MethodDecl->hasAttr<UnavailableAttr>()
8999 || MethodDecl->hasAttr<DeprecatedAttr>())
9000 return false;
9001 if (MethodDecl->getObjCDeclQualifier() !=
9002 MethodImpl->getObjCDeclQualifier())
9003 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009004 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009005 return false;
9006
9007 if (MethodDecl->param_size() != MethodImpl->param_size())
9008 return false;
9009
9010 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9011 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9012 EF = MethodDecl->param_end();
9013 IM != EM && IF != EF; ++IM, ++IF) {
9014 const ParmVarDecl *DeclVar = (*IF);
9015 const ParmVarDecl *ImplVar = (*IM);
9016 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9017 return false;
9018 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9019 return false;
9020 }
9021 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9022
9023}
Richard Smith053f6c62014-05-16 23:01:30 +00009024
9025// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9026// doesn't include ASTContext.h
9027template
9028clang::LazyGenerationalUpdatePtr<
9029 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9030clang::LazyGenerationalUpdatePtr<
9031 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9032 const clang::ASTContext &Ctx, Decl *Value);