blob: 0414c7a9faf85a89bf1f42e2b567bd0ad5010392 [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 {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000061 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
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),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000737 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
738 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
739 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000740 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
741 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
742 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
743 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
744 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000745 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
746 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000747 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000748 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
749 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
750 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
751 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000752 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000753 TUDecl = TranslationUnitDecl::Create(*this);
754}
755
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000756ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000757 ReleaseParentMapEntries();
758
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000759 // Release the DenseMaps associated with DeclContext objects.
760 // FIXME: Is this the ideal solution?
761 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000762
Manuel Klimeka7328992013-06-03 13:51:33 +0000763 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000764 for (auto &Pair : Deallocations)
765 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000766
Ted Kremenek076baeb2010-06-08 23:00:58 +0000767 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000768 // because they can contain DenseMaps.
769 for (llvm::DenseMap<const ObjCContainerDecl*,
770 const ASTRecordLayout*>::iterator
771 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
772 // Increment in loop to prevent using deallocated memory.
773 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
774 R->Destroy(*this);
775
Ted Kremenek076baeb2010-06-08 23:00:58 +0000776 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
777 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000782
783 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
784 AEnd = DeclAttrs.end();
785 A != AEnd; ++A)
786 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000787
David Majnemere694f3e2015-08-14 14:43:50 +0000788 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
789 MaterializedTemporaryValues)
790 MTVPair.second->~APValue();
791
Reid Kleckner588c9372014-02-19 23:44:52 +0000792 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000793}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000794
Manuel Klimek95403e62014-05-21 13:28:59 +0000795void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000796 if (!PointerParents) return;
797 for (const auto &Entry : *PointerParents) {
798 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
799 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
800 } else if (Entry.second.is<ParentVector *>()) {
801 delete Entry.second.get<ParentVector *>();
802 }
803 }
804 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
806 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000807 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000808 delete Entry.second.get<ParentVector *>();
809 }
810 }
811}
812
Douglas Gregor1a809332010-05-23 18:26:36 +0000813void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000814 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000815}
816
Mike Stump11289f42009-09-09 15:08:12 +0000817void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000818ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000819 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000820}
821
Chris Lattner4eb445d2007-01-26 01:27:23 +0000822void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000823 llvm::errs() << "\n*** AST Context Stats:\n";
824 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000825
Douglas Gregora30d0462009-05-26 14:40:08 +0000826 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000827#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000828#define ABSTRACT_TYPE(Name, Parent)
829#include "clang/AST/TypeNodes.def"
830 0 // Extra
831 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000832
Chris Lattner4eb445d2007-01-26 01:27:23 +0000833 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
834 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000835 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000836 }
837
Douglas Gregora30d0462009-05-26 14:40:08 +0000838 unsigned Idx = 0;
839 unsigned TotalBytes = 0;
840#define TYPE(Name, Parent) \
841 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000842 llvm::errs() << " " << counts[Idx] << " " << #Name \
843 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000844 TotalBytes += counts[Idx] * sizeof(Name##Type); \
845 ++Idx;
846#define ABSTRACT_TYPE(Name, Parent)
847#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000848
Chandler Carruth3c147a72011-07-04 05:32:14 +0000849 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
850
Douglas Gregor7454c562010-07-02 20:37:36 +0000851 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
853 << NumImplicitDefaultConstructors
854 << " implicit default constructors created\n";
855 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
856 << NumImplicitCopyConstructors
857 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000858 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000859 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
860 << NumImplicitMoveConstructors
861 << " implicit move constructors created\n";
862 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
863 << NumImplicitCopyAssignmentOperators
864 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000865 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000866 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
867 << NumImplicitMoveAssignmentOperators
868 << " implicit move assignment operators created\n";
869 llvm::errs() << NumImplicitDestructorsDeclared << "/"
870 << NumImplicitDestructors
871 << " implicit destructors created\n";
872
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000873 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000874 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000875 ExternalSource->PrintStats();
876 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000877
Douglas Gregor5b11d492010-07-25 17:53:33 +0000878 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000879}
880
Richard Smith42413142015-05-15 20:05:43 +0000881void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
882 bool NotifyListeners) {
883 if (NotifyListeners)
884 if (auto *Listener = getASTMutationListener())
885 Listener->RedefinedHiddenDefinition(ND, M);
886
887 if (getLangOpts().ModulesLocalVisibility)
888 MergedDefModules[ND].push_back(M);
889 else
890 ND->setHidden(false);
891}
892
893void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
894 auto It = MergedDefModules.find(ND);
895 if (It == MergedDefModules.end())
896 return;
897
898 auto &Merged = It->second;
899 llvm::DenseSet<Module*> Found;
900 for (Module *&M : Merged)
901 if (!Found.insert(M).second)
902 M = nullptr;
903 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
904}
905
Richard Smithf19e1272015-03-07 00:04:49 +0000906ExternCContextDecl *ASTContext::getExternCContextDecl() const {
907 if (!ExternCContext)
908 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
909
910 return ExternCContext;
911}
912
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000913BuiltinTemplateDecl *
914ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
915 const IdentifierInfo *II) const {
916 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
917 BuiltinTemplate->setImplicit();
918 TUDecl->addDecl(BuiltinTemplate);
919
920 return BuiltinTemplate;
921}
922
923BuiltinTemplateDecl *
924ASTContext::getMakeIntegerSeqDecl() const {
925 if (!MakeIntegerSeqDecl)
926 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
927 getMakeIntegerSeqName());
928 return MakeIntegerSeqDecl;
929}
930
Eric Fiselier6ad68552016-07-01 01:24:09 +0000931BuiltinTemplateDecl *
932ASTContext::getTypePackElementDecl() const {
933 if (!TypePackElementDecl)
934 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
935 getTypePackElementName());
936 return TypePackElementDecl;
937}
938
Alp Toker2dea15b2013-12-17 01:22:38 +0000939RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
940 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000941 SourceLocation Loc;
942 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000943 if (getLangOpts().CPlusPlus)
944 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
945 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000946 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000947 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
948 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000949 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000950 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
951 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000952 return NewDecl;
953}
954
955TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
956 StringRef Name) const {
957 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
958 TypedefDecl *NewDecl = TypedefDecl::Create(
959 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
960 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
961 NewDecl->setImplicit();
962 return NewDecl;
963}
964
Douglas Gregor801c99d2011-08-12 06:49:56 +0000965TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000966 if (!Int128Decl)
967 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000968 return Int128Decl;
969}
970
971TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000972 if (!UInt128Decl)
973 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000974 return UInt128Decl;
975}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000976
John McCall48f2d582009-10-23 23:03:21 +0000977void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000978 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000979 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000980 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000981}
982
Artem Belevichb5bc9232015-09-22 17:23:22 +0000983void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
984 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000985 assert((!this->Target || this->Target == &Target) &&
986 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000987 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000988
Douglas Gregore8bbc122011-09-02 00:18:52 +0000989 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000990 this->AuxTarget = AuxTarget;
991
Douglas Gregore8bbc122011-09-02 00:18:52 +0000992 ABI.reset(createCXXABI(Target));
993 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000994 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000995
Chris Lattner970e54e2006-11-12 00:37:36 +0000996 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000997 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000998
Chris Lattner970e54e2006-11-12 00:37:36 +0000999 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001000 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001001 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001002 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001003 InitBuiltinType(CharTy, BuiltinType::Char_S);
1004 else
1005 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001006 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001007 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1008 InitBuiltinType(ShortTy, BuiltinType::Short);
1009 InitBuiltinType(IntTy, BuiltinType::Int);
1010 InitBuiltinType(LongTy, BuiltinType::Long);
1011 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattner970e54e2006-11-12 00:37:36 +00001013 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001014 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1015 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1016 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1017 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1018 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattner970e54e2006-11-12 00:37:36 +00001020 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001021 InitBuiltinType(FloatTy, BuiltinType::Float);
1022 InitBuiltinType(DoubleTy, BuiltinType::Double);
1023 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001024
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001025 // GNU extension, __float128 for IEEE quadruple precision
1026 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1027
Chris Lattnerf122cef2009-04-30 02:43:43 +00001028 // GNU extension, 128-bit integers.
1029 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1030 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1031
Hans Wennborg0d81e012013-05-10 10:08:40 +00001032 // C++ 3.9.1p5
1033 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1034 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1035 else // -fshort-wchar makes wchar_t be unsigned.
1036 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1037 if (LangOpts.CPlusPlus && LangOpts.WChar)
1038 WideCharTy = WCharTy;
1039 else {
1040 // C99 (or C++ using -fno-wchar).
1041 WideCharTy = getFromTargetType(Target.getWCharType());
1042 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001043
James Molloy36365542012-05-04 10:55:22 +00001044 WIntTy = getFromTargetType(Target.getWIntType());
1045
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001046 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1047 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1048 else // C99
1049 Char16Ty = getFromTargetType(Target.getChar16Type());
1050
1051 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1052 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1053 else // C99
1054 Char32Ty = getFromTargetType(Target.getChar32Type());
1055
Douglas Gregor4619e432008-12-05 23:32:09 +00001056 // Placeholder type for type-dependent expressions whose type is
1057 // completely unknown. No code should ever check a type against
1058 // DependentTy and users should never see it; however, it is here to
1059 // help diagnose failures to properly check for type-dependent
1060 // expressions.
1061 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062
John McCall36e7fe32010-10-12 00:20:44 +00001063 // Placeholder type for functions.
1064 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1065
John McCall0009fcc2011-04-26 20:42:42 +00001066 // Placeholder type for bound members.
1067 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1068
John McCall526ab472011-10-25 17:37:35 +00001069 // Placeholder type for pseudo-objects.
1070 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1071
John McCall31996342011-04-07 08:22:57 +00001072 // "any" type; useful for debugger-like clients.
1073 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1074
John McCall8a6b59a2011-10-17 18:09:15 +00001075 // Placeholder type for unbridged ARC casts.
1076 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1077
Eli Friedman34866c72012-08-31 00:14:07 +00001078 // Placeholder type for builtin functions.
1079 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1080
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001081 // Placeholder type for OMP array sections.
1082 if (LangOpts.OpenMP)
1083 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1084
Chris Lattner970e54e2006-11-12 00:37:36 +00001085 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001086 FloatComplexTy = getComplexType(FloatTy);
1087 DoubleComplexTy = getComplexType(DoubleTy);
1088 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001089 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001090
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001091 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001092 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1093 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001094 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001095
Alexey Bader954ba212016-04-08 13:40:33 +00001096 if (LangOpts.OpenCL) {
1097#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1098 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001099#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001100
Guy Benyei61054192013-02-07 10:55:47 +00001101 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001102 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001103 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1104 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1105 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1106 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001107 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001108
1109 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001110 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1111 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001112
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001113 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001114
1115 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001116
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001117 // void * type
1118 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001119
1120 // nullptr type (C++0x 2.14.7)
1121 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001122
1123 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1124 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001125
1126 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001127 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001128}
1129
David Blaikie9c902b52011-09-25 23:23:43 +00001130DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001131 return SourceMgr.getDiagnostics();
1132}
1133
Douglas Gregor561eceb2010-08-30 16:49:28 +00001134AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1135 AttrVec *&Result = DeclAttrs[D];
1136 if (!Result) {
1137 void *Mem = Allocate(sizeof(AttrVec));
1138 Result = new (Mem) AttrVec;
1139 }
1140
1141 return *Result;
1142}
1143
1144/// \brief Erase the attributes corresponding to the given declaration.
1145void ASTContext::eraseDeclAttrs(const Decl *D) {
1146 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1147 if (Pos != DeclAttrs.end()) {
1148 Pos->second->~AttrVec();
1149 DeclAttrs.erase(Pos);
1150 }
1151}
1152
Larisse Voufo39a1e502013-08-06 01:03:05 +00001153// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001154MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001155ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001156 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001157 return getTemplateOrSpecializationInfo(Var)
1158 .dyn_cast<MemberSpecializationInfo *>();
1159}
1160
1161ASTContext::TemplateOrSpecializationInfo
1162ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1163 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1164 TemplateOrInstantiation.find(Var);
1165 if (Pos == TemplateOrInstantiation.end())
1166 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001167
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001168 return Pos->second;
1169}
1170
Mike Stump11289f42009-09-09 15:08:12 +00001171void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001172ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001173 TemplateSpecializationKind TSK,
1174 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001175 assert(Inst->isStaticDataMember() && "Not a static data member");
1176 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001177 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1178 Tmpl, TSK, PointOfInstantiation));
1179}
1180
1181void
1182ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1183 TemplateOrSpecializationInfo TSI) {
1184 assert(!TemplateOrInstantiation[Inst] &&
1185 "Already noted what the variable was instantiated from");
1186 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001187}
1188
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001189FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1190 const FunctionDecl *FD){
1191 assert(FD && "Specialization is 0");
1192 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001193 = ClassScopeSpecializationPattern.find(FD);
1194 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001195 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001196
1197 return Pos->second;
1198}
1199
1200void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1201 FunctionDecl *Pattern) {
1202 assert(FD && "Specialization is 0");
1203 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001204 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001205}
1206
John McCalle61f2ba2009-11-18 02:36:19 +00001207NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001208ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001209 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001210 = InstantiatedFromUsingDecl.find(UUD);
1211 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001212 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001213
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001214 return Pos->second;
1215}
1216
1217void
John McCallb96ec562009-12-04 22:46:56 +00001218ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1219 assert((isa<UsingDecl>(Pattern) ||
1220 isa<UnresolvedUsingValueDecl>(Pattern) ||
1221 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1222 "pattern decl is not a using decl");
1223 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1224 InstantiatedFromUsingDecl[Inst] = Pattern;
1225}
1226
1227UsingShadowDecl *
1228ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1229 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1230 = InstantiatedFromUsingShadowDecl.find(Inst);
1231 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001232 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001233
1234 return Pos->second;
1235}
1236
1237void
1238ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1239 UsingShadowDecl *Pattern) {
1240 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1241 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001242}
1243
Anders Carlsson5da84842009-09-01 04:26:58 +00001244FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1245 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1246 = InstantiatedFromUnnamedFieldDecl.find(Field);
1247 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001248 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001249
Anders Carlsson5da84842009-09-01 04:26:58 +00001250 return Pos->second;
1251}
1252
1253void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1254 FieldDecl *Tmpl) {
1255 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1256 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1257 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1258 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001259
Anders Carlsson5da84842009-09-01 04:26:58 +00001260 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1261}
1262
Douglas Gregor832940b2010-03-02 23:58:15 +00001263ASTContext::overridden_cxx_method_iterator
1264ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001265 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1266 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001267 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001268 return nullptr;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001269
Douglas Gregor832940b2010-03-02 23:58:15 +00001270 return Pos->second.begin();
1271}
1272
1273ASTContext::overridden_cxx_method_iterator
1274ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001275 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1276 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001277 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001278 return nullptr;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001279
Douglas Gregor832940b2010-03-02 23:58:15 +00001280 return Pos->second.end();
1281}
1282
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001283unsigned
1284ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001285 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1286 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001287 if (Pos == OverriddenMethods.end())
1288 return 0;
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001289
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001290 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001291}
1292
Douglas Gregor832940b2010-03-02 23:58:15 +00001293void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1294 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001295 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001296 OverriddenMethods[Method].push_back(Overridden);
1297}
1298
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001299void ASTContext::getOverriddenMethods(
1300 const NamedDecl *D,
1301 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001302 assert(D);
1303
1304 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001305 Overridden.append(overridden_methods_begin(CXXMethod),
1306 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001307 return;
1308 }
1309
1310 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1311 if (!Method)
1312 return;
1313
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001314 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1315 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001316 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001317}
1318
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001319void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1320 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1321 assert(!Import->isFromASTFile() && "Non-local import declaration");
1322 if (!FirstLocalImport) {
1323 FirstLocalImport = Import;
1324 LastLocalImport = Import;
1325 return;
1326 }
1327
1328 LastLocalImport->NextLocalImport = Import;
1329 LastLocalImport = Import;
1330}
1331
Chris Lattner53cfe802007-07-18 17:52:12 +00001332//===----------------------------------------------------------------------===//
1333// Type Sizing and Analysis
1334//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001335
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001336/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1337/// scalar floating point type.
1338const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001339 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001340 assert(BT && "Not a floating point type!");
1341 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001342 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001343 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001344 case BuiltinType::Float: return Target->getFloatFormat();
1345 case BuiltinType::Double: return Target->getDoubleFormat();
1346 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001347 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001348 }
1349}
1350
Rafael Espindola71eccb32013-08-08 19:53:46 +00001351CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001352 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001353
John McCall94268702010-10-08 18:24:19 +00001354 bool UseAlignAttrOnly = false;
1355 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1356 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001357
John McCall94268702010-10-08 18:24:19 +00001358 // __attribute__((aligned)) can increase or decrease alignment
1359 // *except* on a struct or struct member, where it only increases
1360 // alignment unless 'packed' is also specified.
1361 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001362 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001363 // ignore that possibility; Sema should diagnose it.
1364 if (isa<FieldDecl>(D)) {
1365 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1366 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1367 } else {
1368 UseAlignAttrOnly = true;
1369 }
1370 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001371 else if (isa<FieldDecl>(D))
1372 UseAlignAttrOnly =
1373 D->hasAttr<PackedAttr>() ||
1374 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001375
John McCall4e819612011-01-20 07:57:12 +00001376 // If we're using the align attribute only, just ignore everything
1377 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001378 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001379 // do nothing
1380
John McCall94268702010-10-08 18:24:19 +00001381 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001382 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001383 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001384 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001385 T = RT->getPointeeType();
1386 else
1387 T = getPointerType(RT->getPointeeType());
1388 }
Richard Smithf6d70302014-06-10 23:34:28 +00001389 QualType BaseT = getBaseElementType(T);
1390 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001391 // Adjust alignments of declarations with array type by the
1392 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001393 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001394 unsigned MinWidth = Target->getLargeArrayMinWidth();
1395 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001396 if (isa<VariableArrayType>(arrayType))
1397 Align = std::max(Align, Target->getLargeArrayAlign());
1398 else if (isa<ConstantArrayType>(arrayType) &&
1399 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1400 Align = std::max(Align, Target->getLargeArrayAlign());
1401 }
John McCall33ddac02011-01-19 10:06:00 +00001402 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001403 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001404 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001405 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001406 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1407 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001408 }
John McCall4e819612011-01-20 07:57:12 +00001409
1410 // Fields can be subject to extra alignment constraints, like if
1411 // the field is packed, the struct is packed, or the struct has a
1412 // a max-field-alignment constraint (#pragma pack). So calculate
1413 // the actual alignment of the field within the struct, and then
1414 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001415 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1416 const RecordDecl *Parent = Field->getParent();
1417 // We can only produce a sensible answer if the record is valid.
1418 if (!Parent->isInvalidDecl()) {
1419 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001420
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001421 // Start with the record's overall alignment.
1422 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001423
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001424 // Use the GCD of that and the offset within the record.
1425 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1426 if (Offset > 0) {
1427 // Alignment is always a power of 2, so the GCD will be a power of 2,
1428 // which means we get to do this crazy thing instead of Euclid's.
1429 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1430 if (LowBitOfOffset < FieldAlign)
1431 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1432 }
1433
1434 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001435 }
Charles Davis3fc51072010-02-23 04:52:00 +00001436 }
Chris Lattner68061312009-01-24 21:53:27 +00001437 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001438
Ken Dyckcc56c542011-01-15 18:38:59 +00001439 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001440}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001441
John McCallf1249922012-08-21 04:10:00 +00001442// getTypeInfoDataSizeInChars - Return the size of a type, in
1443// chars. If the type is a record, its data size is returned. This is
1444// the size of the memcpy that's performed when assigning this type
1445// using a trivial copy/move assignment operator.
1446std::pair<CharUnits, CharUnits>
1447ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1448 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1449
1450 // In C++, objects can sometimes be allocated into the tail padding
1451 // of a base-class subobject. We decide whether that's possible
1452 // during class layout, so here we can just trust the layout results.
1453 if (getLangOpts().CPlusPlus) {
1454 if (const RecordType *RT = T->getAs<RecordType>()) {
1455 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1456 sizeAndAlign.first = layout.getDataSize();
1457 }
1458 }
1459
1460 return sizeAndAlign;
1461}
1462
Richard Trieu04d2d942013-05-14 21:59:17 +00001463/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1464/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1465std::pair<CharUnits, CharUnits>
1466static getConstantArrayInfoInChars(const ASTContext &Context,
1467 const ConstantArrayType *CAT) {
1468 std::pair<CharUnits, CharUnits> EltInfo =
1469 Context.getTypeInfoInChars(CAT->getElementType());
1470 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001471 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1472 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001473 "Overflow in array type char size evaluation");
1474 uint64_t Width = EltInfo.first.getQuantity() * Size;
1475 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001476 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1477 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001478 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001479 return std::make_pair(CharUnits::fromQuantity(Width),
1480 CharUnits::fromQuantity(Align));
1481}
1482
John McCall87fe5d52010-05-20 01:18:31 +00001483std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001484ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001485 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1486 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001487 TypeInfo Info = getTypeInfo(T);
1488 return std::make_pair(toCharUnitsFromBits(Info.Width),
1489 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001490}
1491
1492std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001493ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001494 return getTypeInfoInChars(T.getTypePtr());
1495}
1496
David Majnemer34b57492014-07-30 01:30:47 +00001497bool ASTContext::isAlignmentRequired(const Type *T) const {
1498 return getTypeInfo(T).AlignIsRequired;
1499}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001500
David Majnemer34b57492014-07-30 01:30:47 +00001501bool ASTContext::isAlignmentRequired(QualType T) const {
1502 return isAlignmentRequired(T.getTypePtr());
1503}
1504
1505TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001506 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1507 if (I != MemoizedTypeInfo.end())
1508 return I->second;
1509
1510 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1511 TypeInfo TI = getTypeInfoImpl(T);
1512 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001513 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001514}
1515
1516/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1517/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001518///
1519/// FIXME: Pointers into different addr spaces could have different sizes and
1520/// alignment requirements: getPointerInfo should take an AddrSpace, this
1521/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001522TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1523 uint64_t Width = 0;
1524 unsigned Align = 8;
1525 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001526 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001527#define TYPE(Class, Base)
1528#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001529#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001530#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001531#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1532 case Type::Class: \
1533 assert(!T->isDependentType() && "should not see dependent types here"); \
1534 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001535#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001536 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001537
Chris Lattner355332d2007-07-13 22:27:08 +00001538 case Type::FunctionNoProto:
1539 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001540 // GCC extension: alignof(function) = 32 bits
1541 Width = 0;
1542 Align = 32;
1543 break;
1544
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001545 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001546 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001547 Width = 0;
1548 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1549 break;
1550
Steve Naroff5c131802007-08-30 01:06:46 +00001551 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001552 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001553
David Majnemer34b57492014-07-30 01:30:47 +00001554 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001555 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001556 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001557 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001558 Width = EltInfo.Width * Size;
1559 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001560 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1561 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001562 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001563 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001564 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001565 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001566 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001567 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001568 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1569 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001570 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001571 // If the alignment is not a power of 2, round up to the next power of 2.
1572 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001573 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001574 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001575 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001576 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001577 // Adjust the alignment based on the target max.
1578 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1579 if (TargetVectorAlign && TargetVectorAlign < Align)
1580 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001581 break;
1582 }
Chris Lattner647fb222007-07-18 18:26:58 +00001583
Chris Lattner7570e9c2008-03-08 08:52:55 +00001584 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001585 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001586 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001587 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001588 // GCC extension: alignof(void) = 8 bits.
1589 Width = 0;
1590 Align = 8;
1591 break;
1592
Chris Lattner6a4f7452007-12-19 19:23:28 +00001593 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001594 Width = Target->getBoolWidth();
1595 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001596 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001597 case BuiltinType::Char_S:
1598 case BuiltinType::Char_U:
1599 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001600 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001601 Width = Target->getCharWidth();
1602 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001603 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001604 case BuiltinType::WChar_S:
1605 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001606 Width = Target->getWCharWidth();
1607 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001608 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001609 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getChar16Width();
1611 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001612 break;
1613 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 Width = Target->getChar32Width();
1615 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001616 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001617 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001618 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001619 Width = Target->getShortWidth();
1620 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001621 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001622 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001623 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001624 Width = Target->getIntWidth();
1625 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001626 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001627 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001628 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001629 Width = Target->getLongWidth();
1630 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001631 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001632 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001633 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001634 Width = Target->getLongLongWidth();
1635 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001636 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001637 case BuiltinType::Int128:
1638 case BuiltinType::UInt128:
1639 Width = 128;
1640 Align = 128; // int128_t is 128-bit aligned on all targets.
1641 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001642 case BuiltinType::Half:
1643 Width = Target->getHalfWidth();
1644 Align = Target->getHalfAlign();
1645 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001646 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001647 Width = Target->getFloatWidth();
1648 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001649 break;
1650 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001651 Width = Target->getDoubleWidth();
1652 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001653 break;
1654 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001655 Width = Target->getLongDoubleWidth();
1656 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001657 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001658 case BuiltinType::Float128:
1659 Width = Target->getFloat128Width();
1660 Align = Target->getFloat128Align();
1661 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001662 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001663 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1664 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001665 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001666 case BuiltinType::ObjCId:
1667 case BuiltinType::ObjCClass:
1668 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001669 Width = Target->getPointerWidth(0);
1670 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001671 break;
Guy Benyei61054192013-02-07 10:55:47 +00001672 case BuiltinType::OCLSampler:
1673 // Samplers are modeled as integers.
1674 Width = Target->getIntWidth();
1675 Align = Target->getIntAlign();
1676 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001677 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001678 case BuiltinType::OCLClkEvent:
1679 case BuiltinType::OCLQueue:
1680 case BuiltinType::OCLNDRange:
1681 case BuiltinType::OCLReserveID:
Alexey Bader954ba212016-04-08 13:40:33 +00001682#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1683 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001684#include "clang/Basic/OpenCLImageTypes.def"
Alexey Bader954ba212016-04-08 13:40:33 +00001685
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001686 // Currently these types are pointers to opaque types.
1687 Width = Target->getPointerWidth(0);
1688 Align = Target->getPointerAlign(0);
1689 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001690 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001691 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001692 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001693 Width = Target->getPointerWidth(0);
1694 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001695 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001696 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001697 unsigned AS = getTargetAddressSpace(
1698 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001699 Width = Target->getPointerWidth(AS);
1700 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001701 break;
1702 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001703 case Type::LValueReference:
1704 case Type::RValueReference: {
1705 // alignof and sizeof should never enter this code path here, so we go
1706 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001707 unsigned AS = getTargetAddressSpace(
1708 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getPointerWidth(AS);
1710 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001711 break;
1712 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001713 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001714 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001715 Width = Target->getPointerWidth(AS);
1716 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001717 break;
1718 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001719 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001720 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001721 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001722 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001723 }
Chris Lattner647fb222007-07-18 18:26:58 +00001724 case Type::Complex: {
1725 // Complex types have the same alignment as their elements, but twice the
1726 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001727 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1728 Width = EltInfo.Width * 2;
1729 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001730 break;
1731 }
John McCall8b07ec22010-05-15 11:32:37 +00001732 case Type::ObjCObject:
1733 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001734 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001735 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001736 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001737 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001738 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001739 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001740 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001741 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001742 break;
1743 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001744 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001745 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001746 const TagType *TT = cast<TagType>(T);
1747
1748 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001749 Width = 8;
1750 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001751 break;
1752 }
Mike Stump11289f42009-09-09 15:08:12 +00001753
David Majnemer475b25e2015-01-21 10:54:38 +00001754 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1755 const EnumDecl *ED = ET->getDecl();
1756 TypeInfo Info =
1757 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1758 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1759 Info.Align = AttrAlign;
1760 Info.AlignIsRequired = true;
1761 }
1762 return Info;
1763 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001764
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001765 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001766 const RecordDecl *RD = RT->getDecl();
1767 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001768 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001769 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001770 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001771 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001772 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001773
Chris Lattner63d2b362009-10-22 05:17:15 +00001774 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001775 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1776 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001777
Richard Smith30482bc2011-02-20 03:19:35 +00001778 case Type::Auto: {
1779 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001780 assert(!A->getDeducedType().isNull() &&
1781 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001782 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001783 }
1784
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001785 case Type::Paren:
1786 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1787
Douglas Gregoref462e62009-04-30 17:32:17 +00001788 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001789 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001790 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001791 // If the typedef has an aligned attribute on it, it overrides any computed
1792 // alignment we have. This violates the GCC documentation (which says that
1793 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001794 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001795 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001796 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001797 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001798 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001799 AlignIsRequired = Info.AlignIsRequired;
1800 }
David Majnemer34b57492014-07-30 01:30:47 +00001801 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001802 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001803 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001804
Abramo Bagnara6150c882010-05-11 21:36:43 +00001805 case Type::Elaborated:
1806 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001807
John McCall81904512011-01-06 01:58:22 +00001808 case Type::Attributed:
1809 return getTypeInfo(
1810 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1811
Eli Friedman0dfb8892011-10-06 23:00:33 +00001812 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001813 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001814 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1815 Width = Info.Width;
1816 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001817
1818 // If the size of the type doesn't exceed the platform's max
1819 // atomic promotion width, make the size and alignment more
1820 // favorable to atomic operations:
1821 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1822 // Round the size up to a power of 2.
1823 if (!llvm::isPowerOf2_64(Width))
1824 Width = llvm::NextPowerOf2(Width);
1825
1826 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001827 Align = static_cast<unsigned>(Width);
1828 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001829 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001830 break;
1831
1832 case Type::Pipe: {
1833 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1834 Width = Info.Width;
1835 Align = Info.Align;
1836 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001837
Douglas Gregoref462e62009-04-30 17:32:17 +00001838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001840 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001841 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001842}
1843
Alexey Bataev00396512015-07-02 03:40:19 +00001844unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1845 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1846 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1847 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1848 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1849 getTargetInfo().getABI() == "elfv1-qpx" &&
1850 T->isSpecificBuiltinType(BuiltinType::Double))
1851 SimdAlign = 256;
1852 return SimdAlign;
1853}
1854
Ken Dyckcc56c542011-01-15 18:38:59 +00001855/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1856CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1857 return CharUnits::fromQuantity(BitSize / getCharWidth());
1858}
1859
Ken Dyckb0fcc592011-02-11 01:54:29 +00001860/// toBits - Convert a size in characters to a size in characters.
1861int64_t ASTContext::toBits(CharUnits CharSize) const {
1862 return CharSize.getQuantity() * getCharWidth();
1863}
1864
Ken Dyck8c89d592009-12-22 14:23:30 +00001865/// getTypeSizeInChars - Return the size of the specified type, in characters.
1866/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001867CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001868 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001869}
Jay Foad39c79802011-01-12 09:06:06 +00001870CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001871 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001872}
1873
Ken Dycka6046ab2010-01-26 17:25:18 +00001874/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001875/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001876CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001877 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001878}
Jay Foad39c79802011-01-12 09:06:06 +00001879CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001880 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001881}
1882
Chris Lattnera3402cd2009-01-27 18:08:34 +00001883/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1884/// type for the current target in bits. This can be different than the ABI
1885/// alignment in cases where it is beneficial for performance to overalign
1886/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001887unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001888 TypeInfo TI = getTypeInfo(T);
1889 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001890
David Majnemere1544562015-04-24 01:25:05 +00001891 T = T->getBaseElementTypeUnsafe();
1892
1893 // The preferred alignment of member pointers is that of a pointer.
1894 if (T->isMemberPointerType())
1895 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1896
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001897 if (!Target->allowsLargerPreferedTypeAlignment())
1898 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001899
Eli Friedman7ab09572009-05-25 21:27:19 +00001900 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001901 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001902 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001903 if (const EnumType *ET = T->getAs<EnumType>())
1904 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001905 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001906 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1907 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001908 // Don't increase the alignment if an alignment attribute was specified on a
1909 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001910 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001911 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001912
Chris Lattnera3402cd2009-01-27 18:08:34 +00001913 return ABIAlign;
1914}
1915
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001916/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1917/// for __attribute__((aligned)) on this target, to be used if no alignment
1918/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001919unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001920 return getTargetInfo().getDefaultAlignForAttributeAligned();
1921}
1922
Ulrich Weigandfa806422013-05-06 16:23:57 +00001923/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1924/// to a global variable of the specified type.
1925unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1926 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1927}
1928
1929/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1930/// should be given to a global variable of the specified type.
1931CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1932 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1933}
1934
David Majnemer08ef2ba2015-06-23 20:34:18 +00001935CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1936 CharUnits Offset = CharUnits::Zero();
1937 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1938 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1939 Offset += Layout->getBaseClassOffset(Base);
1940 Layout = &getASTRecordLayout(Base);
1941 }
1942 return Offset;
1943}
1944
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001945/// DeepCollectObjCIvars -
1946/// This routine first collects all declared, but not synthesized, ivars in
1947/// super class and then collects all ivars, including those synthesized for
1948/// current class. This routine is used for implementation of current class
1949/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001950///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001951void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1952 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001953 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001954 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1955 DeepCollectObjCIvars(SuperClass, false, Ivars);
1956 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001957 for (const auto *I : OI->ivars())
1958 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001959 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001960 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001961 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001962 Iv= Iv->getNextIvar())
1963 Ivars.push_back(Iv);
1964 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001965}
1966
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001967/// CollectInheritedProtocols - Collect all protocols in current class and
1968/// those inherited by it.
1969void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001970 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001971 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001972 // We can use protocol_iterator here instead of
1973 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001974 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001975 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001976 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001977
1978 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001979 for (const auto *Cat : OI->visible_categories())
1980 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001981
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001982 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1983 while (SD) {
1984 CollectInheritedProtocols(SD, Protocols);
1985 SD = SD->getSuperClass();
1986 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001987 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001988 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001989 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001990 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001991 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001992 // Insert the protocol.
1993 if (!Protocols.insert(
1994 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1995 return;
1996
1997 for (auto *Proto : OP->protocols())
1998 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001999 }
2000}
2001
Jay Foad39c79802011-01-12 09:06:06 +00002002unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002003 unsigned count = 0;
2004 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002005 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002006 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002007
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002008 // Count ivar defined in this class's implementation. This
2009 // includes synthesized ivars.
2010 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002011 count += ImplDecl->ivar_size();
2012
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002013 return count;
2014}
2015
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002016bool ASTContext::isSentinelNullExpr(const Expr *E) {
2017 if (!E)
2018 return false;
2019
2020 // nullptr_t is always treated as null.
2021 if (E->getType()->isNullPtrType()) return true;
2022
2023 if (E->getType()->isAnyPointerType() &&
2024 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2025 Expr::NPC_ValueDependentIsNull))
2026 return true;
2027
2028 // Unfortunately, __null has type 'int'.
2029 if (isa<GNUNullExpr>(E)) return true;
2030
2031 return false;
2032}
2033
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002034/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2035ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2036 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2037 I = ObjCImpls.find(D);
2038 if (I != ObjCImpls.end())
2039 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002040 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002041}
2042/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2043ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2044 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2045 I = ObjCImpls.find(D);
2046 if (I != ObjCImpls.end())
2047 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002048 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002049}
2050
2051/// \brief Set the implementation of ObjCInterfaceDecl.
2052void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2053 ObjCImplementationDecl *ImplD) {
2054 assert(IFaceD && ImplD && "Passed null params");
2055 ObjCImpls[IFaceD] = ImplD;
2056}
2057/// \brief Set the implementation of ObjCCategoryDecl.
2058void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2059 ObjCCategoryImplDecl *ImplD) {
2060 assert(CatD && ImplD && "Passed null params");
2061 ObjCImpls[CatD] = ImplD;
2062}
2063
Chandler Carruth21c90602015-12-30 03:24:14 +00002064const ObjCMethodDecl *
2065ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2066 return ObjCMethodRedecls.lookup(MD);
2067}
2068
2069void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2070 const ObjCMethodDecl *Redecl) {
2071 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2072 ObjCMethodRedecls[MD] = Redecl;
2073}
2074
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002075const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2076 const NamedDecl *ND) const {
2077 if (const ObjCInterfaceDecl *ID =
2078 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002079 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002080 if (const ObjCCategoryDecl *CD =
2081 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002082 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002083 if (const ObjCImplDecl *IMD =
2084 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002085 return IMD->getClassInterface();
2086
Craig Topper36250ad2014-05-12 05:36:57 +00002087 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002088}
2089
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002090/// \brief Get the copy initialization expression of VarDecl,or NULL if
2091/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002092Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002093 assert(VD && "Passed null params");
2094 assert(VD->hasAttr<BlocksAttr>() &&
2095 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002096 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002097 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002098 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002099}
2100
2101/// \brief Set the copy inialization expression of a block var decl.
2102void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2103 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002104 assert(VD->hasAttr<BlocksAttr>() &&
2105 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002106 BlockVarCopyInits[VD] = Init;
2107}
2108
John McCallbcd03502009-12-07 02:54:59 +00002109TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002110 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002111 if (!DataSize)
2112 DataSize = TypeLoc::getFullDataSizeForType(T);
2113 else
2114 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002115 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002116
John McCallbcd03502009-12-07 02:54:59 +00002117 TypeSourceInfo *TInfo =
2118 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2119 new (TInfo) TypeSourceInfo(T);
2120 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002121}
2122
John McCallbcd03502009-12-07 02:54:59 +00002123TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002124 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002125 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002126 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002127 return DI;
2128}
2129
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002130const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002131ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002132 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002133}
2134
2135const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002136ASTContext::getASTObjCImplementationLayout(
2137 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002138 return getObjCLayout(D->getClassInterface(), D);
2139}
2140
Chris Lattner983a8bb2007-07-13 22:13:22 +00002141//===----------------------------------------------------------------------===//
2142// Type creation/memoization methods
2143//===----------------------------------------------------------------------===//
2144
Jay Foad39c79802011-01-12 09:06:06 +00002145QualType
John McCall33ddac02011-01-19 10:06:00 +00002146ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2147 unsigned fastQuals = quals.getFastQualifiers();
2148 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002149
2150 // Check if we've already instantiated this type.
2151 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002152 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002153 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002154 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2155 assert(eq->getQualifiers() == quals);
2156 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002157 }
2158
John McCall33ddac02011-01-19 10:06:00 +00002159 // If the base type is not canonical, make the appropriate canonical type.
2160 QualType canon;
2161 if (!baseType->isCanonicalUnqualified()) {
2162 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002163 canonSplit.Quals.addConsistentQualifiers(quals);
2164 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002165
2166 // Re-find the insert position.
2167 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2168 }
2169
2170 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2171 ExtQualNodes.InsertNode(eq, insertPos);
2172 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002173}
2174
Jay Foad39c79802011-01-12 09:06:06 +00002175QualType
2176ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002177 QualType CanT = getCanonicalType(T);
2178 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002179 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002180
John McCall8ccfcb52009-09-24 19:53:00 +00002181 // If we are composing extended qualifiers together, merge together
2182 // into one ExtQuals node.
2183 QualifierCollector Quals;
2184 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002185
John McCall8ccfcb52009-09-24 19:53:00 +00002186 // If this type already has an address space specified, it cannot get
2187 // another one.
2188 assert(!Quals.hasAddressSpace() &&
2189 "Type cannot be in multiple addr spaces!");
2190 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002191
John McCall8ccfcb52009-09-24 19:53:00 +00002192 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002193}
2194
Chris Lattnerd60183d2009-02-18 22:53:11 +00002195QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002196 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002197 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002198 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002199 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002200
John McCall53fa7142010-12-24 02:08:15 +00002201 if (const PointerType *ptr = T->getAs<PointerType>()) {
2202 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002203 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002204 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2205 return getPointerType(ResultType);
2206 }
2207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
John McCall8ccfcb52009-09-24 19:53:00 +00002209 // If we are composing extended qualifiers together, merge together
2210 // into one ExtQuals node.
2211 QualifierCollector Quals;
2212 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002213
John McCall8ccfcb52009-09-24 19:53:00 +00002214 // If this type already has an ObjCGC specified, it cannot get
2215 // another one.
2216 assert(!Quals.hasObjCGCAttr() &&
2217 "Type cannot have multiple ObjCGCs!");
2218 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002219
John McCall8ccfcb52009-09-24 19:53:00 +00002220 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002221}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002222
John McCall4f5019e2010-12-19 02:44:49 +00002223const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2224 FunctionType::ExtInfo Info) {
2225 if (T->getExtInfo() == Info)
2226 return T;
2227
2228 QualType Result;
2229 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002230 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002231 } else {
2232 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2233 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2234 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002235 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002236 }
2237
2238 return cast<FunctionType>(Result.getTypePtr());
2239}
2240
Richard Smith2a7d4812013-05-04 07:00:32 +00002241void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2242 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002243 FD = FD->getMostRecentDecl();
2244 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002245 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2246 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002247 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002248 if (FunctionDecl *Next = FD->getPreviousDecl())
2249 FD = Next;
2250 else
2251 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002252 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002253 if (ASTMutationListener *L = getASTMutationListener())
2254 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002255}
2256
Richard Smith0b3a4622014-11-13 20:01:57 +00002257/// Get a function type and produce the equivalent function type with the
2258/// specified exception specification. Type sugar that can be present on a
2259/// declaration of a function with an exception specification is permitted
2260/// and preserved. Other type sugar (for instance, typedefs) is not.
2261static QualType getFunctionTypeWithExceptionSpec(
2262 ASTContext &Context, QualType Orig,
2263 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2264 // Might have some parens.
2265 if (auto *PT = dyn_cast<ParenType>(Orig))
2266 return Context.getParenType(
2267 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2268
2269 // Might have a calling-convention attribute.
2270 if (auto *AT = dyn_cast<AttributedType>(Orig))
2271 return Context.getAttributedType(
2272 AT->getAttrKind(),
2273 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2274 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2275 ESI));
2276
2277 // Anything else must be a function type. Rebuild it with the new exception
2278 // specification.
2279 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2280 return Context.getFunctionType(
2281 Proto->getReturnType(), Proto->getParamTypes(),
2282 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2283}
2284
2285void ASTContext::adjustExceptionSpec(
2286 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2287 bool AsWritten) {
2288 // Update the type.
2289 QualType Updated =
2290 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2291 FD->setType(Updated);
2292
2293 if (!AsWritten)
2294 return;
2295
2296 // Update the type in the type source information too.
2297 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2298 // If the type and the type-as-written differ, we may need to update
2299 // the type-as-written too.
2300 if (TSInfo->getType() != FD->getType())
2301 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2302
2303 // FIXME: When we get proper type location information for exceptions,
2304 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2305 // up the TypeSourceInfo;
2306 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2307 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2308 "TypeLoc size mismatch from updating exception specification");
2309 TSInfo->overrideType(Updated);
2310 }
2311}
2312
Chris Lattnerc6395932007-06-22 20:56:16 +00002313/// getComplexType - Return the uniqued reference to the type for a complex
2314/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002315QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002316 // Unique pointers, to guarantee there is only one pointer of a particular
2317 // structure.
2318 llvm::FoldingSetNodeID ID;
2319 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002320
Craig Topper36250ad2014-05-12 05:36:57 +00002321 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002322 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2323 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002324
Chris Lattnerc6395932007-06-22 20:56:16 +00002325 // If the pointee type isn't canonical, this won't be a canonical type either,
2326 // so fill in the canonical type field.
2327 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002328 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002329 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002330
Chris Lattnerc6395932007-06-22 20:56:16 +00002331 // Get the new insert position for the node we care about.
2332 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002333 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002334 }
John McCall90d1c2d2009-09-24 23:30:46 +00002335 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002336 Types.push_back(New);
2337 ComplexTypes.InsertNode(New, InsertPos);
2338 return QualType(New, 0);
2339}
2340
Chris Lattner970e54e2006-11-12 00:37:36 +00002341/// getPointerType - Return the uniqued reference to the type for a pointer to
2342/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002343QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002344 // Unique pointers, to guarantee there is only one pointer of a particular
2345 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002346 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002347 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002348
Craig Topper36250ad2014-05-12 05:36:57 +00002349 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002350 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002351 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002352
Chris Lattner7ccecb92006-11-12 08:50:50 +00002353 // If the pointee type isn't canonical, this won't be a canonical type either,
2354 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002355 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002356 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002357 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002358
Bob Wilsonc8541f22013-03-15 17:12:43 +00002359 // Get the new insert position for the node we care about.
2360 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002361 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002362 }
John McCall90d1c2d2009-09-24 23:30:46 +00002363 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002364 Types.push_back(New);
2365 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002366 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002367}
2368
Reid Kleckner0503a872013-12-05 01:23:43 +00002369QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2370 llvm::FoldingSetNodeID ID;
2371 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002372 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002373 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2374 if (AT)
2375 return QualType(AT, 0);
2376
2377 QualType Canonical = getCanonicalType(New);
2378
2379 // Get the new insert position for the node we care about.
2380 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002381 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002382
2383 AT = new (*this, TypeAlignment)
2384 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2385 Types.push_back(AT);
2386 AdjustedTypes.InsertNode(AT, InsertPos);
2387 return QualType(AT, 0);
2388}
2389
Reid Kleckner8a365022013-06-24 17:51:48 +00002390QualType ASTContext::getDecayedType(QualType T) const {
2391 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2392
Reid Kleckner8a365022013-06-24 17:51:48 +00002393 QualType Decayed;
2394
2395 // C99 6.7.5.3p7:
2396 // A declaration of a parameter as "array of type" shall be
2397 // adjusted to "qualified pointer to type", where the type
2398 // qualifiers (if any) are those specified within the [ and ] of
2399 // the array type derivation.
2400 if (T->isArrayType())
2401 Decayed = getArrayDecayedType(T);
2402
2403 // C99 6.7.5.3p8:
2404 // A declaration of a parameter as "function returning type"
2405 // shall be adjusted to "pointer to function returning type", as
2406 // in 6.3.2.1.
2407 if (T->isFunctionType())
2408 Decayed = getPointerType(T);
2409
Reid Kleckner0503a872013-12-05 01:23:43 +00002410 llvm::FoldingSetNodeID ID;
2411 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002412 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002413 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2414 if (AT)
2415 return QualType(AT, 0);
2416
Reid Kleckner8a365022013-06-24 17:51:48 +00002417 QualType Canonical = getCanonicalType(Decayed);
2418
2419 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002420 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002421 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002422
Reid Kleckner0503a872013-12-05 01:23:43 +00002423 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2424 Types.push_back(AT);
2425 AdjustedTypes.InsertNode(AT, InsertPos);
2426 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002427}
2428
Mike Stump11289f42009-09-09 15:08:12 +00002429/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002430/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002431QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002432 assert(T->isFunctionType() && "block of function types only");
2433 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002434 // structure.
2435 llvm::FoldingSetNodeID ID;
2436 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002437
Craig Topper36250ad2014-05-12 05:36:57 +00002438 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002439 if (BlockPointerType *PT =
2440 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2441 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002442
2443 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002444 // type either so fill in the canonical type field.
2445 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002446 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002447 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002448
Steve Naroffec33ed92008-08-27 16:04:49 +00002449 // Get the new insert position for the node we care about.
2450 BlockPointerType *NewIP =
2451 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002452 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002453 }
John McCall90d1c2d2009-09-24 23:30:46 +00002454 BlockPointerType *New
2455 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002456 Types.push_back(New);
2457 BlockPointerTypes.InsertNode(New, InsertPos);
2458 return QualType(New, 0);
2459}
2460
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002461/// getLValueReferenceType - Return the uniqued reference to the type for an
2462/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002463QualType
2464ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002465 assert(getCanonicalType(T) != OverloadTy &&
2466 "Unresolved overloaded function type");
2467
Bill Wendling3708c182007-05-27 10:15:43 +00002468 // Unique pointers, to guarantee there is only one pointer of a particular
2469 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002470 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002471 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002472
Craig Topper36250ad2014-05-12 05:36:57 +00002473 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002474 if (LValueReferenceType *RT =
2475 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002476 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002477
John McCallfc93cf92009-10-22 22:37:11 +00002478 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2479
Bill Wendling3708c182007-05-27 10:15:43 +00002480 // If the referencee type isn't canonical, this won't be a canonical type
2481 // either, so fill in the canonical type field.
2482 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002483 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2484 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2485 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002486
Bill Wendling3708c182007-05-27 10:15:43 +00002487 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002488 LValueReferenceType *NewIP =
2489 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002490 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002491 }
2492
John McCall90d1c2d2009-09-24 23:30:46 +00002493 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002494 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2495 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002496 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002497 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002498
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002499 return QualType(New, 0);
2500}
2501
2502/// getRValueReferenceType - Return the uniqued reference to the type for an
2503/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002504QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002505 // Unique pointers, to guarantee there is only one pointer of a particular
2506 // structure.
2507 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002508 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002509
Craig Topper36250ad2014-05-12 05:36:57 +00002510 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002511 if (RValueReferenceType *RT =
2512 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2513 return QualType(RT, 0);
2514
John McCallfc93cf92009-10-22 22:37:11 +00002515 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2516
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002517 // If the referencee type isn't canonical, this won't be a canonical type
2518 // either, so fill in the canonical type field.
2519 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002520 if (InnerRef || !T.isCanonical()) {
2521 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2522 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002523
2524 // Get the new insert position for the node we care about.
2525 RValueReferenceType *NewIP =
2526 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002527 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002528 }
2529
John McCall90d1c2d2009-09-24 23:30:46 +00002530 RValueReferenceType *New
2531 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002532 Types.push_back(New);
2533 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002534 return QualType(New, 0);
2535}
2536
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002537/// getMemberPointerType - Return the uniqued reference to the type for a
2538/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002539QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002540 // Unique pointers, to guarantee there is only one pointer of a particular
2541 // structure.
2542 llvm::FoldingSetNodeID ID;
2543 MemberPointerType::Profile(ID, T, Cls);
2544
Craig Topper36250ad2014-05-12 05:36:57 +00002545 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002546 if (MemberPointerType *PT =
2547 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2548 return QualType(PT, 0);
2549
2550 // If the pointee or class type isn't canonical, this won't be a canonical
2551 // type either, so fill in the canonical type field.
2552 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002553 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002554 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2555
2556 // Get the new insert position for the node we care about.
2557 MemberPointerType *NewIP =
2558 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002559 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002560 }
John McCall90d1c2d2009-09-24 23:30:46 +00002561 MemberPointerType *New
2562 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002563 Types.push_back(New);
2564 MemberPointerTypes.InsertNode(New, InsertPos);
2565 return QualType(New, 0);
2566}
2567
Mike Stump11289f42009-09-09 15:08:12 +00002568/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002569/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002570QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002571 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002572 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002573 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002574 assert((EltTy->isDependentType() ||
2575 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002576 "Constant array of VLAs is illegal!");
2577
Chris Lattnere2df3f92009-05-13 04:12:56 +00002578 // Convert the array size into a canonical width matching the pointer size for
2579 // the target.
2580 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002581 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002582 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002583
Chris Lattner23b7eb62007-06-15 23:05:46 +00002584 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002585 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002586
Craig Topper36250ad2014-05-12 05:36:57 +00002587 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002588 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002589 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002590 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002591
John McCall33ddac02011-01-19 10:06:00 +00002592 // If the element type isn't canonical or has qualifiers, this won't
2593 // be a canonical type either, so fill in the canonical type field.
2594 QualType Canon;
2595 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2596 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002597 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002598 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002599 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002600
Chris Lattner36f8e652007-01-27 08:31:04 +00002601 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002602 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002603 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002604 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002605 }
Mike Stump11289f42009-09-09 15:08:12 +00002606
John McCall90d1c2d2009-09-24 23:30:46 +00002607 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002608 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002609 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002610 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002611 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002612}
2613
John McCall06549462011-01-18 08:40:38 +00002614/// getVariableArrayDecayedType - Turns the given type, which may be
2615/// variably-modified, into the corresponding type with all the known
2616/// sizes replaced with [*].
2617QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2618 // Vastly most common case.
2619 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002620
John McCall06549462011-01-18 08:40:38 +00002621 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002622
John McCall06549462011-01-18 08:40:38 +00002623 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002624 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002625 switch (ty->getTypeClass()) {
2626#define TYPE(Class, Base)
2627#define ABSTRACT_TYPE(Class, Base)
2628#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2629#include "clang/AST/TypeNodes.def"
2630 llvm_unreachable("didn't desugar past all non-canonical types?");
2631
2632 // These types should never be variably-modified.
2633 case Type::Builtin:
2634 case Type::Complex:
2635 case Type::Vector:
2636 case Type::ExtVector:
2637 case Type::DependentSizedExtVector:
2638 case Type::ObjCObject:
2639 case Type::ObjCInterface:
2640 case Type::ObjCObjectPointer:
2641 case Type::Record:
2642 case Type::Enum:
2643 case Type::UnresolvedUsing:
2644 case Type::TypeOfExpr:
2645 case Type::TypeOf:
2646 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002647 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002648 case Type::DependentName:
2649 case Type::InjectedClassName:
2650 case Type::TemplateSpecialization:
2651 case Type::DependentTemplateSpecialization:
2652 case Type::TemplateTypeParm:
2653 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002654 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002655 case Type::PackExpansion:
2656 llvm_unreachable("type should never be variably-modified");
2657
2658 // These types can be variably-modified but should never need to
2659 // further decay.
2660 case Type::FunctionNoProto:
2661 case Type::FunctionProto:
2662 case Type::BlockPointer:
2663 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002664 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002665 return type;
2666
2667 // These types can be variably-modified. All these modifications
2668 // preserve structure except as noted by comments.
2669 // TODO: if we ever care about optimizing VLAs, there are no-op
2670 // optimizations available here.
2671 case Type::Pointer:
2672 result = getPointerType(getVariableArrayDecayedType(
2673 cast<PointerType>(ty)->getPointeeType()));
2674 break;
2675
2676 case Type::LValueReference: {
2677 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2678 result = getLValueReferenceType(
2679 getVariableArrayDecayedType(lv->getPointeeType()),
2680 lv->isSpelledAsLValue());
2681 break;
2682 }
2683
2684 case Type::RValueReference: {
2685 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2686 result = getRValueReferenceType(
2687 getVariableArrayDecayedType(lv->getPointeeType()));
2688 break;
2689 }
2690
Eli Friedman0dfb8892011-10-06 23:00:33 +00002691 case Type::Atomic: {
2692 const AtomicType *at = cast<AtomicType>(ty);
2693 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2694 break;
2695 }
2696
John McCall06549462011-01-18 08:40:38 +00002697 case Type::ConstantArray: {
2698 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2699 result = getConstantArrayType(
2700 getVariableArrayDecayedType(cat->getElementType()),
2701 cat->getSize(),
2702 cat->getSizeModifier(),
2703 cat->getIndexTypeCVRQualifiers());
2704 break;
2705 }
2706
2707 case Type::DependentSizedArray: {
2708 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2709 result = getDependentSizedArrayType(
2710 getVariableArrayDecayedType(dat->getElementType()),
2711 dat->getSizeExpr(),
2712 dat->getSizeModifier(),
2713 dat->getIndexTypeCVRQualifiers(),
2714 dat->getBracketsRange());
2715 break;
2716 }
2717
2718 // Turn incomplete types into [*] types.
2719 case Type::IncompleteArray: {
2720 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2721 result = getVariableArrayType(
2722 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002723 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002724 ArrayType::Normal,
2725 iat->getIndexTypeCVRQualifiers(),
2726 SourceRange());
2727 break;
2728 }
2729
2730 // Turn VLA types into [*] types.
2731 case Type::VariableArray: {
2732 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2733 result = getVariableArrayType(
2734 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002735 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002736 ArrayType::Star,
2737 vat->getIndexTypeCVRQualifiers(),
2738 vat->getBracketsRange());
2739 break;
2740 }
2741 }
2742
2743 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002744 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002745}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002746
Steve Naroffcadebd02007-08-30 18:14:25 +00002747/// getVariableArrayType - Returns a non-unique reference to the type for a
2748/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002749QualType ASTContext::getVariableArrayType(QualType EltTy,
2750 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002751 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002752 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002753 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002754 // Since we don't unique expressions, it isn't possible to unique VLA's
2755 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002756 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002757
John McCall33ddac02011-01-19 10:06:00 +00002758 // Be sure to pull qualifiers off the element type.
2759 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2760 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002761 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002762 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002763 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002764 }
2765
John McCall90d1c2d2009-09-24 23:30:46 +00002766 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002767 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002768
2769 VariableArrayTypes.push_back(New);
2770 Types.push_back(New);
2771 return QualType(New, 0);
2772}
2773
Douglas Gregor4619e432008-12-05 23:32:09 +00002774/// getDependentSizedArrayType - Returns a non-unique reference to
2775/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002776/// type.
John McCall33ddac02011-01-19 10:06:00 +00002777QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2778 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002779 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002780 unsigned elementTypeQuals,
2781 SourceRange brackets) const {
2782 assert((!numElements || numElements->isTypeDependent() ||
2783 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002784 "Size must be type- or value-dependent!");
2785
John McCall33ddac02011-01-19 10:06:00 +00002786 // Dependently-sized array types that do not have a specified number
2787 // of elements will have their sizes deduced from a dependent
2788 // initializer. We do no canonicalization here at all, which is okay
2789 // because they can't be used in most locations.
2790 if (!numElements) {
2791 DependentSizedArrayType *newType
2792 = new (*this, TypeAlignment)
2793 DependentSizedArrayType(*this, elementType, QualType(),
2794 numElements, ASM, elementTypeQuals,
2795 brackets);
2796 Types.push_back(newType);
2797 return QualType(newType, 0);
2798 }
2799
2800 // Otherwise, we actually build a new type every time, but we
2801 // also build a canonical type.
2802
2803 SplitQualType canonElementType = getCanonicalType(elementType).split();
2804
Craig Topper36250ad2014-05-12 05:36:57 +00002805 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002806 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002807 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002808 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002809 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002810
John McCall33ddac02011-01-19 10:06:00 +00002811 // Look for an existing type with these properties.
2812 DependentSizedArrayType *canonTy =
2813 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002814
John McCall33ddac02011-01-19 10:06:00 +00002815 // If we don't have one, build one.
2816 if (!canonTy) {
2817 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002818 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002819 QualType(), numElements, ASM, elementTypeQuals,
2820 brackets);
2821 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2822 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002823 }
2824
John McCall33ddac02011-01-19 10:06:00 +00002825 // Apply qualifiers from the element type to the array.
2826 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002827 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002828
David Majnemer16a74702015-07-24 05:54:19 +00002829 // If we didn't need extra canonicalization for the element type or the size
2830 // expression, then just use that as our result.
2831 if (QualType(canonElementType.Ty, 0) == elementType &&
2832 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002833 return canon;
2834
2835 // Otherwise, we need to build a type which follows the spelling
2836 // of the element type.
2837 DependentSizedArrayType *sugaredType
2838 = new (*this, TypeAlignment)
2839 DependentSizedArrayType(*this, elementType, canon, numElements,
2840 ASM, elementTypeQuals, brackets);
2841 Types.push_back(sugaredType);
2842 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002843}
2844
John McCall33ddac02011-01-19 10:06:00 +00002845QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002846 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002847 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002848 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002849 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002850
Craig Topper36250ad2014-05-12 05:36:57 +00002851 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002852 if (IncompleteArrayType *iat =
2853 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2854 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002855
2856 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002857 // either, so fill in the canonical type field. We also have to pull
2858 // qualifiers off the element type.
2859 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002860
John McCall33ddac02011-01-19 10:06:00 +00002861 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2862 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002863 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002864 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002865 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002866
2867 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002868 IncompleteArrayType *existing =
2869 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2870 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002871 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002872
John McCall33ddac02011-01-19 10:06:00 +00002873 IncompleteArrayType *newType = new (*this, TypeAlignment)
2874 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002875
John McCall33ddac02011-01-19 10:06:00 +00002876 IncompleteArrayTypes.InsertNode(newType, insertPos);
2877 Types.push_back(newType);
2878 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002879}
2880
Steve Naroff91fcddb2007-07-18 18:00:27 +00002881/// getVectorType - Return the unique reference to a vector type of
2882/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002883QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002884 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002885 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002886
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002887 // Check if we've already instantiated a vector of this type.
2888 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002889 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002890
Craig Topper36250ad2014-05-12 05:36:57 +00002891 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002892 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2893 return QualType(VTP, 0);
2894
2895 // If the element type isn't canonical, this won't be a canonical type either,
2896 // so fill in the canonical type field.
2897 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002898 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002899 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002900
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002901 // Get the new insert position for the node we care about.
2902 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002903 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002904 }
John McCall90d1c2d2009-09-24 23:30:46 +00002905 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002906 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002907 VectorTypes.InsertNode(New, InsertPos);
2908 Types.push_back(New);
2909 return QualType(New, 0);
2910}
2911
Nate Begemance4d7fc2008-04-18 23:10:10 +00002912/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002913/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002914QualType
2915ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002916 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002917
Steve Naroff91fcddb2007-07-18 18:00:27 +00002918 // Check if we've already instantiated a vector of this type.
2919 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002920 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002921 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002922 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002923 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2924 return QualType(VTP, 0);
2925
2926 // If the element type isn't canonical, this won't be a canonical type either,
2927 // so fill in the canonical type field.
2928 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002929 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002930 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002931
Steve Naroff91fcddb2007-07-18 18:00:27 +00002932 // Get the new insert position for the node we care about.
2933 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002935 }
John McCall90d1c2d2009-09-24 23:30:46 +00002936 ExtVectorType *New = new (*this, TypeAlignment)
2937 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002938 VectorTypes.InsertNode(New, InsertPos);
2939 Types.push_back(New);
2940 return QualType(New, 0);
2941}
2942
Jay Foad39c79802011-01-12 09:06:06 +00002943QualType
2944ASTContext::getDependentSizedExtVectorType(QualType vecType,
2945 Expr *SizeExpr,
2946 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002947 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002948 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002949 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002950
Craig Topper36250ad2014-05-12 05:36:57 +00002951 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002952 DependentSizedExtVectorType *Canon
2953 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2954 DependentSizedExtVectorType *New;
2955 if (Canon) {
2956 // We already have a canonical version of this array type; use it as
2957 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002958 New = new (*this, TypeAlignment)
2959 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2960 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002961 } else {
2962 QualType CanonVecTy = getCanonicalType(vecType);
2963 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002964 New = new (*this, TypeAlignment)
2965 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2966 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002967
2968 DependentSizedExtVectorType *CanonCheck
2969 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2970 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2971 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002972 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2973 } else {
2974 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2975 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002976 New = new (*this, TypeAlignment)
2977 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002978 }
2979 }
Mike Stump11289f42009-09-09 15:08:12 +00002980
Douglas Gregor758a8692009-06-17 21:51:59 +00002981 Types.push_back(New);
2982 return QualType(New, 0);
2983}
2984
John McCall18afab72016-03-01 00:49:02 +00002985/// \brief Determine whether \p T is canonical as the result type of a function.
2986static bool isCanonicalResultType(QualType T) {
2987 return T.isCanonical() &&
2988 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2989 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2990}
2991
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002992/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002993///
Jay Foad39c79802011-01-12 09:06:06 +00002994QualType
2995ASTContext::getFunctionNoProtoType(QualType ResultTy,
2996 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002997 // Unique functions, to guarantee there is only one function of a particular
2998 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002999 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003000 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003001
Craig Topper36250ad2014-05-12 05:36:57 +00003002 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003003 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003004 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003005 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003006
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003007 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003008 if (!isCanonicalResultType(ResultTy)) {
3009 Canonical =
3010 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003011
Chris Lattner47955de2007-01-27 08:37:20 +00003012 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003013 FunctionNoProtoType *NewIP =
3014 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003015 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003016 }
Mike Stump11289f42009-09-09 15:08:12 +00003017
John McCall90d1c2d2009-09-24 23:30:46 +00003018 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003019 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003020 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003021 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003022 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003023}
3024
Douglas Gregora602a152015-10-01 20:20:47 +00003025CanQualType
3026ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3027 CanQualType CanResultType = getCanonicalType(ResultType);
3028
3029 // Canonical result types do not have ARC lifetime qualifiers.
3030 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3031 Qualifiers Qs = CanResultType.getQualifiers();
3032 Qs.removeObjCLifetime();
3033 return CanQualType::CreateUnsafe(
3034 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3035 }
3036
3037 return CanResultType;
3038}
3039
Jay Foad39c79802011-01-12 09:06:06 +00003040QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003041ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003042 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003043 size_t NumArgs = ArgArray.size();
3044
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003045 // Unique functions, to guarantee there is only one function of a particular
3046 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003047 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003048 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3049 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003050
Craig Topper36250ad2014-05-12 05:36:57 +00003051 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003052 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003053 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003054 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003055
3056 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003057 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003058 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003059 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003060 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003061 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003062 isCanonical = false;
3063
3064 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003065 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003066 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003067 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003068 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003069 CanonicalArgs.reserve(NumArgs);
3070 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003071 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003072
John McCalldb40c7f2010-12-14 08:05:40 +00003073 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003074 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003075 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003076
Douglas Gregora602a152015-10-01 20:20:47 +00003077 // Adjust the canonical function result type.
3078 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003079 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003080
Chris Lattnerfd4de792007-01-27 01:15:32 +00003081 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003082 FunctionProtoType *NewIP =
3083 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003084 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003085 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003086
John McCall31168b02011-06-15 23:02:42 +00003087 // FunctionProtoType objects are allocated with extra bytes after
3088 // them for three variable size arrays at the end:
3089 // - parameter types
3090 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003091 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003092 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003093 // expression, or information used to resolve the exception
3094 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003095 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003096 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003097
Richard Smith8acb4282014-07-31 21:57:55 +00003098 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3099 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3100 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003101 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003102 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003103 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003104 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003105 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003106 }
John McCall18afab72016-03-01 00:49:02 +00003107
3108 // Put the ExtParameterInfos last. If all were equal, it would make
3109 // more sense to put these before the exception specification, because
3110 // it's much easier to skip past them compared to the elaborate switch
3111 // required to skip the exception specification. However, all is not
3112 // equal; ExtParameterInfos are used to model very uncommon features,
3113 // and it's better not to burden the more common paths.
3114 if (EPI.ExtParameterInfos) {
3115 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3116 }
John McCall31168b02011-06-15 23:02:42 +00003117
John McCalldb40c7f2010-12-14 08:05:40 +00003118 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003119 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003120 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003121 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003122 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003123 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003124}
Chris Lattneref51c202006-11-10 07:17:23 +00003125
Xiuli Pan9c14e282016-01-09 12:53:17 +00003126/// Return pipe type for the specified type.
3127QualType ASTContext::getPipeType(QualType T) const {
3128 llvm::FoldingSetNodeID ID;
3129 PipeType::Profile(ID, T);
3130
3131 void *InsertPos = 0;
3132 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3133 return QualType(PT, 0);
3134
3135 // If the pipe element type isn't canonical, this won't be a canonical type
3136 // either, so fill in the canonical type field.
3137 QualType Canonical;
3138 if (!T.isCanonical()) {
3139 Canonical = getPipeType(getCanonicalType(T));
3140
3141 // Get the new insert position for the node we care about.
3142 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3143 assert(!NewIP && "Shouldn't be in the map!");
3144 (void)NewIP;
3145 }
3146 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3147 Types.push_back(New);
3148 PipeTypes.InsertNode(New, InsertPos);
3149 return QualType(New, 0);
3150}
3151
John McCalle78aac42010-03-10 03:28:59 +00003152#ifndef NDEBUG
3153static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3154 if (!isa<CXXRecordDecl>(D)) return false;
3155 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3156 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3157 return true;
3158 if (RD->getDescribedClassTemplate() &&
3159 !isa<ClassTemplateSpecializationDecl>(RD))
3160 return true;
3161 return false;
3162}
3163#endif
3164
3165/// getInjectedClassNameType - Return the unique reference to the
3166/// injected class name type for the specified templated declaration.
3167QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003168 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003169 assert(NeedsInjectedClassNameType(Decl));
3170 if (Decl->TypeForDecl) {
3171 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003172 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003173 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3174 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3175 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3176 } else {
John McCall424cec92011-01-19 06:33:43 +00003177 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003178 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003179 Decl->TypeForDecl = newType;
3180 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003181 }
3182 return QualType(Decl->TypeForDecl, 0);
3183}
3184
Douglas Gregor83a586e2008-04-13 21:07:44 +00003185/// getTypeDeclType - Return the unique reference to the type for the
3186/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003187QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003188 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003189 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003190
Richard Smithdda56e42011-04-15 14:24:37 +00003191 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003192 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003193
John McCall96f0b5f2010-03-10 06:48:02 +00003194 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3195 "Template type parameter types are always available.");
3196
John McCall81e38502010-02-16 03:57:14 +00003197 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003198 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003199 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003200 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003201 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003202 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003203 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003204 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003205 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003206 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3207 Decl->TypeForDecl = newType;
3208 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003209 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003210 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003211
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003212 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003213}
3214
Chris Lattner32d920b2007-01-26 02:01:53 +00003215/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003216/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003217QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003218ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3219 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003220 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003221
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003222 if (Canonical.isNull())
3223 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003224 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003225 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003226 Decl->TypeForDecl = newType;
3227 Types.push_back(newType);
3228 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003229}
3230
Jay Foad39c79802011-01-12 09:06:06 +00003231QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003232 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3233
Douglas Gregorec9fd132012-01-14 16:38:05 +00003234 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003235 if (PrevDecl->TypeForDecl)
3236 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3237
John McCall424cec92011-01-19 06:33:43 +00003238 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3239 Decl->TypeForDecl = newType;
3240 Types.push_back(newType);
3241 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003242}
3243
Jay Foad39c79802011-01-12 09:06:06 +00003244QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003245 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3246
Douglas Gregorec9fd132012-01-14 16:38:05 +00003247 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003248 if (PrevDecl->TypeForDecl)
3249 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3250
John McCall424cec92011-01-19 06:33:43 +00003251 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3252 Decl->TypeForDecl = newType;
3253 Types.push_back(newType);
3254 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003255}
3256
John McCall81904512011-01-06 01:58:22 +00003257QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3258 QualType modifiedType,
3259 QualType equivalentType) {
3260 llvm::FoldingSetNodeID id;
3261 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3262
Craig Topper36250ad2014-05-12 05:36:57 +00003263 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003264 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3265 if (type) return QualType(type, 0);
3266
3267 QualType canon = getCanonicalType(equivalentType);
3268 type = new (*this, TypeAlignment)
3269 AttributedType(canon, attrKind, modifiedType, equivalentType);
3270
3271 Types.push_back(type);
3272 AttributedTypes.InsertNode(type, insertPos);
3273
3274 return QualType(type, 0);
3275}
3276
John McCallcebee162009-10-18 09:09:24 +00003277/// \brief Retrieve a substitution-result type.
3278QualType
3279ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003280 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003281 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003282 && "replacement types must always be canonical");
3283
3284 llvm::FoldingSetNodeID ID;
3285 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003286 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003287 SubstTemplateTypeParmType *SubstParm
3288 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3289
3290 if (!SubstParm) {
3291 SubstParm = new (*this, TypeAlignment)
3292 SubstTemplateTypeParmType(Parm, Replacement);
3293 Types.push_back(SubstParm);
3294 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3295 }
3296
3297 return QualType(SubstParm, 0);
3298}
3299
Douglas Gregorada4b792011-01-14 02:55:32 +00003300/// \brief Retrieve a
3301QualType ASTContext::getSubstTemplateTypeParmPackType(
3302 const TemplateTypeParmType *Parm,
3303 const TemplateArgument &ArgPack) {
3304#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003305 for (const auto &P : ArgPack.pack_elements()) {
3306 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3307 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003308 }
3309#endif
3310
3311 llvm::FoldingSetNodeID ID;
3312 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003313 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003314 if (SubstTemplateTypeParmPackType *SubstParm
3315 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3316 return QualType(SubstParm, 0);
3317
3318 QualType Canon;
3319 if (!Parm->isCanonicalUnqualified()) {
3320 Canon = getCanonicalType(QualType(Parm, 0));
3321 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3322 ArgPack);
3323 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3324 }
3325
3326 SubstTemplateTypeParmPackType *SubstParm
3327 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3328 ArgPack);
3329 Types.push_back(SubstParm);
3330 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3331 return QualType(SubstParm, 0);
3332}
3333
Douglas Gregoreff93e02009-02-05 23:33:38 +00003334/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003335/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003336/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003337QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003338 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003339 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003340 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003341 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003342 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003343 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003344 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3345
3346 if (TypeParm)
3347 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003348
Chandler Carruth08836322011-05-01 00:51:33 +00003349 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003350 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003351 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003352
3353 TemplateTypeParmType *TypeCheck
3354 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3355 assert(!TypeCheck && "Template type parameter canonical type broken");
3356 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003357 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003358 TypeParm = new (*this, TypeAlignment)
3359 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003360
3361 Types.push_back(TypeParm);
3362 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3363
3364 return QualType(TypeParm, 0);
3365}
3366
John McCalle78aac42010-03-10 03:28:59 +00003367TypeSourceInfo *
3368ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3369 SourceLocation NameLoc,
3370 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003371 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003372 assert(!Name.getAsDependentTemplateName() &&
3373 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003374 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003375
3376 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003377 TemplateSpecializationTypeLoc TL =
3378 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003379 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003380 TL.setTemplateNameLoc(NameLoc);
3381 TL.setLAngleLoc(Args.getLAngleLoc());
3382 TL.setRAngleLoc(Args.getRAngleLoc());
3383 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3384 TL.setArgLocInfo(i, Args[i].getLocInfo());
3385 return DI;
3386}
3387
Mike Stump11289f42009-09-09 15:08:12 +00003388QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003389ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003390 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003391 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003392 assert(!Template.getAsDependentTemplateName() &&
3393 "No dependent template names here!");
3394
John McCall6b51f282009-11-23 01:53:49 +00003395 unsigned NumArgs = Args.size();
3396
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003397 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003398 ArgVec.reserve(NumArgs);
3399 for (unsigned i = 0; i != NumArgs; ++i)
3400 ArgVec.push_back(Args[i].getArgument());
3401
John McCall2408e322010-04-27 00:57:59 +00003402 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003403 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003404}
3405
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003406#ifndef NDEBUG
3407static bool hasAnyPackExpansions(const TemplateArgument *Args,
3408 unsigned NumArgs) {
3409 for (unsigned I = 0; I != NumArgs; ++I)
3410 if (Args[I].isPackExpansion())
3411 return true;
3412
3413 return true;
3414}
3415#endif
3416
John McCall0ad16662009-10-29 08:12:44 +00003417QualType
3418ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003419 const TemplateArgument *Args,
3420 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003421 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003422 assert(!Template.getAsDependentTemplateName() &&
3423 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003424 // Look through qualified template names.
3425 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3426 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003427
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003428 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003429 Template.getAsTemplateDecl() &&
3430 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003431 QualType CanonType;
3432 if (!Underlying.isNull())
3433 CanonType = getCanonicalType(Underlying);
3434 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003435 // We can get here with an alias template when the specialization contains
3436 // a pack expansion that does not match up with a parameter pack.
3437 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3438 "Caller must compute aliased type");
3439 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003440 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3441 NumArgs);
3442 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003443
Douglas Gregora8e02e72009-07-28 23:00:59 +00003444 // Allocate the (non-canonical) template specialization type, but don't
3445 // try to unique it: these types typically have location information that
3446 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003447 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3448 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003449 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003450 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003451 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003452 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3453 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003454
Douglas Gregor8bf42052009-02-09 18:46:07 +00003455 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003456 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003457}
3458
Mike Stump11289f42009-09-09 15:08:12 +00003459QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003460ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3461 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003462 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003463 assert(!Template.getAsDependentTemplateName() &&
3464 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003465
Douglas Gregore29139c2011-03-03 17:04:51 +00003466 // Look through qualified template names.
3467 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3468 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003469
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003470 // Build the canonical template specialization type.
3471 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003472 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003473 CanonArgs.reserve(NumArgs);
3474 for (unsigned I = 0; I != NumArgs; ++I)
3475 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3476
3477 // Determine whether this canonical template specialization type already
3478 // exists.
3479 llvm::FoldingSetNodeID ID;
3480 TemplateSpecializationType::Profile(ID, CanonTemplate,
3481 CanonArgs.data(), NumArgs, *this);
3482
Craig Topper36250ad2014-05-12 05:36:57 +00003483 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003484 TemplateSpecializationType *Spec
3485 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3486
3487 if (!Spec) {
3488 // Allocate a new canonical template specialization type.
3489 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3490 sizeof(TemplateArgument) * NumArgs),
3491 TypeAlignment);
3492 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3493 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003494 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003495 Types.push_back(Spec);
3496 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3497 }
3498
3499 assert(Spec->isDependentType() &&
3500 "Non-dependent template-id type must have a canonical type");
3501 return QualType(Spec, 0);
3502}
3503
3504QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003505ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3506 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003507 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003508 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003509 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003510
Craig Topper36250ad2014-05-12 05:36:57 +00003511 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003512 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003513 if (T)
3514 return QualType(T, 0);
3515
Douglas Gregorc42075a2010-02-04 18:10:26 +00003516 QualType Canon = NamedType;
3517 if (!Canon.isCanonical()) {
3518 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003519 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3520 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003521 (void)CheckT;
3522 }
3523
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003524 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003525 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003526 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003527 return QualType(T, 0);
3528}
3529
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003530QualType
Jay Foad39c79802011-01-12 09:06:06 +00003531ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003532 llvm::FoldingSetNodeID ID;
3533 ParenType::Profile(ID, InnerType);
3534
Craig Topper36250ad2014-05-12 05:36:57 +00003535 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003536 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3537 if (T)
3538 return QualType(T, 0);
3539
3540 QualType Canon = InnerType;
3541 if (!Canon.isCanonical()) {
3542 Canon = getCanonicalType(InnerType);
3543 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3544 assert(!CheckT && "Paren canonical type broken");
3545 (void)CheckT;
3546 }
3547
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003548 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003549 Types.push_back(T);
3550 ParenTypes.InsertNode(T, InsertPos);
3551 return QualType(T, 0);
3552}
3553
Douglas Gregor02085352010-03-31 20:19:30 +00003554QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3555 NestedNameSpecifier *NNS,
3556 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003557 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003558 if (Canon.isNull()) {
3559 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003560 ElaboratedTypeKeyword CanonKeyword = Keyword;
3561 if (Keyword == ETK_None)
3562 CanonKeyword = ETK_Typename;
3563
3564 if (CanonNNS != NNS || CanonKeyword != Keyword)
3565 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003566 }
3567
3568 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003569 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003570
Craig Topper36250ad2014-05-12 05:36:57 +00003571 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003572 DependentNameType *T
3573 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003574 if (T)
3575 return QualType(T, 0);
3576
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003577 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003578 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003579 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003580 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003581}
3582
Mike Stump11289f42009-09-09 15:08:12 +00003583QualType
John McCallc392f372010-06-11 00:33:02 +00003584ASTContext::getDependentTemplateSpecializationType(
3585 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003586 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003587 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003588 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003589 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003590 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003591 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3592 ArgCopy.push_back(Args[I].getArgument());
3593 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3594 ArgCopy.size(),
3595 ArgCopy.data());
3596}
3597
3598QualType
3599ASTContext::getDependentTemplateSpecializationType(
3600 ElaboratedTypeKeyword Keyword,
3601 NestedNameSpecifier *NNS,
3602 const IdentifierInfo *Name,
3603 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003604 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003605 assert((!NNS || NNS->isDependent()) &&
3606 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003607
Douglas Gregorc42075a2010-02-04 18:10:26 +00003608 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003609 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3610 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003611
Craig Topper36250ad2014-05-12 05:36:57 +00003612 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003613 DependentTemplateSpecializationType *T
3614 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003615 if (T)
3616 return QualType(T, 0);
3617
John McCallc392f372010-06-11 00:33:02 +00003618 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003619
John McCallc392f372010-06-11 00:33:02 +00003620 ElaboratedTypeKeyword CanonKeyword = Keyword;
3621 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3622
3623 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003624 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003625 for (unsigned I = 0; I != NumArgs; ++I) {
3626 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3627 if (!CanonArgs[I].structurallyEquals(Args[I]))
3628 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003629 }
3630
John McCallc392f372010-06-11 00:33:02 +00003631 QualType Canon;
3632 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3633 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3634 Name, NumArgs,
3635 CanonArgs.data());
3636
3637 // Find the insert position again.
3638 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3639 }
3640
3641 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3642 sizeof(TemplateArgument) * NumArgs),
3643 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003644 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003645 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003646 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003647 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003648 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003649}
3650
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003651QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003652 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003653 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003654 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003655
3656 assert(Pattern->containsUnexpandedParameterPack() &&
3657 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003658 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003659 PackExpansionType *T
3660 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3661 if (T)
3662 return QualType(T, 0);
3663
3664 QualType Canon;
3665 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003666 Canon = getCanonicalType(Pattern);
3667 // The canonical type might not contain an unexpanded parameter pack, if it
3668 // contains an alias template specialization which ignores one of its
3669 // parameters.
3670 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003671 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003672
Richard Smith68eea502012-07-16 00:20:35 +00003673 // Find the insert position again, in case we inserted an element into
3674 // PackExpansionTypes and invalidated our insert position.
3675 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3676 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003677 }
3678
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003679 T = new (*this, TypeAlignment)
3680 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003681 Types.push_back(T);
3682 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003683 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003684}
3685
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003686/// CmpProtocolNames - Comparison predicate for sorting protocols
3687/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003688static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3689 ObjCProtocolDecl *const *RHS) {
3690 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003691}
3692
Craig Topper1f26d5b2016-01-03 19:43:23 +00003693static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3694 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003695
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003696 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3697 return false;
3698
Craig Topper1f26d5b2016-01-03 19:43:23 +00003699 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003700 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003701 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003702 return false;
3703 return true;
3704}
3705
Craig Topper6a8c1512015-10-22 01:56:18 +00003706static void
3707SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003708 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003709 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003710
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003711 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003712 for (ObjCProtocolDecl *&P : Protocols)
3713 P = P->getCanonicalDecl();
3714
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003715 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003716 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3717 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003718}
3719
John McCall8b07ec22010-05-15 11:32:37 +00003720QualType ASTContext::getObjCObjectType(QualType BaseType,
3721 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003722 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003723 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003724 llvm::makeArrayRef(Protocols, NumProtocols),
3725 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003726}
3727
3728QualType ASTContext::getObjCObjectType(
3729 QualType baseType,
3730 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003731 ArrayRef<ObjCProtocolDecl *> protocols,
3732 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003733 // If the base type is an interface and there aren't any protocols or
3734 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003735 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3736 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003737 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003738
3739 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003740 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003741 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003742 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003743 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3744 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003745
Douglas Gregore9d95f12015-07-07 03:57:35 +00003746 // Determine the type arguments to be used for canonicalization,
3747 // which may be explicitly specified here or written on the base
3748 // type.
3749 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3750 if (effectiveTypeArgs.empty()) {
3751 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3752 effectiveTypeArgs = baseObject->getTypeArgs();
3753 }
John McCallfc93cf92009-10-22 22:37:11 +00003754
Douglas Gregore9d95f12015-07-07 03:57:35 +00003755 // Build the canonical type, which has the canonical base type and a
3756 // sorted-and-uniqued list of protocols and the type arguments
3757 // canonicalized.
3758 QualType canonical;
3759 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3760 effectiveTypeArgs.end(),
3761 [&](QualType type) {
3762 return type.isCanonical();
3763 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003764 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003765 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3766 // Determine the canonical type arguments.
3767 ArrayRef<QualType> canonTypeArgs;
3768 SmallVector<QualType, 4> canonTypeArgsVec;
3769 if (!typeArgsAreCanonical) {
3770 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3771 for (auto typeArg : effectiveTypeArgs)
3772 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3773 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003774 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003775 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003776 }
3777
Douglas Gregore9d95f12015-07-07 03:57:35 +00003778 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3779 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3780 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003781 canonProtocolsVec.append(protocols.begin(), protocols.end());
3782 SortAndUniqueProtocols(canonProtocolsVec);
3783 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003784 } else {
3785 canonProtocols = protocols;
3786 }
3787
3788 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003789 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003790
John McCallfc93cf92009-10-22 22:37:11 +00003791 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003792 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3793 }
3794
Douglas Gregore9d95f12015-07-07 03:57:35 +00003795 unsigned size = sizeof(ObjCObjectTypeImpl);
3796 size += typeArgs.size() * sizeof(QualType);
3797 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3798 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003799 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003800 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3801 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003802
3803 Types.push_back(T);
3804 ObjCObjectTypes.InsertNode(T, InsertPos);
3805 return QualType(T, 0);
3806}
3807
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003808/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3809/// protocol list adopt all protocols in QT's qualified-id protocol
3810/// list.
3811bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3812 ObjCInterfaceDecl *IC) {
3813 if (!QT->isObjCQualifiedIdType())
3814 return false;
3815
3816 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3817 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003818 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003819 if (!IC->ClassImplementsProtocol(Proto, false))
3820 return false;
3821 }
3822 return true;
3823 }
3824 return false;
3825}
3826
3827/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3828/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3829/// of protocols.
3830bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3831 ObjCInterfaceDecl *IDecl) {
3832 if (!QT->isObjCQualifiedIdType())
3833 return false;
3834 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3835 if (!OPT)
3836 return false;
3837 if (!IDecl->hasDefinition())
3838 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003839 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3840 CollectInheritedProtocols(IDecl, InheritedProtocols);
3841 if (InheritedProtocols.empty())
3842 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003843 // Check that if every protocol in list of id<plist> conforms to a protcol
3844 // of IDecl's, then bridge casting is ok.
3845 bool Conforms = false;
3846 for (auto *Proto : OPT->quals()) {
3847 Conforms = false;
3848 for (auto *PI : InheritedProtocols) {
3849 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3850 Conforms = true;
3851 break;
3852 }
3853 }
3854 if (!Conforms)
3855 break;
3856 }
3857 if (Conforms)
3858 return true;
3859
Aaron Ballman83731462014-03-17 16:14:00 +00003860 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003861 // If both the right and left sides have qualifiers.
3862 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003863 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003864 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003865 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003866 break;
3867 }
3868 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003869 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003870 }
3871 return true;
3872}
3873
John McCall8b07ec22010-05-15 11:32:37 +00003874/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3875/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003876QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003877 llvm::FoldingSetNodeID ID;
3878 ObjCObjectPointerType::Profile(ID, ObjectT);
3879
Craig Topper36250ad2014-05-12 05:36:57 +00003880 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003881 if (ObjCObjectPointerType *QT =
3882 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3883 return QualType(QT, 0);
3884
3885 // Find the canonical object type.
3886 QualType Canonical;
3887 if (!ObjectT.isCanonical()) {
3888 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3889
3890 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003891 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3892 }
3893
Douglas Gregorf85bee62010-02-08 22:59:26 +00003894 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003895 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3896 ObjCObjectPointerType *QType =
3897 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003898
Steve Narofffb4330f2009-06-17 22:40:22 +00003899 Types.push_back(QType);
3900 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003901 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003902}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003903
Douglas Gregor1c283312010-08-11 12:19:30 +00003904/// getObjCInterfaceType - Return the unique reference to the type for the
3905/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003906QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3907 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003908 if (Decl->TypeForDecl)
3909 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003910
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003911 if (PrevDecl) {
3912 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3913 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3914 return QualType(PrevDecl->TypeForDecl, 0);
3915 }
3916
Douglas Gregor7671e532011-12-16 16:34:57 +00003917 // Prefer the definition, if there is one.
3918 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3919 Decl = Def;
3920
Douglas Gregor1c283312010-08-11 12:19:30 +00003921 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3922 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3923 Decl->TypeForDecl = T;
3924 Types.push_back(T);
3925 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003926}
3927
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003928/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3929/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003930/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003931/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003932/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003933QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003934 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003935 if (tofExpr->isTypeDependent()) {
3936 llvm::FoldingSetNodeID ID;
3937 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003938
Craig Topper36250ad2014-05-12 05:36:57 +00003939 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003940 DependentTypeOfExprType *Canon
3941 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3942 if (Canon) {
3943 // We already have a "canonical" version of an identical, dependent
3944 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003945 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003946 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003947 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003948 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003949 Canon
3950 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003951 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3952 toe = Canon;
3953 }
3954 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003955 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003956 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003957 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003958 Types.push_back(toe);
3959 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003960}
3961
Steve Naroffa773cd52007-08-01 18:02:17 +00003962/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003963/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003964/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003965/// an issue. This doesn't affect the type checker, since it operates
3966/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003967QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003968 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003969 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003970 Types.push_back(tot);
3971 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003972}
3973
Richard Smith8eb1d322014-06-05 20:13:13 +00003974/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3975/// nodes. This would never be helpful, since each such type has its own
3976/// expression, and would not give a significant memory saving, since there
3977/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003978QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003979 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003980
3981 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003982 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003983 // unique dependent type. Two such decltype-specifiers refer to the same
3984 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003985 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003986 llvm::FoldingSetNodeID ID;
3987 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003988
Craig Topper36250ad2014-05-12 05:36:57 +00003989 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003990 DependentDecltypeType *Canon
3991 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003992 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003993 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003994 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003995 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003996 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003997 dt = new (*this, TypeAlignment)
3998 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003999 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004000 dt = new (*this, TypeAlignment)
4001 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004002 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004003 Types.push_back(dt);
4004 return QualType(dt, 0);
4005}
4006
Alexis Hunte852b102011-05-24 22:41:36 +00004007/// getUnaryTransformationType - We don't unique these, since the memory
4008/// savings are minimal and these are rare.
4009QualType ASTContext::getUnaryTransformType(QualType BaseType,
4010 QualType UnderlyingType,
4011 UnaryTransformType::UTTKind Kind)
4012 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004013 UnaryTransformType *ut = nullptr;
4014
4015 if (BaseType->isDependentType()) {
4016 // Look in the folding set for an existing type.
4017 llvm::FoldingSetNodeID ID;
4018 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4019
4020 void *InsertPos = nullptr;
4021 DependentUnaryTransformType *Canon
4022 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4023
4024 if (!Canon) {
4025 // Build a new, canonical __underlying_type(type) type.
4026 Canon = new (*this, TypeAlignment)
4027 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4028 Kind);
4029 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4030 }
4031 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4032 QualType(), Kind,
4033 QualType(Canon, 0));
4034 } else {
4035 QualType CanonType = getCanonicalType(UnderlyingType);
4036 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4037 UnderlyingType, Kind,
4038 CanonType);
4039 }
4040 Types.push_back(ut);
4041 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004042}
4043
Richard Smith2a7d4812013-05-04 07:00:32 +00004044/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4045/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4046/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004047QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004048 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004049 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004050 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004051
Richard Smith2a7d4812013-05-04 07:00:32 +00004052 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004053 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004054 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004055 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004056 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4057 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004058
Richard Smith74aeef52013-04-26 16:15:35 +00004059 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004060 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004061 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004062 Types.push_back(AT);
4063 if (InsertPos)
4064 AutoTypes.InsertNode(AT, InsertPos);
4065 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004066}
4067
Eli Friedman0dfb8892011-10-06 23:00:33 +00004068/// getAtomicType - Return the uniqued reference to the atomic type for
4069/// the given value type.
4070QualType ASTContext::getAtomicType(QualType T) const {
4071 // Unique pointers, to guarantee there is only one pointer of a particular
4072 // structure.
4073 llvm::FoldingSetNodeID ID;
4074 AtomicType::Profile(ID, T);
4075
Craig Topper36250ad2014-05-12 05:36:57 +00004076 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004077 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4078 return QualType(AT, 0);
4079
4080 // If the atomic value type isn't canonical, this won't be a canonical type
4081 // either, so fill in the canonical type field.
4082 QualType Canonical;
4083 if (!T.isCanonical()) {
4084 Canonical = getAtomicType(getCanonicalType(T));
4085
4086 // Get the new insert position for the node we care about.
4087 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004088 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004089 }
4090 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4091 Types.push_back(New);
4092 AtomicTypes.InsertNode(New, InsertPos);
4093 return QualType(New, 0);
4094}
4095
Richard Smith02e85f32011-04-14 22:09:26 +00004096/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4097QualType ASTContext::getAutoDeductType() const {
4098 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004099 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004100 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004101 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004102 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004103 return AutoDeductTy;
4104}
4105
4106/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4107QualType ASTContext::getAutoRRefDeductType() const {
4108 if (AutoRRefDeductTy.isNull())
4109 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4110 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4111 return AutoRRefDeductTy;
4112}
4113
Chris Lattnerfb072462007-01-23 05:45:31 +00004114/// getTagDeclType - Return the unique reference to the type for the
4115/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004116QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004117 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004118 // FIXME: What is the design on getTagDeclType when it requires casting
4119 // away const? mutable?
4120 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004121}
4122
Mike Stump11289f42009-09-09 15:08:12 +00004123/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4124/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4125/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004126CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004127 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004128}
Chris Lattnerfb072462007-01-23 05:45:31 +00004129
Hans Wennborg27541db2011-10-27 08:29:09 +00004130/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4131CanQualType ASTContext::getIntMaxType() const {
4132 return getFromTargetType(Target->getIntMaxType());
4133}
4134
4135/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4136CanQualType ASTContext::getUIntMaxType() const {
4137 return getFromTargetType(Target->getUIntMaxType());
4138}
4139
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004140/// getSignedWCharType - Return the type of "signed wchar_t".
4141/// Used when in C++, as a GCC extension.
4142QualType ASTContext::getSignedWCharType() const {
4143 // FIXME: derive from "Target" ?
4144 return WCharTy;
4145}
4146
4147/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4148/// Used when in C++, as a GCC extension.
4149QualType ASTContext::getUnsignedWCharType() const {
4150 // FIXME: derive from "Target" ?
4151 return UnsignedIntTy;
4152}
4153
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004154QualType ASTContext::getIntPtrType() const {
4155 return getFromTargetType(Target->getIntPtrType());
4156}
4157
4158QualType ASTContext::getUIntPtrType() const {
4159 return getCorrespondingUnsignedType(getIntPtrType());
4160}
4161
Hans Wennborg27541db2011-10-27 08:29:09 +00004162/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004163/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4164QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004165 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004166}
4167
Eli Friedman4e91899e2012-11-27 02:58:24 +00004168/// \brief Return the unique type for "pid_t" defined in
4169/// <sys/types.h>. We need this to compute the correct type for vfork().
4170QualType ASTContext::getProcessIDType() const {
4171 return getFromTargetType(Target->getProcessIDType());
4172}
4173
Chris Lattnera21ad802008-04-02 05:18:44 +00004174//===----------------------------------------------------------------------===//
4175// Type Operators
4176//===----------------------------------------------------------------------===//
4177
Jay Foad39c79802011-01-12 09:06:06 +00004178CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004179 // Push qualifiers into arrays, and then discard any remaining
4180 // qualifiers.
4181 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004182 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004183 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004184 QualType Result;
4185 if (isa<ArrayType>(Ty)) {
4186 Result = getArrayDecayedType(QualType(Ty,0));
4187 } else if (isa<FunctionType>(Ty)) {
4188 Result = getPointerType(QualType(Ty, 0));
4189 } else {
4190 Result = QualType(Ty, 0);
4191 }
4192
4193 return CanQualType::CreateUnsafe(Result);
4194}
4195
John McCall6c9dd522011-01-18 07:41:22 +00004196QualType ASTContext::getUnqualifiedArrayType(QualType type,
4197 Qualifiers &quals) {
4198 SplitQualType splitType = type.getSplitUnqualifiedType();
4199
4200 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4201 // the unqualified desugared type and then drops it on the floor.
4202 // We then have to strip that sugar back off with
4203 // getUnqualifiedDesugaredType(), which is silly.
4204 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004205 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004206
4207 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004208 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004209 quals = splitType.Quals;
4210 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004211 }
4212
John McCall6c9dd522011-01-18 07:41:22 +00004213 // Otherwise, recurse on the array's element type.
4214 QualType elementType = AT->getElementType();
4215 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4216
4217 // If that didn't change the element type, AT has no qualifiers, so we
4218 // can just use the results in splitType.
4219 if (elementType == unqualElementType) {
4220 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004221 quals = splitType.Quals;
4222 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004223 }
4224
4225 // Otherwise, add in the qualifiers from the outermost type, then
4226 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004227 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004228
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004229 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004230 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004231 CAT->getSizeModifier(), 0);
4232 }
4233
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004234 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004235 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004236 }
4237
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004238 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004239 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004240 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004241 VAT->getSizeModifier(),
4242 VAT->getIndexTypeCVRQualifiers(),
4243 VAT->getBracketsRange());
4244 }
4245
4246 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004247 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004248 DSAT->getSizeModifier(), 0,
4249 SourceRange());
4250}
4251
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004252/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4253/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4254/// they point to and return true. If T1 and T2 aren't pointer types
4255/// or pointer-to-member types, or if they are not similar at this
4256/// level, returns false and leaves T1 and T2 unchanged. Top-level
4257/// qualifiers on T1 and T2 are ignored. This function will typically
4258/// be called in a loop that successively "unwraps" pointer and
4259/// pointer-to-member types to compare them at each level.
4260bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4261 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4262 *T2PtrType = T2->getAs<PointerType>();
4263 if (T1PtrType && T2PtrType) {
4264 T1 = T1PtrType->getPointeeType();
4265 T2 = T2PtrType->getPointeeType();
4266 return true;
4267 }
4268
4269 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4270 *T2MPType = T2->getAs<MemberPointerType>();
4271 if (T1MPType && T2MPType &&
4272 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4273 QualType(T2MPType->getClass(), 0))) {
4274 T1 = T1MPType->getPointeeType();
4275 T2 = T2MPType->getPointeeType();
4276 return true;
4277 }
4278
David Blaikiebbafb8a2012-03-11 07:00:24 +00004279 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004280 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4281 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4282 if (T1OPType && T2OPType) {
4283 T1 = T1OPType->getPointeeType();
4284 T2 = T2OPType->getPointeeType();
4285 return true;
4286 }
4287 }
4288
4289 // FIXME: Block pointers, too?
4290
4291 return false;
4292}
4293
Jay Foad39c79802011-01-12 09:06:06 +00004294DeclarationNameInfo
4295ASTContext::getNameForTemplate(TemplateName Name,
4296 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004297 switch (Name.getKind()) {
4298 case TemplateName::QualifiedTemplate:
4299 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004300 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004301 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4302 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004303
John McCalld9dfe3a2011-06-30 08:33:18 +00004304 case TemplateName::OverloadedTemplate: {
4305 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4306 // DNInfo work in progress: CHECKME: what about DNLoc?
4307 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4308 }
4309
4310 case TemplateName::DependentTemplate: {
4311 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004312 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004313 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004314 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4315 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004316 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004317 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4318 // DNInfo work in progress: FIXME: source locations?
4319 DeclarationNameLoc DNLoc;
4320 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4321 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4322 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004323 }
4324 }
4325
John McCalld9dfe3a2011-06-30 08:33:18 +00004326 case TemplateName::SubstTemplateTemplateParm: {
4327 SubstTemplateTemplateParmStorage *subst
4328 = Name.getAsSubstTemplateTemplateParm();
4329 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4330 NameLoc);
4331 }
4332
4333 case TemplateName::SubstTemplateTemplateParmPack: {
4334 SubstTemplateTemplateParmPackStorage *subst
4335 = Name.getAsSubstTemplateTemplateParmPack();
4336 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4337 NameLoc);
4338 }
4339 }
4340
4341 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004342}
4343
Jay Foad39c79802011-01-12 09:06:06 +00004344TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004345 switch (Name.getKind()) {
4346 case TemplateName::QualifiedTemplate:
4347 case TemplateName::Template: {
4348 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004349 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004350 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004351 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4352
4353 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004354 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004355 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004356
John McCalld9dfe3a2011-06-30 08:33:18 +00004357 case TemplateName::OverloadedTemplate:
4358 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004359
John McCalld9dfe3a2011-06-30 08:33:18 +00004360 case TemplateName::DependentTemplate: {
4361 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4362 assert(DTN && "Non-dependent template names must refer to template decls.");
4363 return DTN->CanonicalTemplateName;
4364 }
4365
4366 case TemplateName::SubstTemplateTemplateParm: {
4367 SubstTemplateTemplateParmStorage *subst
4368 = Name.getAsSubstTemplateTemplateParm();
4369 return getCanonicalTemplateName(subst->getReplacement());
4370 }
4371
4372 case TemplateName::SubstTemplateTemplateParmPack: {
4373 SubstTemplateTemplateParmPackStorage *subst
4374 = Name.getAsSubstTemplateTemplateParmPack();
4375 TemplateTemplateParmDecl *canonParameter
4376 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4377 TemplateArgument canonArgPack
4378 = getCanonicalTemplateArgument(subst->getArgumentPack());
4379 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4380 }
4381 }
4382
4383 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004384}
4385
Douglas Gregoradee3e32009-11-11 23:06:43 +00004386bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4387 X = getCanonicalTemplateName(X);
4388 Y = getCanonicalTemplateName(Y);
4389 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4390}
4391
Mike Stump11289f42009-09-09 15:08:12 +00004392TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004393ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004394 switch (Arg.getKind()) {
4395 case TemplateArgument::Null:
4396 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004397
Douglas Gregora8e02e72009-07-28 23:00:59 +00004398 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004399 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004400
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004401 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004402 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004403 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004404 }
Mike Stump11289f42009-09-09 15:08:12 +00004405
Eli Friedmanb826a002012-09-26 02:36:12 +00004406 case TemplateArgument::NullPtr:
4407 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4408 /*isNullPtr*/true);
4409
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004410 case TemplateArgument::Template:
4411 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004412
4413 case TemplateArgument::TemplateExpansion:
4414 return TemplateArgument(getCanonicalTemplateName(
4415 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004416 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004417
Douglas Gregora8e02e72009-07-28 23:00:59 +00004418 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004419 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004420
Douglas Gregora8e02e72009-07-28 23:00:59 +00004421 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004422 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004423
Douglas Gregora8e02e72009-07-28 23:00:59 +00004424 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004425 if (Arg.pack_size() == 0)
4426 return Arg;
4427
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004428 TemplateArgument *CanonArgs
4429 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004430 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004431 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004432 AEnd = Arg.pack_end();
4433 A != AEnd; (void)++A, ++Idx)
4434 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004435
Benjamin Kramercce63472015-08-05 09:40:22 +00004436 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004437 }
4438 }
4439
4440 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004441 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004442}
4443
Douglas Gregor333489b2009-03-27 23:10:48 +00004444NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004445ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004446 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004447 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004448
4449 switch (NNS->getKind()) {
4450 case NestedNameSpecifier::Identifier:
4451 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004452 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004453 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4454 NNS->getAsIdentifier());
4455
4456 case NestedNameSpecifier::Namespace:
4457 // A namespace is canonical; build a nested-name-specifier with
4458 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004459 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004460 NNS->getAsNamespace()->getOriginalNamespace());
4461
4462 case NestedNameSpecifier::NamespaceAlias:
4463 // A namespace is canonical; build a nested-name-specifier with
4464 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004465 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004466 NNS->getAsNamespaceAlias()->getNamespace()
4467 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004468
4469 case NestedNameSpecifier::TypeSpec:
4470 case NestedNameSpecifier::TypeSpecWithTemplate: {
4471 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004472
4473 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4474 // break it apart into its prefix and identifier, then reconsititute those
4475 // as the canonical nested-name-specifier. This is required to canonicalize
4476 // a dependent nested-name-specifier involving typedefs of dependent-name
4477 // types, e.g.,
4478 // typedef typename T::type T1;
4479 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004480 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4481 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004482 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004483
Eli Friedman5358a0a2012-03-03 04:09:56 +00004484 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4485 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4486 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004487 return NestedNameSpecifier::Create(*this, nullptr, false,
4488 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004489 }
4490
4491 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004492 case NestedNameSpecifier::Super:
4493 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004494 return NNS;
4495 }
4496
David Blaikie8a40f702012-01-17 06:56:22 +00004497 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004498}
4499
Jay Foad39c79802011-01-12 09:06:06 +00004500const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004501 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004502 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004503 // Handle the common positive case fast.
4504 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4505 return AT;
4506 }
Mike Stump11289f42009-09-09 15:08:12 +00004507
John McCall8ccfcb52009-09-24 19:53:00 +00004508 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004509 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004510 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004511
John McCall8ccfcb52009-09-24 19:53:00 +00004512 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004513 // implements C99 6.7.3p8: "If the specification of an array type includes
4514 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004515
Chris Lattner7adf0762008-08-04 07:31:14 +00004516 // If we get here, we either have type qualifiers on the type, or we have
4517 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004518 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004519
John McCall33ddac02011-01-19 10:06:00 +00004520 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004521 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004522
Chris Lattner7adf0762008-08-04 07:31:14 +00004523 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004524 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004525 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004526 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004527
Chris Lattner7adf0762008-08-04 07:31:14 +00004528 // Otherwise, we have an array and we have qualifiers on it. Push the
4529 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004530 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004531
Chris Lattner7adf0762008-08-04 07:31:14 +00004532 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4533 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4534 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004535 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004536 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4537 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4538 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004539 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004540
Mike Stump11289f42009-09-09 15:08:12 +00004541 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004542 = dyn_cast<DependentSizedArrayType>(ATy))
4543 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004544 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004545 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004546 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004547 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004548 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004549
Chris Lattner7adf0762008-08-04 07:31:14 +00004550 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004551 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004552 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004553 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004554 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004555 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004556}
4557
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004558QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004559 if (T->isArrayType() || T->isFunctionType())
4560 return getDecayedType(T);
4561 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004562}
4563
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004564QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004565 T = getVariableArrayDecayedType(T);
4566 T = getAdjustedParameterType(T);
4567 return T.getUnqualifiedType();
4568}
4569
David Majnemerd09a51c2015-03-03 01:50:05 +00004570QualType ASTContext::getExceptionObjectType(QualType T) const {
4571 // C++ [except.throw]p3:
4572 // A throw-expression initializes a temporary object, called the exception
4573 // object, the type of which is determined by removing any top-level
4574 // cv-qualifiers from the static type of the operand of throw and adjusting
4575 // the type from "array of T" or "function returning T" to "pointer to T"
4576 // or "pointer to function returning T", [...]
4577 T = getVariableArrayDecayedType(T);
4578 if (T->isArrayType() || T->isFunctionType())
4579 T = getDecayedType(T);
4580 return T.getUnqualifiedType();
4581}
4582
Chris Lattnera21ad802008-04-02 05:18:44 +00004583/// getArrayDecayedType - Return the properly qualified result of decaying the
4584/// specified array type to a pointer. This operation is non-trivial when
4585/// handling typedefs etc. The canonical type of "T" must be an array type,
4586/// this returns a pointer to a properly qualified element of the array.
4587///
4588/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004589QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004590 // Get the element type with 'getAsArrayType' so that we don't lose any
4591 // typedefs in the element type of the array. This also handles propagation
4592 // of type qualifiers from the array type into the element type if present
4593 // (C99 6.7.3p8).
4594 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4595 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004596
Chris Lattner7adf0762008-08-04 07:31:14 +00004597 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004598
4599 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004600 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004601}
4602
John McCall33ddac02011-01-19 10:06:00 +00004603QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4604 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004605}
4606
John McCall33ddac02011-01-19 10:06:00 +00004607QualType ASTContext::getBaseElementType(QualType type) const {
4608 Qualifiers qs;
4609 while (true) {
4610 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004611 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004612 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004613
John McCall33ddac02011-01-19 10:06:00 +00004614 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004615 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004616 }
Mike Stump11289f42009-09-09 15:08:12 +00004617
John McCall33ddac02011-01-19 10:06:00 +00004618 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004619}
4620
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004621/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004622uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004623ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4624 uint64_t ElementCount = 1;
4625 do {
4626 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004627 CA = dyn_cast_or_null<ConstantArrayType>(
4628 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004629 } while (CA);
4630 return ElementCount;
4631}
4632
Steve Naroff0af91202007-04-27 21:51:21 +00004633/// getFloatingRank - Return a relative rank for floating point types.
4634/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004635static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004636 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004637 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004638
John McCall9dd450b2009-09-21 23:43:11 +00004639 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4640 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004641 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004642 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004643 case BuiltinType::Float: return FloatRank;
4644 case BuiltinType::Double: return DoubleRank;
4645 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004646 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00004647 }
4648}
4649
Mike Stump11289f42009-09-09 15:08:12 +00004650/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4651/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004652/// 'typeDomain' is a real floating point or complex type.
4653/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004654QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4655 QualType Domain) const {
4656 FloatingRank EltRank = getFloatingRank(Size);
4657 if (Domain->isComplexType()) {
4658 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004659 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004660 case FloatRank: return FloatComplexTy;
4661 case DoubleRank: return DoubleComplexTy;
4662 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004663 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004664 }
Steve Naroff0af91202007-04-27 21:51:21 +00004665 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004666
4667 assert(Domain->isRealFloatingType() && "Unknown domain!");
4668 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004669 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004670 case FloatRank: return FloatTy;
4671 case DoubleRank: return DoubleTy;
4672 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004673 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00004674 }
David Blaikief47fa302012-01-17 02:30:50 +00004675 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004676}
4677
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004678/// getFloatingTypeOrder - Compare the rank of the two specified floating
4679/// point types, ignoring the domain of the type (i.e. 'double' ==
4680/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004681/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004682int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004683 FloatingRank LHSR = getFloatingRank(LHS);
4684 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004685
Chris Lattnerb90739d2008-04-06 23:38:49 +00004686 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004687 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004688 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004689 return 1;
4690 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004691}
4692
Chris Lattner76a00cf2008-04-06 22:59:24 +00004693/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4694/// routine will assert if passed a built-in type that isn't an integer or enum,
4695/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004696unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004697 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004698
Chris Lattner76a00cf2008-04-06 22:59:24 +00004699 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004700 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004701 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004702 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004703 case BuiltinType::Char_S:
4704 case BuiltinType::Char_U:
4705 case BuiltinType::SChar:
4706 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004707 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004708 case BuiltinType::Short:
4709 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004710 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004711 case BuiltinType::Int:
4712 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004713 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004714 case BuiltinType::Long:
4715 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004716 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004717 case BuiltinType::LongLong:
4718 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004719 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004720 case BuiltinType::Int128:
4721 case BuiltinType::UInt128:
4722 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004723 }
4724}
4725
Eli Friedman629ffb92009-08-20 04:21:42 +00004726/// \brief Whether this is a promotable bitfield reference according
4727/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4728///
4729/// \returns the type this bit-field will promote to, or NULL if no
4730/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004731QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004732 if (E->isTypeDependent() || E->isValueDependent())
4733 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004734
4735 // FIXME: We should not do this unless E->refersToBitField() is true. This
4736 // matters in C where getSourceBitField() will find bit-fields for various
4737 // cases where the source expression is not a bit-field designator.
4738
John McCalld25db7e2013-05-06 21:39:12 +00004739 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004740 if (!Field)
4741 return QualType();
4742
4743 QualType FT = Field->getType();
4744
Richard Smithcaf33902011-10-10 18:28:20 +00004745 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004746 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004747 // C++ [conv.prom]p5:
4748 // A prvalue for an integral bit-field can be converted to a prvalue of type
4749 // int if int can represent all the values of the bit-field; otherwise, it
4750 // can be converted to unsigned int if unsigned int can represent all the
4751 // values of the bit-field. If the bit-field is larger yet, no integral
4752 // promotion applies to it.
4753 // C11 6.3.1.1/2:
4754 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4755 // If an int can represent all values of the original type (as restricted by
4756 // the width, for a bit-field), the value is converted to an int; otherwise,
4757 // it is converted to an unsigned int.
4758 //
4759 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4760 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004761 if (BitWidth < IntSize)
4762 return IntTy;
4763
4764 if (BitWidth == IntSize)
4765 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4766
4767 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004768 // like the base type. GCC has some weird bugs in this area that we
4769 // deliberately do not follow (GCC follows a pre-standard resolution to
4770 // C's DR315 which treats bit-width as being part of the type, and this leaks
4771 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004772 return QualType();
4773}
4774
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004775/// getPromotedIntegerType - Returns the type that Promotable will
4776/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4777/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004778QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004779 assert(!Promotable.isNull());
4780 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004781 if (const EnumType *ET = Promotable->getAs<EnumType>())
4782 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004783
4784 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4785 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4786 // (3.9.1) can be converted to a prvalue of the first of the following
4787 // types that can represent all the values of its underlying type:
4788 // int, unsigned int, long int, unsigned long int, long long int, or
4789 // unsigned long long int [...]
4790 // FIXME: Is there some better way to compute this?
4791 if (BT->getKind() == BuiltinType::WChar_S ||
4792 BT->getKind() == BuiltinType::WChar_U ||
4793 BT->getKind() == BuiltinType::Char16 ||
4794 BT->getKind() == BuiltinType::Char32) {
4795 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4796 uint64_t FromSize = getTypeSize(BT);
4797 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4798 LongLongTy, UnsignedLongLongTy };
4799 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4800 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4801 if (FromSize < ToSize ||
4802 (FromSize == ToSize &&
4803 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4804 return PromoteTypes[Idx];
4805 }
4806 llvm_unreachable("char type should fit into long long");
4807 }
4808 }
4809
4810 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004811 if (Promotable->isSignedIntegerType())
4812 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004813 uint64_t PromotableSize = getIntWidth(Promotable);
4814 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004815 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4816 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4817}
4818
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004819/// \brief Recurses in pointer/array types until it finds an objc retainable
4820/// type and returns its ownership.
4821Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4822 while (!T.isNull()) {
4823 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4824 return T.getObjCLifetime();
4825 if (T->isArrayType())
4826 T = getBaseElementType(T);
4827 else if (const PointerType *PT = T->getAs<PointerType>())
4828 T = PT->getPointeeType();
4829 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004830 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004831 else
4832 break;
4833 }
4834
4835 return Qualifiers::OCL_None;
4836}
4837
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004838static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4839 // Incomplete enum types are not treated as integer types.
4840 // FIXME: In C++, enum types are never integer types.
4841 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4842 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004843 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004844}
4845
Mike Stump11289f42009-09-09 15:08:12 +00004846/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004847/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004848/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004849int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004850 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4851 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004852
4853 // Unwrap enums to their underlying type.
4854 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4855 LHSC = getIntegerTypeForEnum(ET);
4856 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4857 RHSC = getIntegerTypeForEnum(ET);
4858
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004859 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Chris Lattner76a00cf2008-04-06 22:59:24 +00004861 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4862 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004863
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004864 unsigned LHSRank = getIntegerRank(LHSC);
4865 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004866
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004867 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4868 if (LHSRank == RHSRank) return 0;
4869 return LHSRank > RHSRank ? 1 : -1;
4870 }
Mike Stump11289f42009-09-09 15:08:12 +00004871
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004872 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4873 if (LHSUnsigned) {
4874 // If the unsigned [LHS] type is larger, return it.
4875 if (LHSRank >= RHSRank)
4876 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004877
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004878 // If the signed type can represent all values of the unsigned type, it
4879 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004880 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004881 return -1;
4882 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004883
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004884 // If the unsigned [RHS] type is larger, return it.
4885 if (RHSRank >= LHSRank)
4886 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004887
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004888 // If the signed type can represent all values of the unsigned type, it
4889 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004890 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004891 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004892}
Anders Carlsson98f07902007-08-17 05:31:46 +00004893
Ben Langmuirf5416742016-02-04 00:55:24 +00004894TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004895 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004896 assert(!CFConstantStringTagDecl &&
4897 "tag and typedef should be initialized together");
4898 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4899 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004900
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004901 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00004902 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00004903
Anders Carlsson98f07902007-08-17 05:31:46 +00004904 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004905 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004906 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004907 // int flags;
4908 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004909 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00004910 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004911 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004912 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00004913 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004914 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004915 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00004916
Anders Carlsson98f07902007-08-17 05:31:46 +00004917 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004918 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004919 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004920 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00004921 SourceLocation(),
4922 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00004923 FieldTypes[i], /*TInfo=*/nullptr,
4924 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004925 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004926 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004927 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00004928 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004929 }
4930
Ben Langmuirf5416742016-02-04 00:55:24 +00004931 CFConstantStringTagDecl->completeDefinition();
4932 // This type is designed to be compatible with NSConstantString, but cannot
4933 // use the same name, since NSConstantString is an interface.
4934 auto tagType = getTagDeclType(CFConstantStringTagDecl);
4935 CFConstantStringTypeDecl =
4936 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00004937 }
Mike Stump11289f42009-09-09 15:08:12 +00004938
Quentin Colombet043406b2016-02-03 22:41:00 +00004939 return CFConstantStringTypeDecl;
4940}
4941
Ben Langmuirf5416742016-02-04 00:55:24 +00004942RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4943 if (!CFConstantStringTagDecl)
4944 getCFConstantStringDecl(); // Build the tag and the typedef.
4945 return CFConstantStringTagDecl;
4946}
4947
Quentin Colombet043406b2016-02-03 22:41:00 +00004948// getCFConstantStringType - Return the type used for constant CFStrings.
4949QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00004950 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00004951}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004952
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004953QualType ASTContext::getObjCSuperType() const {
4954 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004955 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004956 TUDecl->addDecl(ObjCSuperTypeDecl);
4957 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4958 }
4959 return ObjCSuperType;
4960}
4961
Douglas Gregor512b0772009-04-23 22:29:11 +00004962void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004963 const TypedefType *TD = T->getAs<TypedefType>();
4964 assert(TD && "Invalid CFConstantStringType");
4965 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
4966 auto TagType =
4967 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
4968 assert(TagType && "Invalid CFConstantStringType");
4969 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00004970}
4971
Jay Foad39c79802011-01-12 09:06:06 +00004972QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004973 if (BlockDescriptorType)
4974 return getTagDeclType(BlockDescriptorType);
4975
Alp Toker2dea15b2013-12-17 01:22:38 +00004976 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004977 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004978 RD = buildImplicitRecord("__block_descriptor");
4979 RD->startDefinition();
4980
Mike Stumpd0153282009-10-20 02:12:22 +00004981 QualType FieldTypes[] = {
4982 UnsignedLongTy,
4983 UnsignedLongTy,
4984 };
4985
Craig Topperd6d31ac2013-07-15 08:24:27 +00004986 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004987 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004988 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004989 };
4990
4991 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004992 FieldDecl *Field = FieldDecl::Create(
4993 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004994 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4995 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004996 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004997 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004998 }
4999
Alp Toker2dea15b2013-12-17 01:22:38 +00005000 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005001
Alp Toker2dea15b2013-12-17 01:22:38 +00005002 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005003
5004 return getTagDeclType(BlockDescriptorType);
5005}
5006
Jay Foad39c79802011-01-12 09:06:06 +00005007QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005008 if (BlockDescriptorExtendedType)
5009 return getTagDeclType(BlockDescriptorExtendedType);
5010
Alp Toker2dea15b2013-12-17 01:22:38 +00005011 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005012 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005013 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5014 RD->startDefinition();
5015
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005016 QualType FieldTypes[] = {
5017 UnsignedLongTy,
5018 UnsignedLongTy,
5019 getPointerType(VoidPtrTy),
5020 getPointerType(VoidPtrTy)
5021 };
5022
Craig Topperd6d31ac2013-07-15 08:24:27 +00005023 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005024 "reserved",
5025 "Size",
5026 "CopyFuncPtr",
5027 "DestroyFuncPtr"
5028 };
5029
5030 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005031 FieldDecl *Field = FieldDecl::Create(
5032 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005033 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5034 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005035 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005036 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005037 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005038 }
5039
Alp Toker2dea15b2013-12-17 01:22:38 +00005040 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005041
Alp Toker2dea15b2013-12-17 01:22:38 +00005042 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005043 return getTagDeclType(BlockDescriptorExtendedType);
5044}
5045
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005046/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5047/// requires copy/dispose. Note that this must match the logic
5048/// in buildByrefHelpers.
5049bool ASTContext::BlockRequiresCopying(QualType Ty,
5050 const VarDecl *D) {
5051 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5052 const Expr *copyExpr = getBlockVarCopyInits(D);
5053 if (!copyExpr && record->hasTrivialDestructor()) return false;
5054
Mike Stump94967902009-10-21 18:16:27 +00005055 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005056 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005057
5058 if (!Ty->isObjCRetainableType()) return false;
5059
5060 Qualifiers qs = Ty.getQualifiers();
5061
5062 // If we have lifetime, that dominates.
5063 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005064 switch (lifetime) {
5065 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5066
5067 // These are just bits as far as the runtime is concerned.
5068 case Qualifiers::OCL_ExplicitNone:
5069 case Qualifiers::OCL_Autoreleasing:
5070 return false;
5071
5072 // Tell the runtime that this is ARC __weak, called by the
5073 // byref routines.
5074 case Qualifiers::OCL_Weak:
5075 // ARC __strong __block variables need to be retained.
5076 case Qualifiers::OCL_Strong:
5077 return true;
5078 }
5079 llvm_unreachable("fell out of lifetime switch!");
5080 }
5081 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5082 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005083}
5084
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005085bool ASTContext::getByrefLifetime(QualType Ty,
5086 Qualifiers::ObjCLifetime &LifeTime,
5087 bool &HasByrefExtendedLayout) const {
5088
5089 if (!getLangOpts().ObjC1 ||
5090 getLangOpts().getGC() != LangOptions::NonGC)
5091 return false;
5092
5093 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005094 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005095 HasByrefExtendedLayout = true;
5096 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005097 } else if ((LifeTime = Ty.getObjCLifetime())) {
5098 // Honor the ARC qualifiers.
5099 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5100 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005101 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005102 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005103 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005104 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005105 return true;
5106}
5107
Douglas Gregorbab8a962011-09-08 01:46:34 +00005108TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5109 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005110 ObjCInstanceTypeDecl =
5111 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005112 return ObjCInstanceTypeDecl;
5113}
5114
Anders Carlsson18acd442007-10-29 06:33:42 +00005115// This returns true if a type has been typedefed to BOOL:
5116// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005117static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005118 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005119 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5120 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005121
Anders Carlssond8499822007-10-29 05:01:08 +00005122 return false;
5123}
5124
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005125/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005126/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005127CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005128 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5129 return CharUnits::Zero();
5130
Ken Dyck40775002010-01-11 17:06:35 +00005131 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005132
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005133 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005134 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005135 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005136 // Treat arrays as pointers, since that's how they're passed in.
5137 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005138 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005139 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005140}
5141
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005142bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005143 return getTargetInfo().getCXXABI().isMicrosoft() &&
5144 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005145 VD->getType()->isIntegralOrEnumerationType() &&
5146 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005147}
5148
Richard Smithd9b90092016-07-02 01:32:16 +00005149ASTContext::InlineVariableDefinitionKind
5150ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5151 if (!VD->isInline())
5152 return InlineVariableDefinitionKind::None;
5153
5154 // In almost all cases, it's a weak definition.
5155 auto *First = VD->getFirstDecl();
5156 if (!First->isConstexpr() || First->isInlineSpecified() ||
5157 !VD->isStaticDataMember())
5158 return InlineVariableDefinitionKind::Weak;
5159
5160 // If there's a file-context declaration in this translation unit, it's a
5161 // non-discardable definition.
5162 for (auto *D : VD->redecls())
5163 if (D->getLexicalDeclContext()->isFileContext())
5164 return InlineVariableDefinitionKind::Strong;
5165
5166 // If we've not seen one yet, we don't know.
5167 return InlineVariableDefinitionKind::WeakUnknown;
5168}
5169
Ken Dyck40775002010-01-11 17:06:35 +00005170static inline
5171std::string charUnitsToString(const CharUnits &CU) {
5172 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005173}
5174
John McCall351762c2011-02-07 10:33:21 +00005175/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005176/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005177std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5178 std::string S;
5179
David Chisnall950a9512009-11-17 19:33:30 +00005180 const BlockDecl *Decl = Expr->getBlockDecl();
5181 QualType BlockTy =
5182 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5183 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005184 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005185 getObjCEncodingForMethodParameter(
5186 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5187 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005188 else
Alp Toker314cc812014-01-25 16:55:45 +00005189 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005190 // Compute size of all parameters.
5191 // Start with computing size of a pointer in number of bytes.
5192 // FIXME: There might(should) be a better way of doing this computation!
5193 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005194 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5195 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005196 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005197 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005198 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005199 if (sz.isZero())
5200 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005201 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005202 ParmOffset += sz;
5203 }
5204 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005205 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005206 // Block pointer and offset.
5207 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005208
5209 // Argument types.
5210 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005211 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005212 QualType PType = PVDecl->getOriginalType();
5213 if (const ArrayType *AT =
5214 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5215 // Use array's original type only if it has known number of
5216 // elements.
5217 if (!isa<ConstantArrayType>(AT))
5218 PType = PVDecl->getType();
5219 } else if (PType->isFunctionType())
5220 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005221 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005222 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5223 S, true /*Extended*/);
5224 else
5225 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005226 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005227 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005228 }
John McCall351762c2011-02-07 10:33:21 +00005229
5230 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005231}
5232
Douglas Gregora9d84932011-05-27 01:19:52 +00005233bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005234 std::string& S) {
5235 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005236 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005237 CharUnits ParmOffset;
5238 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005239 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005240 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005241 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005242 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005243 continue;
5244
David Chisnall50e4eba2010-12-30 14:05:53 +00005245 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005246 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005247 ParmOffset += sz;
5248 }
5249 S += charUnitsToString(ParmOffset);
5250 ParmOffset = CharUnits::Zero();
5251
5252 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005253 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005254 QualType PType = PVDecl->getOriginalType();
5255 if (const ArrayType *AT =
5256 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5257 // Use array's original type only if it has known number of
5258 // elements.
5259 if (!isa<ConstantArrayType>(AT))
5260 PType = PVDecl->getType();
5261 } else if (PType->isFunctionType())
5262 PType = PVDecl->getType();
5263 getObjCEncodingForType(PType, S);
5264 S += charUnitsToString(ParmOffset);
5265 ParmOffset += getObjCEncodingTypeSize(PType);
5266 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005267
5268 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005269}
5270
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005271/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5272/// method parameter or return type. If Extended, include class names and
5273/// block object types.
5274void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5275 QualType T, std::string& S,
5276 bool Extended) const {
5277 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5278 getObjCEncodingForTypeQualifier(QT, S);
5279 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005280 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005281 true /*OutermostType*/,
5282 false /*EncodingProperty*/,
5283 false /*StructField*/,
5284 Extended /*EncodeBlockParameters*/,
5285 Extended /*EncodeClassNames*/);
5286}
5287
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005288/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005289/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005290bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005291 std::string& S,
5292 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005293 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005294 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005295 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5296 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005297 // Compute size of all parameters.
5298 // Start with computing size of a pointer in number of bytes.
5299 // FIXME: There might(should) be a better way of doing this computation!
5300 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005301 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005302 // The first two arguments (self and _cmd) are pointers; account for
5303 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005304 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005305 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005306 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005307 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005308 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005309 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005310 continue;
5311
Ken Dyck40775002010-01-11 17:06:35 +00005312 assert (sz.isPositive() &&
5313 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005314 ParmOffset += sz;
5315 }
Ken Dyck40775002010-01-11 17:06:35 +00005316 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005317 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005318 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005319
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005320 // Argument types.
5321 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005322 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005323 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005324 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005325 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005326 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005327 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5328 // Use array's original type only if it has known number of
5329 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005330 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005331 PType = PVDecl->getType();
5332 } else if (PType->isFunctionType())
5333 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005334 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5335 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005336 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005337 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005338 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005339
5340 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005341}
5342
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005343ObjCPropertyImplDecl *
5344ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5345 const ObjCPropertyDecl *PD,
5346 const Decl *Container) const {
5347 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005348 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005349 if (const ObjCCategoryImplDecl *CID =
5350 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005351 for (auto *PID : CID->property_impls())
5352 if (PID->getPropertyDecl() == PD)
5353 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005354 } else {
5355 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5356 for (auto *PID : OID->property_impls())
5357 if (PID->getPropertyDecl() == PD)
5358 return PID;
5359 }
5360 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005361}
5362
Daniel Dunbar4932b362008-08-28 04:38:10 +00005363/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005364/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005365/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5366/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005367/// Property attributes are stored as a comma-delimited C string. The simple
5368/// attributes readonly and bycopy are encoded as single characters. The
5369/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5370/// encoded as single characters, followed by an identifier. Property types
5371/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005372/// these attributes are defined by the following enumeration:
5373/// @code
5374/// enum PropertyAttributes {
5375/// kPropertyReadOnly = 'R', // property is read-only.
5376/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5377/// kPropertyByref = '&', // property is a reference to the value last assigned
5378/// kPropertyDynamic = 'D', // property is dynamic
5379/// kPropertyGetter = 'G', // followed by getter selector name
5380/// kPropertySetter = 'S', // followed by setter selector name
5381/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005382/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005383/// kPropertyWeak = 'W' // 'weak' property
5384/// kPropertyStrong = 'P' // property GC'able
5385/// kPropertyNonAtomic = 'N' // property non-atomic
5386/// };
5387/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005388void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005389 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005390 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005391 // Collect information from the property implementation decl(s).
5392 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005393 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005394
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005395 if (ObjCPropertyImplDecl *PropertyImpDecl =
5396 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5397 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5398 Dynamic = true;
5399 else
5400 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005401 }
5402
5403 // FIXME: This is not very efficient.
5404 S = "T";
5405
5406 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005407 // GCC has some special rules regarding encoding of properties which
5408 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005409 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005410
5411 if (PD->isReadOnly()) {
5412 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005413 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5414 S += ",C";
5415 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5416 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005417 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5418 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005419 } else {
5420 switch (PD->getSetterKind()) {
5421 case ObjCPropertyDecl::Assign: break;
5422 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005423 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005424 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005425 }
5426 }
5427
5428 // It really isn't clear at all what this means, since properties
5429 // are "dynamic by default".
5430 if (Dynamic)
5431 S += ",D";
5432
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005433 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5434 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005435
Daniel Dunbar4932b362008-08-28 04:38:10 +00005436 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5437 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005438 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005439 }
5440
5441 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5442 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005443 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005444 }
5445
5446 if (SynthesizePID) {
5447 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5448 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005449 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005450 }
5451
5452 // FIXME: OBJCGC: weak & strong
5453}
5454
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005455/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005456/// Another legacy compatibility encoding: 32-bit longs are encoded as
5457/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005458/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5459///
5460void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005461 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005462 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005463 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005464 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005465 else
Jay Foad39c79802011-01-12 09:06:06 +00005466 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005467 PointeeTy = IntTy;
5468 }
5469 }
5470}
5471
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005472void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005473 const FieldDecl *Field,
5474 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005475 // We follow the behavior of gcc, expanding structures which are
5476 // directly pointed to, and expanding embedded structures. Note that
5477 // these rules are sufficient to prevent recursive encoding of the
5478 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005479 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005480 true /* outermost type */, false, false,
5481 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005482}
5483
Joe Groff98ac7d22014-07-07 22:25:15 +00005484void ASTContext::getObjCEncodingForPropertyType(QualType T,
5485 std::string& S) const {
5486 // Encode result type.
5487 // GCC has some special rules regarding encoding of properties which
5488 // closely resembles encoding of ivars.
5489 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5490 true /* outermost type */,
5491 true /* encoding property */);
5492}
5493
John McCall393a78d2012-12-20 02:45:14 +00005494static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5495 BuiltinType::Kind kind) {
5496 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005497 case BuiltinType::Void: return 'v';
5498 case BuiltinType::Bool: return 'B';
5499 case BuiltinType::Char_U:
5500 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005501 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005502 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005503 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005504 case BuiltinType::UInt: return 'I';
5505 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005506 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005507 case BuiltinType::UInt128: return 'T';
5508 case BuiltinType::ULongLong: return 'Q';
5509 case BuiltinType::Char_S:
5510 case BuiltinType::SChar: return 'c';
5511 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005512 case BuiltinType::WChar_S:
5513 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005514 case BuiltinType::Int: return 'i';
5515 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005516 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005517 case BuiltinType::LongLong: return 'q';
5518 case BuiltinType::Int128: return 't';
5519 case BuiltinType::Float: return 'f';
5520 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005521 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005522 case BuiltinType::NullPtr: return '*'; // like char*
5523
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005524 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005525 case BuiltinType::Half:
5526 // FIXME: potentially need @encodes for these!
5527 return ' ';
5528
5529 case BuiltinType::ObjCId:
5530 case BuiltinType::ObjCClass:
5531 case BuiltinType::ObjCSel:
5532 llvm_unreachable("@encoding ObjC primitive type");
5533
5534 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005535#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5536 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005537#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005538 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005539 case BuiltinType::OCLClkEvent:
5540 case BuiltinType::OCLQueue:
5541 case BuiltinType::OCLNDRange:
5542 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005543 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005544 case BuiltinType::Dependent:
5545#define BUILTIN_TYPE(KIND, ID)
5546#define PLACEHOLDER_TYPE(KIND, ID) \
5547 case BuiltinType::KIND:
5548#include "clang/AST/BuiltinTypes.def"
5549 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005550 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005551 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005552}
5553
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005554static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5555 EnumDecl *Enum = ET->getDecl();
5556
5557 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5558 if (!Enum->isFixed())
5559 return 'i';
5560
5561 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005562 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5563 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005564}
5565
Jay Foad39c79802011-01-12 09:06:06 +00005566static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005567 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005568 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005569 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005570 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5571 // The GNU runtime requires more information; bitfields are encoded as b,
5572 // then the offset (in bits) of the first element, then the type of the
5573 // bitfield, then the size in bits. For example, in this structure:
5574 //
5575 // struct
5576 // {
5577 // int integer;
5578 // int flags:2;
5579 // };
5580 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5581 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5582 // information is not especially sensible, but we're stuck with it for
5583 // compatibility with GCC, although providing it breaks anything that
5584 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005585 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005586 const RecordDecl *RD = FD->getParent();
5587 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005588 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005589 if (const EnumType *ET = T->getAs<EnumType>())
5590 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005591 else {
5592 const BuiltinType *BT = T->castAs<BuiltinType>();
5593 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5594 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005595 }
Richard Smithcaf33902011-10-10 18:28:20 +00005596 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005597}
5598
Daniel Dunbar07d07852009-10-18 21:17:35 +00005599// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005600void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5601 bool ExpandPointedToStructures,
5602 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005603 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005604 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005605 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005606 bool StructField,
5607 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005608 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005609 bool EncodePointerToObjCTypedef,
5610 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005611 CanQualType CT = getCanonicalType(T);
5612 switch (CT->getTypeClass()) {
5613 case Type::Builtin:
5614 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005615 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005616 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005617 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5618 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5619 else
5620 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005621 return;
Mike Stump11289f42009-09-09 15:08:12 +00005622
John McCall393a78d2012-12-20 02:45:14 +00005623 case Type::Complex: {
5624 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005625 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005626 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005627 return;
5628 }
John McCall393a78d2012-12-20 02:45:14 +00005629
5630 case Type::Atomic: {
5631 const AtomicType *AT = T->castAs<AtomicType>();
5632 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005633 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005634 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005635 }
John McCall393a78d2012-12-20 02:45:14 +00005636
5637 // encoding for pointer or reference types.
5638 case Type::Pointer:
5639 case Type::LValueReference:
5640 case Type::RValueReference: {
5641 QualType PointeeTy;
5642 if (isa<PointerType>(CT)) {
5643 const PointerType *PT = T->castAs<PointerType>();
5644 if (PT->isObjCSelType()) {
5645 S += ':';
5646 return;
5647 }
5648 PointeeTy = PT->getPointeeType();
5649 } else {
5650 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5651 }
5652
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005653 bool isReadOnly = false;
5654 // For historical/compatibility reasons, the read-only qualifier of the
5655 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5656 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005657 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005658 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005659 if (OutermostType && T.isConstQualified()) {
5660 isReadOnly = true;
5661 S += 'r';
5662 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005663 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005664 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005665 while (P->getAs<PointerType>())
5666 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005667 if (P.isConstQualified()) {
5668 isReadOnly = true;
5669 S += 'r';
5670 }
5671 }
5672 if (isReadOnly) {
5673 // Another legacy compatibility encoding. Some ObjC qualifier and type
5674 // combinations need to be rearranged.
5675 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005676 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005677 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005678 }
Mike Stump11289f42009-09-09 15:08:12 +00005679
Anders Carlssond8499822007-10-29 05:01:08 +00005680 if (PointeeTy->isCharType()) {
5681 // char pointer types should be encoded as '*' unless it is a
5682 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005683 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005684 S += '*';
5685 return;
5686 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005687 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005688 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5689 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5690 S += '#';
5691 return;
5692 }
5693 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5694 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5695 S += '@';
5696 return;
5697 }
5698 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005699 }
Anders Carlssond8499822007-10-29 05:01:08 +00005700 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005701 getLegacyIntegralTypeEncoding(PointeeTy);
5702
Mike Stump11289f42009-09-09 15:08:12 +00005703 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005704 nullptr, false, false, false, false, false, false,
5705 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005706 return;
5707 }
John McCall393a78d2012-12-20 02:45:14 +00005708
5709 case Type::ConstantArray:
5710 case Type::IncompleteArray:
5711 case Type::VariableArray: {
5712 const ArrayType *AT = cast<ArrayType>(CT);
5713
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005714 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005715 // Incomplete arrays are encoded as a pointer to the array element.
5716 S += '^';
5717
Mike Stump11289f42009-09-09 15:08:12 +00005718 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005719 false, ExpandStructures, FD);
5720 } else {
5721 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005722
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005723 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5724 S += llvm::utostr(CAT->getSize().getZExtValue());
5725 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005726 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005727 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5728 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005729 S += '0';
5730 }
Mike Stump11289f42009-09-09 15:08:12 +00005731
5732 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005733 false, ExpandStructures, FD,
5734 false, false, false, false, false, false,
5735 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005736 S += ']';
5737 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005738 return;
5739 }
Mike Stump11289f42009-09-09 15:08:12 +00005740
John McCall393a78d2012-12-20 02:45:14 +00005741 case Type::FunctionNoProto:
5742 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005743 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005744 return;
Mike Stump11289f42009-09-09 15:08:12 +00005745
John McCall393a78d2012-12-20 02:45:14 +00005746 case Type::Record: {
5747 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005748 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005749 // Anonymous structures print as '?'
5750 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5751 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005752 if (ClassTemplateSpecializationDecl *Spec
5753 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5754 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005755 llvm::raw_string_ostream OS(S);
5756 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005757 TemplateArgs.data(),
5758 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005759 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005760 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005761 } else {
5762 S += '?';
5763 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005764 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005765 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005766 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005767 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005768 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005769 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005770 if (FD) {
5771 S += '"';
5772 S += Field->getNameAsString();
5773 S += '"';
5774 }
Mike Stump11289f42009-09-09 15:08:12 +00005775
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005776 // Special case bit-fields.
5777 if (Field->isBitField()) {
5778 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005779 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005780 } else {
5781 QualType qt = Field->getType();
5782 getLegacyIntegralTypeEncoding(qt);
5783 getObjCEncodingForTypeImpl(qt, S, false, true,
5784 FD, /*OutermostType*/false,
5785 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005786 /*StructField*/true,
5787 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005788 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005789 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005790 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005791 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005792 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005793 return;
5794 }
Mike Stump11289f42009-09-09 15:08:12 +00005795
John McCall393a78d2012-12-20 02:45:14 +00005796 case Type::BlockPointer: {
5797 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005798 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005799 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005800 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005801
5802 S += '<';
5803 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005804 getObjCEncodingForTypeImpl(
5805 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5806 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005807 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5808 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005809 // Block self
5810 S += "@?";
5811 // Block parameters
5812 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005813 for (const auto &I : FPT->param_types())
5814 getObjCEncodingForTypeImpl(
5815 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5816 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005817 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5818 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005819 }
5820 S += '>';
5821 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005822 return;
5823 }
Mike Stump11289f42009-09-09 15:08:12 +00005824
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005825 case Type::ObjCObject: {
5826 // hack to match legacy encoding of *id and *Class
5827 QualType Ty = getObjCObjectPointerType(CT);
5828 if (Ty->isObjCIdType()) {
5829 S += "{objc_object=}";
5830 return;
5831 }
5832 else if (Ty->isObjCClassType()) {
5833 S += "{objc_class=}";
5834 return;
5835 }
5836 }
5837
John McCall393a78d2012-12-20 02:45:14 +00005838 case Type::ObjCInterface: {
5839 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005840 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005841 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005842 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005843 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005844 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005845 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005846 DeepCollectObjCIvars(OI, true, Ivars);
5847 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005848 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005849 if (Field->isBitField())
5850 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005851 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005852 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5853 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005854 EncodePointerToObjCTypedef,
5855 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005856 }
5857 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005858 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005859 }
Mike Stump11289f42009-09-09 15:08:12 +00005860
John McCall393a78d2012-12-20 02:45:14 +00005861 case Type::ObjCObjectPointer: {
5862 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005863 if (OPT->isObjCIdType()) {
5864 S += '@';
5865 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005866 }
Mike Stump11289f42009-09-09 15:08:12 +00005867
Steve Narofff0c86112009-10-28 22:03:49 +00005868 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5869 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5870 // Since this is a binary compatibility issue, need to consult with runtime
5871 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005872 S += '#';
5873 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005874 }
Mike Stump11289f42009-09-09 15:08:12 +00005875
Chris Lattnere7cabb92009-07-13 00:10:46 +00005876 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005877 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005878 ExpandPointedToStructures,
5879 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005880 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005881 // Note that we do extended encoding of protocol qualifer list
5882 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005883 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005884 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005885 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005886 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005887 S += '>';
5888 }
5889 S += '"';
5890 }
5891 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005892 }
Mike Stump11289f42009-09-09 15:08:12 +00005893
Chris Lattnere7cabb92009-07-13 00:10:46 +00005894 QualType PointeeTy = OPT->getPointeeType();
5895 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005896 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5897 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005898 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005899 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005900 // {...};
5901 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005902 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005903 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005904 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5905 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5906 DeepCollectObjCIvars(OI, true, Ivars);
5907 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5908 if (cast<FieldDecl>(Ivars[i]) == FD) {
5909 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005910 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005911 S += '}';
5912 return;
5913 }
5914 }
5915 }
Mike Stump11289f42009-09-09 15:08:12 +00005916 getObjCEncodingForTypeImpl(PointeeTy, S,
5917 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005918 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005919 false, false, false, false, false,
5920 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005921 return;
5922 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005923
5924 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005925 if (OPT->getInterfaceDecl() &&
5926 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005927 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005928 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005929 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005930 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005931 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005932 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005933 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005934 S += '"';
5935 }
5936 return;
5937 }
Mike Stump11289f42009-09-09 15:08:12 +00005938
John McCalla9e6e8d2010-05-17 23:56:34 +00005939 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005940 // FIXME: we shoul do better than that. 'M' is available.
5941 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005942 // This matches gcc's encoding, even though technically it is insufficient.
5943 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005944 case Type::Vector:
5945 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005946 // Until we have a coherent encoding of these three types, issue warning.
5947 { if (NotEncodedT)
5948 *NotEncodedT = T;
5949 return;
5950 }
5951
5952 // We could see an undeduced auto type here during error recovery.
5953 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005954 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005955 return;
5956
Xiuli Pan9c14e282016-01-09 12:53:17 +00005957 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00005958#define ABSTRACT_TYPE(KIND, BASE)
5959#define TYPE(KIND, BASE)
5960#define DEPENDENT_TYPE(KIND, BASE) \
5961 case Type::KIND:
5962#define NON_CANONICAL_TYPE(KIND, BASE) \
5963 case Type::KIND:
5964#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5965 case Type::KIND:
5966#include "clang/AST/TypeNodes.def"
5967 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005968 }
John McCall393a78d2012-12-20 02:45:14 +00005969 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005970}
5971
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005972void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5973 std::string &S,
5974 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005975 bool includeVBases,
5976 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005977 assert(RDecl && "Expected non-null RecordDecl");
5978 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00005979 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005980 return;
5981
5982 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5983 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5984 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5985
5986 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005987 for (const auto &BI : CXXRec->bases()) {
5988 if (!BI.isVirtual()) {
5989 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005990 if (base->isEmpty())
5991 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005992 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005993 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5994 std::make_pair(offs, base));
5995 }
5996 }
5997 }
5998
5999 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006000 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006001 uint64_t offs = layout.getFieldOffset(i);
6002 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006003 std::make_pair(offs, Field));
6004 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006005 }
6006
6007 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006008 for (const auto &BI : CXXRec->vbases()) {
6009 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006010 if (base->isEmpty())
6011 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006012 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006013 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6014 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006015 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6016 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006017 }
6018 }
6019
6020 CharUnits size;
6021 if (CXXRec) {
6022 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6023 } else {
6024 size = layout.getSize();
6025 }
6026
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006027#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006028 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006029#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006030 std::multimap<uint64_t, NamedDecl *>::iterator
6031 CurLayObj = FieldOrBaseOffsets.begin();
6032
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006033 if (CXXRec && CXXRec->isDynamicClass() &&
6034 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006035 if (FD) {
6036 S += "\"_vptr$";
6037 std::string recname = CXXRec->getNameAsString();
6038 if (recname.empty()) recname = "?";
6039 S += recname;
6040 S += '"';
6041 }
6042 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006043#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006044 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006045#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006046 }
6047
6048 if (!RDecl->hasFlexibleArrayMember()) {
6049 // Mark the end of the structure.
6050 uint64_t offs = toBits(size);
6051 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006052 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006053 }
6054
6055 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006056#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006057 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006058 if (CurOffs < CurLayObj->first) {
6059 uint64_t padding = CurLayObj->first - CurOffs;
6060 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6061 // packing/alignment of members is different that normal, in which case
6062 // the encoding will be out-of-sync with the real layout.
6063 // If the runtime switches to just consider the size of types without
6064 // taking into account alignment, we could make padding explicit in the
6065 // encoding (e.g. using arrays of chars). The encoding strings would be
6066 // longer then though.
6067 CurOffs += padding;
6068 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006069#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006070
6071 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006072 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006073 break; // reached end of structure.
6074
6075 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6076 // We expand the bases without their virtual bases since those are going
6077 // in the initial structure. Note that this differs from gcc which
6078 // expands virtual bases each time one is encountered in the hierarchy,
6079 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006080 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6081 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006082 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006083#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006084 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006085#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006086 } else {
6087 FieldDecl *field = cast<FieldDecl>(dcl);
6088 if (FD) {
6089 S += '"';
6090 S += field->getNameAsString();
6091 S += '"';
6092 }
6093
6094 if (field->isBitField()) {
6095 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006096#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006097 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006098#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006099 } else {
6100 QualType qt = field->getType();
6101 getLegacyIntegralTypeEncoding(qt);
6102 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6103 /*OutermostType*/false,
6104 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006105 /*StructField*/true,
6106 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006107#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006108 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006109#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006110 }
6111 }
6112 }
6113}
6114
Mike Stump11289f42009-09-09 15:08:12 +00006115void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006116 std::string& S) const {
6117 if (QT & Decl::OBJC_TQ_In)
6118 S += 'n';
6119 if (QT & Decl::OBJC_TQ_Inout)
6120 S += 'N';
6121 if (QT & Decl::OBJC_TQ_Out)
6122 S += 'o';
6123 if (QT & Decl::OBJC_TQ_Bycopy)
6124 S += 'O';
6125 if (QT & Decl::OBJC_TQ_Byref)
6126 S += 'R';
6127 if (QT & Decl::OBJC_TQ_Oneway)
6128 S += 'V';
6129}
6130
Douglas Gregor3ea72692011-08-12 05:46:01 +00006131TypedefDecl *ASTContext::getObjCIdDecl() const {
6132 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006133 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006134 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006135 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006136 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006137 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006138}
6139
Douglas Gregor52e02802011-08-12 06:17:30 +00006140TypedefDecl *ASTContext::getObjCSelDecl() const {
6141 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006142 QualType T = getPointerType(ObjCBuiltinSelTy);
6143 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006144 }
6145 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006146}
6147
Douglas Gregor0a586182011-08-12 05:59:41 +00006148TypedefDecl *ASTContext::getObjCClassDecl() const {
6149 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006150 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006151 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006152 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006153 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006154 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006155}
6156
Douglas Gregord53ae832012-01-17 18:09:05 +00006157ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6158 if (!ObjCProtocolClassDecl) {
6159 ObjCProtocolClassDecl
6160 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6161 SourceLocation(),
6162 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006163 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006164 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006165 SourceLocation(), true);
6166 }
6167
6168 return ObjCProtocolClassDecl;
6169}
6170
Meador Inge5d3fb222012-06-16 03:34:49 +00006171//===----------------------------------------------------------------------===//
6172// __builtin_va_list Construction Functions
6173//===----------------------------------------------------------------------===//
6174
Charles Davisc7d5c942015-09-17 20:55:33 +00006175static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6176 StringRef Name) {
6177 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006178 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006179 return Context->buildImplicitTypedef(T, Name);
6180}
6181
6182static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6183 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6184}
6185
6186static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6187 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006188}
6189
6190static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6191 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006192 QualType T = Context->getPointerType(Context->VoidTy);
6193 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006194}
6195
Tim Northover9bb857a2013-01-31 12:13:10 +00006196static TypedefDecl *
6197CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006198 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006199 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006200 if (Context->getLangOpts().CPlusPlus) {
6201 // namespace std { struct __va_list {
6202 NamespaceDecl *NS;
6203 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6204 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006205 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006206 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006207 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006208 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006209 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006210 }
6211
6212 VaListTagDecl->startDefinition();
6213
6214 const size_t NumFields = 5;
6215 QualType FieldTypes[NumFields];
6216 const char *FieldNames[NumFields];
6217
6218 // void *__stack;
6219 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6220 FieldNames[0] = "__stack";
6221
6222 // void *__gr_top;
6223 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6224 FieldNames[1] = "__gr_top";
6225
6226 // void *__vr_top;
6227 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6228 FieldNames[2] = "__vr_top";
6229
6230 // int __gr_offs;
6231 FieldTypes[3] = Context->IntTy;
6232 FieldNames[3] = "__gr_offs";
6233
6234 // int __vr_offs;
6235 FieldTypes[4] = Context->IntTy;
6236 FieldNames[4] = "__vr_offs";
6237
6238 // Create fields
6239 for (unsigned i = 0; i < NumFields; ++i) {
6240 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6241 VaListTagDecl,
6242 SourceLocation(),
6243 SourceLocation(),
6244 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006245 FieldTypes[i], /*TInfo=*/nullptr,
6246 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006247 /*Mutable=*/false,
6248 ICIS_NoInit);
6249 Field->setAccess(AS_public);
6250 VaListTagDecl->addDecl(Field);
6251 }
6252 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006253 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006254 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006255
6256 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006257 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006258}
6259
Meador Inge5d3fb222012-06-16 03:34:49 +00006260static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6261 // typedef struct __va_list_tag {
6262 RecordDecl *VaListTagDecl;
6263
Alp Toker2dea15b2013-12-17 01:22:38 +00006264 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006265 VaListTagDecl->startDefinition();
6266
6267 const size_t NumFields = 5;
6268 QualType FieldTypes[NumFields];
6269 const char *FieldNames[NumFields];
6270
6271 // unsigned char gpr;
6272 FieldTypes[0] = Context->UnsignedCharTy;
6273 FieldNames[0] = "gpr";
6274
6275 // unsigned char fpr;
6276 FieldTypes[1] = Context->UnsignedCharTy;
6277 FieldNames[1] = "fpr";
6278
6279 // unsigned short reserved;
6280 FieldTypes[2] = Context->UnsignedShortTy;
6281 FieldNames[2] = "reserved";
6282
6283 // void* overflow_arg_area;
6284 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6285 FieldNames[3] = "overflow_arg_area";
6286
6287 // void* reg_save_area;
6288 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6289 FieldNames[4] = "reg_save_area";
6290
6291 // Create fields
6292 for (unsigned i = 0; i < NumFields; ++i) {
6293 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6294 SourceLocation(),
6295 SourceLocation(),
6296 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006297 FieldTypes[i], /*TInfo=*/nullptr,
6298 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006299 /*Mutable=*/false,
6300 ICIS_NoInit);
6301 Field->setAccess(AS_public);
6302 VaListTagDecl->addDecl(Field);
6303 }
6304 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006305 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006306 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6307
6308 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006309 TypedefDecl *VaListTagTypedefDecl =
6310 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6311
Meador Inge5d3fb222012-06-16 03:34:49 +00006312 QualType VaListTagTypedefType =
6313 Context->getTypedefType(VaListTagTypedefDecl);
6314
6315 // typedef __va_list_tag __builtin_va_list[1];
6316 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6317 QualType VaListTagArrayType
6318 = Context->getConstantArrayType(VaListTagTypedefType,
6319 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006320 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006321}
6322
6323static TypedefDecl *
6324CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006325 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006326 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006327 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006328 VaListTagDecl->startDefinition();
6329
6330 const size_t NumFields = 4;
6331 QualType FieldTypes[NumFields];
6332 const char *FieldNames[NumFields];
6333
6334 // unsigned gp_offset;
6335 FieldTypes[0] = Context->UnsignedIntTy;
6336 FieldNames[0] = "gp_offset";
6337
6338 // unsigned fp_offset;
6339 FieldTypes[1] = Context->UnsignedIntTy;
6340 FieldNames[1] = "fp_offset";
6341
6342 // void* overflow_arg_area;
6343 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6344 FieldNames[2] = "overflow_arg_area";
6345
6346 // void* reg_save_area;
6347 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6348 FieldNames[3] = "reg_save_area";
6349
6350 // Create fields
6351 for (unsigned i = 0; i < NumFields; ++i) {
6352 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6353 VaListTagDecl,
6354 SourceLocation(),
6355 SourceLocation(),
6356 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006357 FieldTypes[i], /*TInfo=*/nullptr,
6358 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006359 /*Mutable=*/false,
6360 ICIS_NoInit);
6361 Field->setAccess(AS_public);
6362 VaListTagDecl->addDecl(Field);
6363 }
6364 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006365 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006366 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6367
Richard Smith9b88a4c2015-07-27 05:40:23 +00006368 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006369
Richard Smith9b88a4c2015-07-27 05:40:23 +00006370 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006371 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006372 QualType VaListTagArrayType =
6373 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006374 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006375}
6376
6377static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6378 // typedef int __builtin_va_list[4];
6379 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6380 QualType IntArrayType
6381 = Context->getConstantArrayType(Context->IntTy,
6382 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006383 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006384}
6385
Logan Chien57086ce2012-10-10 06:56:20 +00006386static TypedefDecl *
6387CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006388 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006389 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006390 if (Context->getLangOpts().CPlusPlus) {
6391 // namespace std { struct __va_list {
6392 NamespaceDecl *NS;
6393 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6394 Context->getTranslationUnitDecl(),
6395 /*Inline*/false, SourceLocation(),
6396 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006397 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006398 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006399 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006400 }
6401
6402 VaListDecl->startDefinition();
6403
6404 // void * __ap;
6405 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6406 VaListDecl,
6407 SourceLocation(),
6408 SourceLocation(),
6409 &Context->Idents.get("__ap"),
6410 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006411 /*TInfo=*/nullptr,
6412 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006413 /*Mutable=*/false,
6414 ICIS_NoInit);
6415 Field->setAccess(AS_public);
6416 VaListDecl->addDecl(Field);
6417
6418 // };
6419 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006420 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006421
6422 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006423 QualType T = Context->getRecordType(VaListDecl);
6424 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006425}
6426
Ulrich Weigand47445072013-05-06 16:26:41 +00006427static TypedefDecl *
6428CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006429 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006430 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006431 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006432 VaListTagDecl->startDefinition();
6433
6434 const size_t NumFields = 4;
6435 QualType FieldTypes[NumFields];
6436 const char *FieldNames[NumFields];
6437
6438 // long __gpr;
6439 FieldTypes[0] = Context->LongTy;
6440 FieldNames[0] = "__gpr";
6441
6442 // long __fpr;
6443 FieldTypes[1] = Context->LongTy;
6444 FieldNames[1] = "__fpr";
6445
6446 // void *__overflow_arg_area;
6447 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6448 FieldNames[2] = "__overflow_arg_area";
6449
6450 // void *__reg_save_area;
6451 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6452 FieldNames[3] = "__reg_save_area";
6453
6454 // Create fields
6455 for (unsigned i = 0; i < NumFields; ++i) {
6456 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6457 VaListTagDecl,
6458 SourceLocation(),
6459 SourceLocation(),
6460 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006461 FieldTypes[i], /*TInfo=*/nullptr,
6462 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006463 /*Mutable=*/false,
6464 ICIS_NoInit);
6465 Field->setAccess(AS_public);
6466 VaListTagDecl->addDecl(Field);
6467 }
6468 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006469 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006470 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006471
Richard Smith9b88a4c2015-07-27 05:40:23 +00006472 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006473
6474 // typedef __va_list_tag __builtin_va_list[1];
6475 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006476 QualType VaListTagArrayType =
6477 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006478
Alp Toker56b5cc92013-12-15 10:36:26 +00006479 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006480}
6481
Meador Inge5d3fb222012-06-16 03:34:49 +00006482static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6483 TargetInfo::BuiltinVaListKind Kind) {
6484 switch (Kind) {
6485 case TargetInfo::CharPtrBuiltinVaList:
6486 return CreateCharPtrBuiltinVaListDecl(Context);
6487 case TargetInfo::VoidPtrBuiltinVaList:
6488 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006489 case TargetInfo::AArch64ABIBuiltinVaList:
6490 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006491 case TargetInfo::PowerABIBuiltinVaList:
6492 return CreatePowerABIBuiltinVaListDecl(Context);
6493 case TargetInfo::X86_64ABIBuiltinVaList:
6494 return CreateX86_64ABIBuiltinVaListDecl(Context);
6495 case TargetInfo::PNaClABIBuiltinVaList:
6496 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006497 case TargetInfo::AAPCSABIBuiltinVaList:
6498 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006499 case TargetInfo::SystemZBuiltinVaList:
6500 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006501 }
6502
6503 llvm_unreachable("Unhandled __builtin_va_list type kind");
6504}
6505
6506TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006507 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006508 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006509 assert(BuiltinVaListDecl->isImplicit());
6510 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006511
6512 return BuiltinVaListDecl;
6513}
6514
Richard Smith9b88a4c2015-07-27 05:40:23 +00006515Decl *ASTContext::getVaListTagDecl() const {
6516 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006517 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006518 if (!VaListTagDecl)
6519 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006520
Richard Smith9b88a4c2015-07-27 05:40:23 +00006521 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006522}
6523
Charles Davisc7d5c942015-09-17 20:55:33 +00006524TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6525 if (!BuiltinMSVaListDecl)
6526 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6527
6528 return BuiltinMSVaListDecl;
6529}
6530
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006531void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006532 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006533 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006534
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006535 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006536}
6537
John McCalld28ae272009-12-02 08:04:21 +00006538/// \brief Retrieve the template name that corresponds to a non-empty
6539/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006540TemplateName
6541ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6542 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006543 unsigned size = End - Begin;
6544 assert(size > 1 && "set is not overloaded!");
6545
6546 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6547 size * sizeof(FunctionTemplateDecl*));
6548 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6549
6550 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006551 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006552 NamedDecl *D = *I;
6553 assert(isa<FunctionTemplateDecl>(D) ||
6554 (isa<UsingShadowDecl>(D) &&
6555 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6556 *Storage++ = D;
6557 }
6558
6559 return TemplateName(OT);
6560}
6561
Douglas Gregordc572a32009-03-30 22:58:21 +00006562/// \brief Retrieve the template name that represents a qualified
6563/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006564TemplateName
6565ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6566 bool TemplateKeyword,
6567 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006568 assert(NNS && "Missing nested-name-specifier in qualified template name");
6569
Douglas Gregorc42075a2010-02-04 18:10:26 +00006570 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006571 llvm::FoldingSetNodeID ID;
6572 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6573
Craig Topper36250ad2014-05-12 05:36:57 +00006574 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006575 QualifiedTemplateName *QTN =
6576 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6577 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006578 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6579 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006580 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6581 }
6582
6583 return TemplateName(QTN);
6584}
6585
6586/// \brief Retrieve the template name that represents a dependent
6587/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006588TemplateName
6589ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6590 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006591 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006592 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006593
6594 llvm::FoldingSetNodeID ID;
6595 DependentTemplateName::Profile(ID, NNS, Name);
6596
Craig Topper36250ad2014-05-12 05:36:57 +00006597 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006598 DependentTemplateName *QTN =
6599 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6600
6601 if (QTN)
6602 return TemplateName(QTN);
6603
6604 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6605 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006606 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6607 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006608 } else {
6609 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006610 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6611 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006612 DependentTemplateName *CheckQTN =
6613 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6614 assert(!CheckQTN && "Dependent type name canonicalization broken");
6615 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006616 }
6617
6618 DependentTemplateNames.InsertNode(QTN, InsertPos);
6619 return TemplateName(QTN);
6620}
6621
Douglas Gregor71395fa2009-11-04 00:56:37 +00006622/// \brief Retrieve the template name that represents a dependent
6623/// template name such as \c MetaFun::template operator+.
6624TemplateName
6625ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006626 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006627 assert((!NNS || NNS->isDependent()) &&
6628 "Nested name specifier must be dependent");
6629
6630 llvm::FoldingSetNodeID ID;
6631 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006632
6633 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006634 DependentTemplateName *QTN
6635 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006636
6637 if (QTN)
6638 return TemplateName(QTN);
6639
6640 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6641 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006642 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6643 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006644 } else {
6645 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006646 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6647 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006648
6649 DependentTemplateName *CheckQTN
6650 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6651 assert(!CheckQTN && "Dependent template name canonicalization broken");
6652 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006653 }
6654
6655 DependentTemplateNames.InsertNode(QTN, InsertPos);
6656 return TemplateName(QTN);
6657}
6658
Douglas Gregor5590be02011-01-15 06:45:20 +00006659TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006660ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6661 TemplateName replacement) const {
6662 llvm::FoldingSetNodeID ID;
6663 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006664
6665 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006666 SubstTemplateTemplateParmStorage *subst
6667 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6668
6669 if (!subst) {
6670 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6671 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6672 }
6673
6674 return TemplateName(subst);
6675}
6676
6677TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006678ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6679 const TemplateArgument &ArgPack) const {
6680 ASTContext &Self = const_cast<ASTContext &>(*this);
6681 llvm::FoldingSetNodeID ID;
6682 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006683
6684 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006685 SubstTemplateTemplateParmPackStorage *Subst
6686 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6687
6688 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006689 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006690 ArgPack.pack_size(),
6691 ArgPack.pack_begin());
6692 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6693 }
6694
6695 return TemplateName(Subst);
6696}
6697
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006698/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006699/// TargetInfo, produce the corresponding type. The unsigned @p Type
6700/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006701CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006702 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006703 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006704 case TargetInfo::SignedChar: return SignedCharTy;
6705 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006706 case TargetInfo::SignedShort: return ShortTy;
6707 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6708 case TargetInfo::SignedInt: return IntTy;
6709 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6710 case TargetInfo::SignedLong: return LongTy;
6711 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6712 case TargetInfo::SignedLongLong: return LongLongTy;
6713 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6714 }
6715
David Blaikie83d382b2011-09-23 05:06:16 +00006716 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006717}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006718
6719//===----------------------------------------------------------------------===//
6720// Type Predicates.
6721//===----------------------------------------------------------------------===//
6722
Fariborz Jahanian96207692009-02-18 21:49:28 +00006723/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6724/// garbage collection attribute.
6725///
John McCall553d45a2011-01-12 00:34:59 +00006726Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006727 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006728 return Qualifiers::GCNone;
6729
David Blaikiebbafb8a2012-03-11 07:00:24 +00006730 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006731 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6732
6733 // Default behaviour under objective-C's gc is for ObjC pointers
6734 // (or pointers to them) be treated as though they were declared
6735 // as __strong.
6736 if (GCAttrs == Qualifiers::GCNone) {
6737 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6738 return Qualifiers::Strong;
6739 else if (Ty->isPointerType())
6740 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6741 } else {
6742 // It's not valid to set GC attributes on anything that isn't a
6743 // pointer.
6744#ifndef NDEBUG
6745 QualType CT = Ty->getCanonicalTypeInternal();
6746 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6747 CT = AT->getElementType();
6748 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6749#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006750 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006751 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006752}
6753
Chris Lattner49af6a42008-04-07 06:51:04 +00006754//===----------------------------------------------------------------------===//
6755// Type Compatibility Testing
6756//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006757
Mike Stump11289f42009-09-09 15:08:12 +00006758/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006759/// compatible.
6760static bool areCompatVectorTypes(const VectorType *LHS,
6761 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006762 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006763 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006764 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006765}
6766
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006767bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6768 QualType SecondVec) {
6769 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6770 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6771
6772 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6773 return true;
6774
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006775 // Treat Neon vector types and most AltiVec vector types as if they are the
6776 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006777 const VectorType *First = FirstVec->getAs<VectorType>();
6778 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006779 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006780 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006781 First->getVectorKind() != VectorType::AltiVecPixel &&
6782 First->getVectorKind() != VectorType::AltiVecBool &&
6783 Second->getVectorKind() != VectorType::AltiVecPixel &&
6784 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006785 return true;
6786
6787 return false;
6788}
6789
Steve Naroff8e6aee52009-07-23 01:01:38 +00006790//===----------------------------------------------------------------------===//
6791// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6792//===----------------------------------------------------------------------===//
6793
6794/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6795/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006796bool
6797ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6798 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006799 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006800 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006801 for (auto *PI : rProto->protocols())
6802 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006803 return true;
6804 return false;
6805}
6806
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006807/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6808/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006809bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6810 QualType rhs) {
6811 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6812 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6813 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6814
Aaron Ballman83731462014-03-17 16:14:00 +00006815 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006816 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006817 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006818 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6819 match = true;
6820 break;
6821 }
6822 }
6823 if (!match)
6824 return false;
6825 }
6826 return true;
6827}
6828
Steve Naroff8e6aee52009-07-23 01:01:38 +00006829/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6830/// ObjCQualifiedIDType.
6831bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6832 bool compare) {
6833 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006834 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006835 lhs->isObjCIdType() || lhs->isObjCClassType())
6836 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006837 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006838 rhs->isObjCIdType() || rhs->isObjCClassType())
6839 return true;
6840
6841 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006842 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006843
Steve Naroff8e6aee52009-07-23 01:01:38 +00006844 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006845
Steve Naroff8e6aee52009-07-23 01:01:38 +00006846 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006847 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006848 // make sure we check the class hierarchy.
6849 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006850 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006851 // when comparing an id<P> on lhs with a static type on rhs,
6852 // see if static class implements all of id's protocols, directly or
6853 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006854 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006855 return false;
6856 }
6857 }
6858 // If there are no qualifiers and no interface, we have an 'id'.
6859 return true;
6860 }
Mike Stump11289f42009-09-09 15:08:12 +00006861 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006862 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006863 bool match = false;
6864
6865 // when comparing an id<P> on lhs with a static type on rhs,
6866 // see if static class implements all of id's protocols, directly or
6867 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006868 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006869 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6870 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6871 match = true;
6872 break;
6873 }
6874 }
Mike Stump11289f42009-09-09 15:08:12 +00006875 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006876 // make sure we check the class hierarchy.
6877 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006878 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006879 // when comparing an id<P> on lhs with a static type on rhs,
6880 // see if static class implements all of id's protocols, directly or
6881 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006882 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006883 match = true;
6884 break;
6885 }
6886 }
6887 }
6888 if (!match)
6889 return false;
6890 }
Mike Stump11289f42009-09-09 15:08:12 +00006891
Steve Naroff8e6aee52009-07-23 01:01:38 +00006892 return true;
6893 }
Mike Stump11289f42009-09-09 15:08:12 +00006894
Steve Naroff8e6aee52009-07-23 01:01:38 +00006895 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6896 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6897
Mike Stump11289f42009-09-09 15:08:12 +00006898 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006899 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006900 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006901 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006902 bool match = false;
6903
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006904 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006905 // see if static class implements all of id's protocols, directly or
6906 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006907 // First, lhs protocols in the qualifier list must be found, direct
6908 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006909 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006910 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6911 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6912 match = true;
6913 break;
6914 }
6915 }
6916 if (!match)
6917 return false;
6918 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006919
6920 // Static class's protocols, or its super class or category protocols
6921 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6922 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6923 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6924 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6925 // This is rather dubious but matches gcc's behavior. If lhs has
6926 // no type qualifier and its class has no static protocol(s)
6927 // assume that it is mismatch.
6928 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6929 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006930 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006931 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006932 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006933 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6934 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6935 match = true;
6936 break;
6937 }
6938 }
6939 if (!match)
6940 return false;
6941 }
6942 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006943 return true;
6944 }
6945 return false;
6946}
6947
Eli Friedman47f77112008-08-22 00:56:42 +00006948/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006949/// compatible for assignment from RHS to LHS. This handles validation of any
6950/// protocol qualifiers on the LHS or RHS.
6951///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006952bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6953 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006954 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6955 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6956
Steve Naroff1329fa02009-07-15 18:40:39 +00006957 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006958 if (LHS->isObjCUnqualifiedIdOrClass() ||
6959 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006960 return true;
6961
Douglas Gregorab209d82015-07-07 03:58:42 +00006962 // Function object that propagates a successful result or handles
6963 // __kindof types.
6964 auto finish = [&](bool succeeded) -> bool {
6965 if (succeeded)
6966 return true;
6967
6968 if (!RHS->isKindOfType())
6969 return false;
6970
6971 // Strip off __kindof and protocol qualifiers, then check whether
6972 // we can assign the other way.
6973 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6974 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6975 };
6976
6977 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6978 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6979 QualType(RHSOPT,0),
6980 false));
6981 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006982
Douglas Gregorab209d82015-07-07 03:58:42 +00006983 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6984 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6985 QualType(RHSOPT,0)));
6986 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006987
John McCall8b07ec22010-05-15 11:32:37 +00006988 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006989 if (LHS->getInterface() && RHS->getInterface()) {
6990 return finish(canAssignObjCInterfaces(LHS, RHS));
6991 }
Mike Stump11289f42009-09-09 15:08:12 +00006992
Steve Naroff8e6aee52009-07-23 01:01:38 +00006993 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006994}
6995
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006996/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006997/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006998/// arguments in block literals. When passed as arguments, passing 'A*' where
6999/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7000/// not OK. For the return type, the opposite is not OK.
7001bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7002 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007003 const ObjCObjectPointerType *RHSOPT,
7004 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007005
7006 // Function object that propagates a successful result or handles
7007 // __kindof types.
7008 auto finish = [&](bool succeeded) -> bool {
7009 if (succeeded)
7010 return true;
7011
7012 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7013 if (!Expected->isKindOfType())
7014 return false;
7015
7016 // Strip off __kindof and protocol qualifiers, then check whether
7017 // we can assign the other way.
7018 return canAssignObjCInterfacesInBlockPointer(
7019 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7020 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7021 BlockReturnType);
7022 };
7023
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007024 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007025 return true;
7026
7027 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007028 return finish(RHSOPT->isObjCBuiltinType() ||
7029 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007030 }
7031
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007032 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007033 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7034 QualType(RHSOPT,0),
7035 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007036
7037 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7038 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7039 if (LHS && RHS) { // We have 2 user-defined types.
7040 if (LHS != RHS) {
7041 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007042 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007043 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007044 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007045 }
7046 else
7047 return true;
7048 }
7049 return false;
7050}
7051
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007052/// Comparison routine for Objective-C protocols to be used with
7053/// llvm::array_pod_sort.
7054static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7055 ObjCProtocolDecl * const *rhs) {
7056 return (*lhs)->getName().compare((*rhs)->getName());
7057
7058}
7059
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007060/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007061/// of protocols inherited from two distinct objective-c pointer objects with
7062/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007063/// It is used to build composite qualifier list of the composite type of
7064/// the conditional expression involving two objective-c pointer objects.
7065static
7066void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007067 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007068 const ObjCObjectPointerType *LHSOPT,
7069 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007070 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007071
John McCall8b07ec22010-05-15 11:32:37 +00007072 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7073 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7074 assert(LHS->getInterface() && "LHS must have an interface base");
7075 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007076
7077 // Add all of the protocols for the LHS.
7078 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7079
7080 // Start with the protocol qualifiers.
7081 for (auto proto : LHS->quals()) {
7082 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007083 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007084
7085 // Also add the protocols associated with the LHS interface.
7086 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7087
7088 // Add all of the protocls for the RHS.
7089 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7090
7091 // Start with the protocol qualifiers.
7092 for (auto proto : RHS->quals()) {
7093 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007094 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007095
7096 // Also add the protocols associated with the RHS interface.
7097 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7098
7099 // Compute the intersection of the collected protocol sets.
7100 for (auto proto : LHSProtocolSet) {
7101 if (RHSProtocolSet.count(proto))
7102 IntersectionSet.push_back(proto);
7103 }
7104
7105 // Compute the set of protocols that is implied by either the common type or
7106 // the protocols within the intersection.
7107 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7108 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7109
7110 // Remove any implied protocols from the list of inherited protocols.
7111 if (!ImpliedProtocols.empty()) {
7112 IntersectionSet.erase(
7113 std::remove_if(IntersectionSet.begin(),
7114 IntersectionSet.end(),
7115 [&](ObjCProtocolDecl *proto) -> bool {
7116 return ImpliedProtocols.count(proto) > 0;
7117 }),
7118 IntersectionSet.end());
7119 }
7120
7121 // Sort the remaining protocols by name.
7122 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7123 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007124}
7125
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007126/// Determine whether the first type is a subtype of the second.
7127static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7128 QualType rhs) {
7129 // Common case: two object pointers.
7130 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7131 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7132 if (lhsOPT && rhsOPT)
7133 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7134
7135 // Two block pointers.
7136 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7137 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7138 if (lhsBlock && rhsBlock)
7139 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7140
7141 // If either is an unqualified 'id' and the other is a block, it's
7142 // acceptable.
7143 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7144 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7145 return true;
7146
7147 return false;
7148}
7149
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007150// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007151static bool sameObjCTypeArgs(ASTContext &ctx,
7152 const ObjCInterfaceDecl *iface,
7153 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007154 ArrayRef<QualType> rhsArgs,
7155 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007156 if (lhsArgs.size() != rhsArgs.size())
7157 return false;
7158
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007159 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007160 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007161 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7162 continue;
7163
7164 switch (typeParams->begin()[i]->getVariance()) {
7165 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007166 if (!stripKindOf ||
7167 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7168 rhsArgs[i].stripObjCKindOfType(ctx))) {
7169 return false;
7170 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007171 break;
7172
7173 case ObjCTypeParamVariance::Covariant:
7174 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7175 return false;
7176 break;
7177
7178 case ObjCTypeParamVariance::Contravariant:
7179 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7180 return false;
7181 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007182 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007183 }
7184
7185 return true;
7186}
7187
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007188QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007189 const ObjCObjectPointerType *Lptr,
7190 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007191 const ObjCObjectType *LHS = Lptr->getObjectType();
7192 const ObjCObjectType *RHS = Rptr->getObjectType();
7193 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7194 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007195
7196 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007197 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007198
Manman Renc46f7d12016-05-06 19:35:02 +00007199 // When either LHS or RHS is a kindof type, we should return a kindof type.
7200 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7201 // kindof(A).
7202 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7203
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007204 // Follow the left-hand side up the class hierarchy until we either hit a
7205 // root or find the RHS. Record the ancestors in case we don't find it.
7206 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7207 LHSAncestors;
7208 while (true) {
7209 // Record this ancestor. We'll need this if the common type isn't in the
7210 // path from the LHS to the root.
7211 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007212
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007213 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7214 // Get the type arguments.
7215 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7216 bool anyChanges = false;
7217 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7218 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007219 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7220 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007221 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007222 return QualType();
7223 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7224 // If only one has type arguments, the result will not have type
7225 // arguments.
7226 LHSTypeArgs = { };
7227 anyChanges = true;
7228 }
7229
7230 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007231 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007232 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7233 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007234 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007235 anyChanges = true;
7236
7237 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007238 // If we need to return a kindof type but LHS is not a kindof type, we
7239 // build a new result type.
7240 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007241 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007242 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007243 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007244 return getObjCObjectPointerType(Result);
7245 }
7246
7247 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007248 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007249
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007250 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007251 QualType LHSSuperType = LHS->getSuperClassType();
7252 if (LHSSuperType.isNull())
7253 break;
7254
7255 LHS = LHSSuperType->castAs<ObjCObjectType>();
7256 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007257
7258 // We didn't find anything by following the LHS to its root; now check
7259 // the RHS against the cached set of ancestors.
7260 while (true) {
7261 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7262 if (KnownLHS != LHSAncestors.end()) {
7263 LHS = KnownLHS->second;
7264
7265 // Get the type arguments.
7266 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7267 bool anyChanges = false;
7268 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7269 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007270 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7271 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007272 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007273 return QualType();
7274 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7275 // If only one has type arguments, the result will not have type
7276 // arguments.
7277 RHSTypeArgs = { };
7278 anyChanges = true;
7279 }
7280
7281 // Compute the intersection of protocols.
7282 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7283 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7284 Protocols);
7285 if (!Protocols.empty())
7286 anyChanges = true;
7287
Manman Renc46f7d12016-05-06 19:35:02 +00007288 // If we need to return a kindof type but RHS is not a kindof type, we
7289 // build a new result type.
7290 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007291 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007292 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007293 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007294 return getObjCObjectPointerType(Result);
7295 }
7296
7297 return getObjCObjectPointerType(QualType(RHS, 0));
7298 }
7299
7300 // Find the superclass of the RHS.
7301 QualType RHSSuperType = RHS->getSuperClassType();
7302 if (RHSSuperType.isNull())
7303 break;
7304
7305 RHS = RHSSuperType->castAs<ObjCObjectType>();
7306 }
7307
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007308 return QualType();
7309}
7310
John McCall8b07ec22010-05-15 11:32:37 +00007311bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7312 const ObjCObjectType *RHS) {
7313 assert(LHS->getInterface() && "LHS is not an interface type");
7314 assert(RHS->getInterface() && "RHS is not an interface type");
7315
Chris Lattner49af6a42008-04-07 06:51:04 +00007316 // Verify that the base decls are compatible: the RHS must be a subclass of
7317 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007318 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7319 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7320 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007321 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007322
Douglas Gregore83b9562015-07-07 03:57:53 +00007323 // If the LHS has protocol qualifiers, determine whether all of them are
7324 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7325 // LHS).
7326 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007327 // OK if conversion of LHS to SuperClass results in narrowing of types
7328 // ; i.e., SuperClass may implement at least one of the protocols
7329 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7330 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7331 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7332 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7333 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7334 // qualifiers.
7335 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007336 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007337 // If there is no protocols associated with RHS, it is not a match.
7338 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007339 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007340
7341 for (const auto *LHSProto : LHS->quals()) {
7342 bool SuperImplementsProtocol = false;
7343 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7344 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7345 SuperImplementsProtocol = true;
7346 break;
7347 }
7348 if (!SuperImplementsProtocol)
7349 return false;
7350 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007351 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007352
7353 // If the LHS is specialized, we may need to check type arguments.
7354 if (LHS->isSpecialized()) {
7355 // Follow the superclass chain until we've matched the LHS class in the
7356 // hierarchy. This substitutes type arguments through.
7357 const ObjCObjectType *RHSSuper = RHS;
7358 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7359 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7360
7361 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007362 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007363 !sameObjCTypeArgs(*this, LHS->getInterface(),
7364 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007365 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007366 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007367 }
7368 }
7369
7370 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007371}
7372
Steve Naroffb7605152009-02-12 17:52:19 +00007373bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7374 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007375 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7376 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007377
Steve Naroff7cae42b2009-07-10 23:34:53 +00007378 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007379 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007380
7381 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7382 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007383}
7384
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007385bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7386 return canAssignObjCInterfaces(
7387 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7388 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7389}
7390
Mike Stump11289f42009-09-09 15:08:12 +00007391/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007392/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007393/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007394/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007395bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7396 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007397 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007398 return hasSameType(LHS, RHS);
7399
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007400 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007401}
7402
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007403bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007404 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007405}
7406
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007407bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7408 return !mergeTypes(LHS, RHS, true).isNull();
7409}
7410
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007411/// mergeTransparentUnionType - if T is a transparent union type and a member
7412/// of T is compatible with SubType, return the merged type, else return
7413/// QualType()
7414QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7415 bool OfBlockPointer,
7416 bool Unqualified) {
7417 if (const RecordType *UT = T->getAsUnionType()) {
7418 RecordDecl *UD = UT->getDecl();
7419 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007420 for (const auto *I : UD->fields()) {
7421 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007422 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7423 if (!MT.isNull())
7424 return MT;
7425 }
7426 }
7427 }
7428
7429 return QualType();
7430}
7431
Alp Toker9cacbab2014-01-20 20:26:09 +00007432/// mergeFunctionParameterTypes - merge two types which appear as function
7433/// parameter types
7434QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7435 bool OfBlockPointer,
7436 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007437 // GNU extension: two types are compatible if they appear as a function
7438 // argument, one of the types is a transparent union type and the other
7439 // type is compatible with a union member
7440 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7441 Unqualified);
7442 if (!lmerge.isNull())
7443 return lmerge;
7444
7445 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7446 Unqualified);
7447 if (!rmerge.isNull())
7448 return rmerge;
7449
7450 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7451}
7452
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007453QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007454 bool OfBlockPointer,
7455 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007456 const FunctionType *lbase = lhs->getAs<FunctionType>();
7457 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007458 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7459 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007460 bool allLTypes = true;
7461 bool allRTypes = true;
7462
7463 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007464 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007465 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007466 QualType RHS = rbase->getReturnType();
7467 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007468 bool UnqualifiedResult = Unqualified;
7469 if (!UnqualifiedResult)
7470 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007471 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007472 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007473 else
Alp Toker314cc812014-01-25 16:55:45 +00007474 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007475 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007476 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007477
7478 if (Unqualified)
7479 retType = retType.getUnqualifiedType();
7480
Alp Toker314cc812014-01-25 16:55:45 +00007481 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7482 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007483 if (Unqualified) {
7484 LRetType = LRetType.getUnqualifiedType();
7485 RRetType = RRetType.getUnqualifiedType();
7486 }
7487
7488 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007489 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007490 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007491 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007492
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007493 // FIXME: double check this
7494 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7495 // rbase->getRegParmAttr() != 0 &&
7496 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007497 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7498 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007499
Douglas Gregor8c940862010-01-18 17:14:39 +00007500 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007501 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007502 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007503
John McCall8c6b56f2010-12-15 01:06:38 +00007504 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007505 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7506 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007507 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7508 return QualType();
7509
John McCall31168b02011-06-15 23:02:42 +00007510 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7511 return QualType();
7512
John McCall8c6b56f2010-12-15 01:06:38 +00007513 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7514 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007515
Rafael Espindola8778c282012-11-29 16:09:03 +00007516 if (lbaseInfo.getNoReturn() != NoReturn)
7517 allLTypes = false;
7518 if (rbaseInfo.getNoReturn() != NoReturn)
7519 allRTypes = false;
7520
John McCall31168b02011-06-15 23:02:42 +00007521 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007522
Eli Friedman47f77112008-08-22 00:56:42 +00007523 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007524 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7525 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007526 // Compatible functions must have the same number of parameters
7527 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007528 return QualType();
7529
7530 // Variadic and non-variadic functions aren't compatible
7531 if (lproto->isVariadic() != rproto->isVariadic())
7532 return QualType();
7533
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007534 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7535 return QualType();
7536
John McCall18afab72016-03-01 00:49:02 +00007537 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007538 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007539
7540 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007541 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007542 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7543 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7544 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7545 QualType paramType = mergeFunctionParameterTypes(
7546 lParamType, rParamType, OfBlockPointer, Unqualified);
7547 if (paramType.isNull())
7548 return QualType();
7549
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007550 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007551 paramType = paramType.getUnqualifiedType();
7552
7553 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007554 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007555 lParamType = lParamType.getUnqualifiedType();
7556 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007557 }
Alp Toker601b22c2014-01-21 23:35:24 +00007558
7559 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007560 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007561 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007562 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007563 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007564
Eli Friedman47f77112008-08-22 00:56:42 +00007565 if (allLTypes) return lhs;
7566 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007567
7568 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7569 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007570 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007571 }
7572
7573 if (lproto) allRTypes = false;
7574 if (rproto) allLTypes = false;
7575
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007576 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007577 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007578 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007579 if (proto->isVariadic()) return QualType();
7580 // Check that the types are compatible with the types that
7581 // would result from default argument promotions (C99 6.7.5.3p15).
7582 // The only types actually affected are promotable integer
7583 // types and floats, which would be passed as a different
7584 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007585 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7586 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007587
Eli Friedman448ce402012-08-30 00:44:15 +00007588 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007589 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007590 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7591 paramTy = Enum->getDecl()->getIntegerType();
7592 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007593 return QualType();
7594 }
Alp Toker601b22c2014-01-21 23:35:24 +00007595
7596 if (paramTy->isPromotableIntegerType() ||
7597 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007598 return QualType();
7599 }
7600
7601 if (allLTypes) return lhs;
7602 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007603
7604 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7605 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007606 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007607 }
7608
7609 if (allLTypes) return lhs;
7610 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007611 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007612}
7613
John McCall433c2e62013-03-21 00:10:07 +00007614/// Given that we have an enum type and a non-enum type, try to merge them.
7615static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7616 QualType other, bool isBlockReturnType) {
7617 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7618 // a signed integer type, or an unsigned integer type.
7619 // Compatibility is based on the underlying type, not the promotion
7620 // type.
7621 QualType underlyingType = ET->getDecl()->getIntegerType();
7622 if (underlyingType.isNull()) return QualType();
7623 if (Context.hasSameType(underlyingType, other))
7624 return other;
7625
7626 // In block return types, we're more permissive and accept any
7627 // integral type of the same size.
7628 if (isBlockReturnType && other->isIntegerType() &&
7629 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7630 return other;
7631
7632 return QualType();
7633}
7634
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007635QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007636 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007637 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007638 // C++ [expr]: If an expression initially has the type "reference to T", the
7639 // type is adjusted to "T" prior to any further analysis, the expression
7640 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007641 // expression is an lvalue unless the reference is an rvalue reference and
7642 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007643 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7644 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007645
7646 if (Unqualified) {
7647 LHS = LHS.getUnqualifiedType();
7648 RHS = RHS.getUnqualifiedType();
7649 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007650
Eli Friedman47f77112008-08-22 00:56:42 +00007651 QualType LHSCan = getCanonicalType(LHS),
7652 RHSCan = getCanonicalType(RHS);
7653
7654 // If two types are identical, they are compatible.
7655 if (LHSCan == RHSCan)
7656 return LHS;
7657
John McCall8ccfcb52009-09-24 19:53:00 +00007658 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007659 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7660 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007661 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007662 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00007663 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007664 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7665 return QualType();
7666 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7667 return LHS;
7668 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7669 return RHS;
7670 }
John McCall8ccfcb52009-09-24 19:53:00 +00007671 // If any of these qualifiers are different, we have a type
7672 // mismatch.
7673 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007674 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7675 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007676 return QualType();
7677
7678 // Exactly one GC qualifier difference is allowed: __strong is
7679 // okay if the other type has no GC qualifier but is an Objective
7680 // C object pointer (i.e. implicitly strong by default). We fix
7681 // this by pretending that the unqualified type was actually
7682 // qualified __strong.
7683 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7684 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7685 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7686
7687 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7688 return QualType();
7689
7690 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7691 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7692 }
7693 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7694 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7695 }
Eli Friedman47f77112008-08-22 00:56:42 +00007696 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007697 }
7698
7699 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007700
Eli Friedmandcca6332009-06-01 01:22:52 +00007701 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7702 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007703
Chris Lattnerfd652912008-01-14 05:45:46 +00007704 // We want to consider the two function types to be the same for these
7705 // comparisons, just force one to the other.
7706 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7707 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007708
7709 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007710 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7711 LHSClass = Type::ConstantArray;
7712 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7713 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007714
John McCall8b07ec22010-05-15 11:32:37 +00007715 // ObjCInterfaces are just specialized ObjCObjects.
7716 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7717 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7718
Nate Begemance4d7fc2008-04-18 23:10:10 +00007719 // Canonicalize ExtVector -> Vector.
7720 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7721 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007722
Chris Lattner95554662008-04-07 05:43:21 +00007723 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007724 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007725 // Note that we only have special rules for turning block enum
7726 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007727 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007728 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007729 }
John McCall9dd450b2009-09-21 23:43:11 +00007730 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007731 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007732 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007733 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007734 if (OfBlockPointer && !BlockReturnType) {
7735 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7736 return LHS;
7737 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7738 return RHS;
7739 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007740
Eli Friedman47f77112008-08-22 00:56:42 +00007741 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007742 }
Eli Friedman47f77112008-08-22 00:56:42 +00007743
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007744 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007745 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007746#define TYPE(Class, Base)
7747#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007748#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007749#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7750#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7751#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007752 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007753
Richard Smith27d807c2013-04-30 13:56:41 +00007754 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007755 case Type::LValueReference:
7756 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007757 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007758 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007759
John McCall8b07ec22010-05-15 11:32:37 +00007760 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007761 case Type::IncompleteArray:
7762 case Type::VariableArray:
7763 case Type::FunctionProto:
7764 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007765 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007766
Chris Lattnerfd652912008-01-14 05:45:46 +00007767 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007768 {
7769 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007770 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7771 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007772 if (Unqualified) {
7773 LHSPointee = LHSPointee.getUnqualifiedType();
7774 RHSPointee = RHSPointee.getUnqualifiedType();
7775 }
7776 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7777 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007778 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007779 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007780 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007781 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007782 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007783 return getPointerType(ResultType);
7784 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007785 case Type::BlockPointer:
7786 {
7787 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007788 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7789 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007790 if (Unqualified) {
7791 LHSPointee = LHSPointee.getUnqualifiedType();
7792 RHSPointee = RHSPointee.getUnqualifiedType();
7793 }
7794 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7795 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007796 if (ResultType.isNull()) return QualType();
7797 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7798 return LHS;
7799 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7800 return RHS;
7801 return getBlockPointerType(ResultType);
7802 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007803 case Type::Atomic:
7804 {
7805 // Merge two pointer types, while trying to preserve typedef info
7806 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7807 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7808 if (Unqualified) {
7809 LHSValue = LHSValue.getUnqualifiedType();
7810 RHSValue = RHSValue.getUnqualifiedType();
7811 }
7812 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7813 Unqualified);
7814 if (ResultType.isNull()) return QualType();
7815 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7816 return LHS;
7817 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7818 return RHS;
7819 return getAtomicType(ResultType);
7820 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007821 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007822 {
7823 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7824 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7825 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7826 return QualType();
7827
7828 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7829 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007830 if (Unqualified) {
7831 LHSElem = LHSElem.getUnqualifiedType();
7832 RHSElem = RHSElem.getUnqualifiedType();
7833 }
7834
7835 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007836 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007837 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7838 return LHS;
7839 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7840 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007841 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7842 ArrayType::ArraySizeModifier(), 0);
7843 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7844 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007845 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7846 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007847 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7848 return LHS;
7849 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7850 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007851 if (LVAT) {
7852 // FIXME: This isn't correct! But tricky to implement because
7853 // the array's size has to be the size of LHS, but the type
7854 // has to be different.
7855 return LHS;
7856 }
7857 if (RVAT) {
7858 // FIXME: This isn't correct! But tricky to implement because
7859 // the array's size has to be the size of RHS, but the type
7860 // has to be different.
7861 return RHS;
7862 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007863 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7864 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007865 return getIncompleteArrayType(ResultType,
7866 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007867 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007868 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007869 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007870 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007871 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007872 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007873 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007874 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007875 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007876 case Type::Complex:
7877 // Distinct complex types are incompatible.
7878 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007879 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007880 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007881 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7882 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007883 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007884 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007885 case Type::ObjCObject: {
7886 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007887 // FIXME: This should be type compatibility, e.g. whether
7888 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007889 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7890 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7891 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007892 return LHS;
7893
Eli Friedman47f77112008-08-22 00:56:42 +00007894 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007895 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007896 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007897 if (OfBlockPointer) {
7898 if (canAssignObjCInterfacesInBlockPointer(
7899 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007900 RHS->getAs<ObjCObjectPointerType>(),
7901 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007902 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007903 return QualType();
7904 }
John McCall9dd450b2009-09-21 23:43:11 +00007905 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7906 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007907 return LHS;
7908
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007909 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007910 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00007911 case Type::Pipe:
7912 {
7913 // Merge two pointer types, while trying to preserve typedef info
7914 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7915 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7916 if (Unqualified) {
7917 LHSValue = LHSValue.getUnqualifiedType();
7918 RHSValue = RHSValue.getUnqualifiedType();
7919 }
7920 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7921 Unqualified);
7922 if (ResultType.isNull()) return QualType();
7923 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7924 return LHS;
7925 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7926 return RHS;
7927 return getPipeType(ResultType);
7928 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007929 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007930
David Blaikie8a40f702012-01-17 06:56:22 +00007931 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007932}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007933
John McCall18afab72016-03-01 00:49:02 +00007934bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7935 const FunctionProtoType *firstFnType,
7936 const FunctionProtoType *secondFnType) {
7937 // Fast path: if the first type doesn't have ext parameter infos,
7938 // we match if and only if they second type also doesn't have them.
7939 if (!firstFnType->hasExtParameterInfos())
7940 return !secondFnType->hasExtParameterInfos();
7941
7942 // Otherwise, we can only match if the second type has them.
7943 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007944 return false;
John McCall18afab72016-03-01 00:49:02 +00007945
7946 auto firstEPI = firstFnType->getExtParameterInfos();
7947 auto secondEPI = secondFnType->getExtParameterInfos();
7948 assert(firstEPI.size() == secondEPI.size());
7949
7950 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
7951 if (firstEPI[i] != secondEPI[i])
7952 return false;
7953 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007954 return true;
7955}
7956
Chandler Carruth21c90602015-12-30 03:24:14 +00007957void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7958 ObjCLayouts[CD] = nullptr;
7959}
7960
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007961/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7962/// 'RHS' attributes and returns the merged version; including for function
7963/// return types.
7964QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7965 QualType LHSCan = getCanonicalType(LHS),
7966 RHSCan = getCanonicalType(RHS);
7967 // If two types are identical, they are compatible.
7968 if (LHSCan == RHSCan)
7969 return LHS;
7970 if (RHSCan->isFunctionType()) {
7971 if (!LHSCan->isFunctionType())
7972 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007973 QualType OldReturnType =
7974 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007975 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007976 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007977 QualType ResReturnType =
7978 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7979 if (ResReturnType.isNull())
7980 return QualType();
7981 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7982 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7983 // In either case, use OldReturnType to build the new function type.
7984 const FunctionType *F = LHS->getAs<FunctionType>();
7985 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007986 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7987 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007988 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007989 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007990 return ResultType;
7991 }
7992 }
7993 return QualType();
7994 }
7995
7996 // If the qualifiers are different, the types can still be merged.
7997 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7998 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7999 if (LQuals != RQuals) {
8000 // If any of these qualifiers are different, we have a type mismatch.
8001 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8002 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8003 return QualType();
8004
8005 // Exactly one GC qualifier difference is allowed: __strong is
8006 // okay if the other type has no GC qualifier but is an Objective
8007 // C object pointer (i.e. implicitly strong by default). We fix
8008 // this by pretending that the unqualified type was actually
8009 // qualified __strong.
8010 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8011 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8012 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8013
8014 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8015 return QualType();
8016
8017 if (GC_L == Qualifiers::Strong)
8018 return LHS;
8019 if (GC_R == Qualifiers::Strong)
8020 return RHS;
8021 return QualType();
8022 }
8023
8024 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8025 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8026 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8027 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8028 if (ResQT == LHSBaseQT)
8029 return LHS;
8030 if (ResQT == RHSBaseQT)
8031 return RHS;
8032 }
8033 return QualType();
8034}
8035
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008036//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008037// Integer Predicates
8038//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008039
Jay Foad39c79802011-01-12 09:06:06 +00008040unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008041 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008042 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008043 if (T->isBooleanType())
8044 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008045 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008046 return (unsigned)getTypeSize(T);
8047}
8048
Abramo Bagnara13640492012-09-09 10:21:24 +00008049QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008050 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008051
8052 // Turn <4 x signed int> -> <4 x unsigned int>
8053 if (const VectorType *VTy = T->getAs<VectorType>())
8054 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008055 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008056
8057 // For enums, we return the unsigned version of the base type.
8058 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008059 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008060
8061 const BuiltinType *BTy = T->getAs<BuiltinType>();
8062 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008063 switch (BTy->getKind()) {
8064 case BuiltinType::Char_S:
8065 case BuiltinType::SChar:
8066 return UnsignedCharTy;
8067 case BuiltinType::Short:
8068 return UnsignedShortTy;
8069 case BuiltinType::Int:
8070 return UnsignedIntTy;
8071 case BuiltinType::Long:
8072 return UnsignedLongTy;
8073 case BuiltinType::LongLong:
8074 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008075 case BuiltinType::Int128:
8076 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008077 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008078 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008079 }
8080}
8081
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008082ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008083
Richard Smith1fa5d642013-05-11 05:45:24 +00008084void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8085 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008086
8087//===----------------------------------------------------------------------===//
8088// Builtin Type Computation
8089//===----------------------------------------------------------------------===//
8090
8091/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008092/// pointer over the consumed characters. This returns the resultant type. If
8093/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8094/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8095/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008096///
8097/// RequiresICE is filled in on return to indicate whether the value is required
8098/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008099static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008100 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008101 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008102 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008103 // Modifiers.
8104 int HowLong = 0;
8105 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008106 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008107
Chris Lattnerdc226c22010-10-01 22:42:38 +00008108 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008109 bool Done = false;
8110 while (!Done) {
8111 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008112 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008113 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008114 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008115 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008116 case 'S':
8117 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8118 assert(!Signed && "Can't use 'S' modifier multiple times!");
8119 Signed = true;
8120 break;
8121 case 'U':
8122 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008123 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008124 Unsigned = true;
8125 break;
8126 case 'L':
8127 assert(HowLong <= 2 && "Can't have LLLL modifier");
8128 ++HowLong;
8129 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008130 case 'W':
8131 // This modifier represents int64 type.
8132 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8133 switch (Context.getTargetInfo().getInt64Type()) {
8134 default:
8135 llvm_unreachable("Unexpected integer type");
8136 case TargetInfo::SignedLong:
8137 HowLong = 1;
8138 break;
8139 case TargetInfo::SignedLongLong:
8140 HowLong = 2;
8141 break;
8142 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008143 }
8144 }
8145
8146 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008147
Chris Lattnerecd79c62009-06-14 00:45:47 +00008148 // Read the base type.
8149 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008150 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008151 case 'v':
8152 assert(HowLong == 0 && !Signed && !Unsigned &&
8153 "Bad modifiers used with 'v'!");
8154 Type = Context.VoidTy;
8155 break;
Jack Carter24bef982013-08-15 15:16:57 +00008156 case 'h':
8157 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008158 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008159 Type = Context.HalfTy;
8160 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008161 case 'f':
8162 assert(HowLong == 0 && !Signed && !Unsigned &&
8163 "Bad modifiers used with 'f'!");
8164 Type = Context.FloatTy;
8165 break;
8166 case 'd':
8167 assert(HowLong < 2 && !Signed && !Unsigned &&
8168 "Bad modifiers used with 'd'!");
8169 if (HowLong)
8170 Type = Context.LongDoubleTy;
8171 else
8172 Type = Context.DoubleTy;
8173 break;
8174 case 's':
8175 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8176 if (Unsigned)
8177 Type = Context.UnsignedShortTy;
8178 else
8179 Type = Context.ShortTy;
8180 break;
8181 case 'i':
8182 if (HowLong == 3)
8183 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8184 else if (HowLong == 2)
8185 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8186 else if (HowLong == 1)
8187 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8188 else
8189 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8190 break;
8191 case 'c':
8192 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8193 if (Signed)
8194 Type = Context.SignedCharTy;
8195 else if (Unsigned)
8196 Type = Context.UnsignedCharTy;
8197 else
8198 Type = Context.CharTy;
8199 break;
8200 case 'b': // boolean
8201 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8202 Type = Context.BoolTy;
8203 break;
8204 case 'z': // size_t.
8205 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8206 Type = Context.getSizeType();
8207 break;
8208 case 'F':
8209 Type = Context.getCFConstantStringType();
8210 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008211 case 'G':
8212 Type = Context.getObjCIdType();
8213 break;
8214 case 'H':
8215 Type = Context.getObjCSelType();
8216 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008217 case 'M':
8218 Type = Context.getObjCSuperType();
8219 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008220 case 'a':
8221 Type = Context.getBuiltinVaListType();
8222 assert(!Type.isNull() && "builtin va list type not initialized!");
8223 break;
8224 case 'A':
8225 // This is a "reference" to a va_list; however, what exactly
8226 // this means depends on how va_list is defined. There are two
8227 // different kinds of va_list: ones passed by value, and ones
8228 // passed by reference. An example of a by-value va_list is
8229 // x86, where va_list is a char*. An example of by-ref va_list
8230 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8231 // we want this argument to be a char*&; for x86-64, we want
8232 // it to be a __va_list_tag*.
8233 Type = Context.getBuiltinVaListType();
8234 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008235 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008236 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008237 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008238 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008239 break;
8240 case 'V': {
8241 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008242 unsigned NumElements = strtoul(Str, &End, 10);
8243 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008244 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008245
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008246 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8247 RequiresICE, false);
8248 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008249
8250 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008251 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008252 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008253 break;
8254 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008255 case 'E': {
8256 char *End;
8257
8258 unsigned NumElements = strtoul(Str, &End, 10);
8259 assert(End != Str && "Missing vector size");
8260
8261 Str = End;
8262
8263 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8264 false);
8265 Type = Context.getExtVectorType(ElementType, NumElements);
8266 break;
8267 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008268 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008269 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8270 false);
8271 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008272 Type = Context.getComplexType(ElementType);
8273 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008274 }
8275 case 'Y' : {
8276 Type = Context.getPointerDiffType();
8277 break;
8278 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008279 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008280 Type = Context.getFILEType();
8281 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008282 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008283 return QualType();
8284 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008285 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008286 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008287 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008288 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008289 else
8290 Type = Context.getjmp_bufType();
8291
Mike Stump2adb4da2009-07-28 23:47:15 +00008292 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008293 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008294 return QualType();
8295 }
8296 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008297 case 'K':
8298 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8299 Type = Context.getucontext_tType();
8300
8301 if (Type.isNull()) {
8302 Error = ASTContext::GE_Missing_ucontext;
8303 return QualType();
8304 }
8305 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008306 case 'p':
8307 Type = Context.getProcessIDType();
8308 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008309 }
Mike Stump11289f42009-09-09 15:08:12 +00008310
Chris Lattnerdc226c22010-10-01 22:42:38 +00008311 // If there are modifiers and if we're allowed to parse them, go for it.
8312 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008313 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008314 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008315 default: Done = true; --Str; break;
8316 case '*':
8317 case '&': {
8318 // Both pointers and references can have their pointee types
8319 // qualified with an address space.
8320 char *End;
8321 unsigned AddrSpace = strtoul(Str, &End, 10);
8322 if (End != Str && AddrSpace != 0) {
8323 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8324 Str = End;
8325 }
8326 if (c == '*')
8327 Type = Context.getPointerType(Type);
8328 else
8329 Type = Context.getLValueReferenceType(Type);
8330 break;
8331 }
8332 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8333 case 'C':
8334 Type = Type.withConst();
8335 break;
8336 case 'D':
8337 Type = Context.getVolatileType(Type);
8338 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008339 case 'R':
8340 Type = Type.withRestrict();
8341 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008342 }
8343 }
Chris Lattner84733392010-10-01 07:13:18 +00008344
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008345 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008346 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008347
Chris Lattnerecd79c62009-06-14 00:45:47 +00008348 return Type;
8349}
8350
8351/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008352QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008353 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008354 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008355 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008356
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008357 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008358
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008359 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008360 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008361 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8362 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008363 if (Error != GE_None)
8364 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008365
8366 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8367
Chris Lattnerecd79c62009-06-14 00:45:47 +00008368 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008369 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008370 if (Error != GE_None)
8371 return QualType();
8372
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008373 // If this argument is required to be an IntegerConstantExpression and the
8374 // caller cares, fill in the bitmask we return.
8375 if (RequiresICE && IntegerConstantArgs)
8376 *IntegerConstantArgs |= 1 << ArgTypes.size();
8377
Chris Lattnerecd79c62009-06-14 00:45:47 +00008378 // Do array -> pointer decay. The builtin should use the decayed type.
8379 if (Ty->isArrayType())
8380 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008381
Chris Lattnerecd79c62009-06-14 00:45:47 +00008382 ArgTypes.push_back(Ty);
8383 }
8384
David Majnemerba3e5ec2015-03-13 18:26:17 +00008385 if (Id == Builtin::BI__GetExceptionInfo)
8386 return QualType();
8387
Chris Lattnerecd79c62009-06-14 00:45:47 +00008388 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8389 "'.' should only occur at end of builtin type list!");
8390
Reid Kleckner78af0702013-08-27 23:08:25 +00008391 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008392 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8393
8394 bool Variadic = (TypeStr[0] == '.');
8395
8396 // We really shouldn't be making a no-proto type here, especially in C++.
8397 if (ArgTypes.empty() && Variadic)
8398 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008399
John McCalldb40c7f2010-12-14 08:05:40 +00008400 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008401 EPI.ExtInfo = EI;
8402 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008403
Jordan Rose5c382722013-03-08 21:51:21 +00008404 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008405}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008406
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008407static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8408 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008409 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008410 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008411
Rafael Espindola3ae00052013-05-13 00:12:11 +00008412 GVALinkage External = GVA_StrongExternal;
8413 switch (FD->getTemplateSpecializationKind()) {
8414 case TSK_Undeclared:
8415 case TSK_ExplicitSpecialization:
8416 External = GVA_StrongExternal;
8417 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008418
Rafael Espindola3ae00052013-05-13 00:12:11 +00008419 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008420 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008421
David Majnemerc3d07332014-05-15 06:25:57 +00008422 // C++11 [temp.explicit]p10:
8423 // [ Note: The intent is that an inline function that is the subject of
8424 // an explicit instantiation declaration will still be implicitly
8425 // instantiated when used so that the body can be considered for
8426 // inlining, but that no out-of-line copy of the inline function would be
8427 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008428 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008429 return GVA_AvailableExternally;
8430
Rafael Espindola3ae00052013-05-13 00:12:11 +00008431 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008432 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008433 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008434 }
8435
8436 if (!FD->isInlined())
8437 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008438
David Majnemer3f021502015-10-08 04:53:31 +00008439 if ((!Context.getLangOpts().CPlusPlus &&
8440 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008441 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008442 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008443 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8444
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008445 // GNU or C99 inline semantics. Determine whether this symbol should be
8446 // externally visible.
8447 if (FD->isInlineDefinitionExternallyVisible())
8448 return External;
8449
8450 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008451 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008452 }
8453
David Majnemer54e3ba52014-04-02 23:17:29 +00008454 // Functions specified with extern and inline in -fms-compatibility mode
8455 // forcibly get emitted. While the body of the function cannot be later
8456 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008457 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008458 return GVA_StrongODR;
8459
David Majnemer27d69db2014-04-28 22:17:59 +00008460 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008461}
8462
Artem Belevichca2b9512016-05-02 20:30:03 +00008463static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8464 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008465 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8466 // dllexport/dllimport on inline functions.
8467 if (D->hasAttr<DLLImportAttr>()) {
8468 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8469 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008470 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008471 if (L == GVA_DiscardableODR)
8472 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008473 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8474 D->hasAttr<CUDAGlobalAttr>()) {
8475 // Device-side functions with __global__ attribute must always be
8476 // visible externally so they can be launched from host.
8477 if (L == GVA_DiscardableODR || L == GVA_Internal)
8478 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008479 }
8480 return L;
8481}
8482
8483GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008484 return adjustGVALinkageForAttributes(
8485 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008486}
8487
8488static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8489 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008490 if (!VD->isExternallyVisible())
8491 return GVA_Internal;
8492
David Majnemer27d69db2014-04-28 22:17:59 +00008493 if (VD->isStaticLocal()) {
8494 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8495 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8496 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8497 LexicalContext = LexicalContext->getLexicalParent();
8498
Richard Smith9e2341d2015-03-23 03:25:59 +00008499 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008500 // enclosing function.
8501 if (LexicalContext)
8502 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008503 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008504
8505 // GVA_StrongODR function linkage is stronger than what we need,
8506 // downgrade to GVA_DiscardableODR.
8507 // This allows us to discard the variable if we never end up needing it.
8508 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8509 : StaticLocalLinkage;
8510 }
8511
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008512 // MSVC treats in-class initialized static data members as definitions.
8513 // By giving them non-strong linkage, out-of-line definitions won't
8514 // cause link errors.
8515 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8516 return GVA_DiscardableODR;
8517
Richard Smithd9b90092016-07-02 01:32:16 +00008518 // Most non-template variables have strong linkage; inline variables are
8519 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8520 GVALinkage StrongLinkage;
8521 switch (Context.getInlineVariableDefinitionKind(VD)) {
8522 case ASTContext::InlineVariableDefinitionKind::None:
8523 StrongLinkage = GVA_StrongExternal;
8524 break;
8525 case ASTContext::InlineVariableDefinitionKind::Weak:
8526 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008527 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008528 break;
8529 case ASTContext::InlineVariableDefinitionKind::Strong:
8530 StrongLinkage = GVA_StrongODR;
8531 break;
8532 }
Richard Smith62f19e72016-06-25 00:15:56 +00008533
Richard Smith8809a0c2013-09-27 20:14:12 +00008534 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008535 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008536 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008537
David Majnemer6d1780c2015-07-17 23:36:49 +00008538 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008539 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8540 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008541 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008542 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008543
Rafael Espindola3ae00052013-05-13 00:12:11 +00008544 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008545 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008546
David Majnemer27d69db2014-04-28 22:17:59 +00008547 case TSK_ExplicitInstantiationDeclaration:
8548 return GVA_AvailableExternally;
8549
Rafael Espindola3ae00052013-05-13 00:12:11 +00008550 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008551 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008552 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008553
8554 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008555}
8556
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008557GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008558 return adjustGVALinkageForAttributes(
8559 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008560}
8561
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008562bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008563 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8564 if (!VD->isFileVarDecl())
8565 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008566 // Global named register variables (GNU extension) are never emitted.
8567 if (VD->getStorageClass() == SC_Register)
8568 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008569 if (VD->getDescribedVarTemplate() ||
8570 isa<VarTemplatePartialSpecializationDecl>(VD))
8571 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008572 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8573 // We never need to emit an uninstantiated function template.
8574 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8575 return false;
Nico Weber66220292016-03-02 17:28:48 +00008576 } else if (isa<PragmaCommentDecl>(D))
8577 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008578 else if (isa<OMPThreadPrivateDecl>(D) ||
8579 D->hasAttr<OMPDeclareTargetDeclAttr>())
8580 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008581 else if (isa<PragmaDetectMismatchDecl>(D))
8582 return true;
Nico Weber66220292016-03-02 17:28:48 +00008583 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008584 return !D->getDeclContext()->isDependentContext();
8585 else if (isa<OMPDeclareReductionDecl>(D))
8586 return !D->getDeclContext()->isDependentContext();
Alexey Bataev97720002014-11-11 04:05:39 +00008587 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008588 return false;
8589
8590 // If this is a member of a class template, we do not need to emit it.
8591 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008592 return false;
8593
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008594 // Weak references don't produce any output by themselves.
8595 if (D->hasAttr<WeakRefAttr>())
8596 return false;
8597
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008598 // Aliases and used decls are required.
8599 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8600 return true;
8601
8602 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8603 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008604 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008605 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008606
8607 // Constructors and destructors are required.
8608 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8609 return true;
8610
John McCall6bd2a892013-01-25 22:31:03 +00008611 // The key function for a class is required. This rule only comes
8612 // into play when inline functions can be key functions, though.
8613 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8614 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8615 const CXXRecordDecl *RD = MD->getParent();
8616 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8617 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8618 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8619 return true;
8620 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008621 }
8622 }
8623
8624 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8625
8626 // static, static inline, always_inline, and extern inline functions can
8627 // always be deferred. Normal inline functions can be deferred in C99/C++.
8628 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008629 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8630 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008631 return false;
8632 return true;
8633 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008634
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008635 const VarDecl *VD = cast<VarDecl>(D);
8636 assert(VD->isFileVarDecl() && "Expected file scoped var");
8637
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008638 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8639 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008640 return false;
8641
Richard Smitha0e5e542012-11-12 21:38:00 +00008642 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008643 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008644 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8645 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008646 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008647
Richard Smitha0e5e542012-11-12 21:38:00 +00008648 // Variables that have destruction with side-effects are required.
8649 if (VD->getType().isDestructedType())
8650 return true;
8651
8652 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008653 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8654 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008655 return true;
8656
8657 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008658}
Charles Davis53c59df2010-08-16 03:33:14 +00008659
Reid Kleckner78af0702013-08-27 23:08:25 +00008660CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8661 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008662 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008663 if (IsCXXMethod)
8664 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008665
Alexey Bataeva7547182016-05-18 09:06:38 +00008666 switch (LangOpts.getDefaultCallingConv()) {
8667 case LangOptions::DCC_None:
8668 break;
8669 case LangOptions::DCC_CDecl:
8670 return CC_C;
8671 case LangOptions::DCC_FastCall:
8672 if (getTargetInfo().hasFeature("sse2"))
8673 return CC_X86FastCall;
8674 break;
8675 case LangOptions::DCC_StdCall:
8676 if (!IsVariadic)
8677 return CC_X86StdCall;
8678 break;
8679 case LangOptions::DCC_VectorCall:
8680 // __vectorcall cannot be applied to variadic functions.
8681 if (!IsVariadic)
8682 return CC_X86VectorCall;
8683 break;
8684 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008685 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008686}
8687
Jay Foad39c79802011-01-12 09:06:06 +00008688bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008689 // Pass through to the C++ ABI object
8690 return ABI->isNearlyEmpty(RD);
8691}
8692
Reid Kleckner96f8f932014-02-05 17:27:08 +00008693VTableContextBase *ASTContext::getVTableContext() {
8694 if (!VTContext.get()) {
8695 if (Target->getCXXABI().isMicrosoft())
8696 VTContext.reset(new MicrosoftVTableContext(*this));
8697 else
8698 VTContext.reset(new ItaniumVTableContext(*this));
8699 }
8700 return VTContext.get();
8701}
8702
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008703MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008704 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008705 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008706 case TargetCXXABI::GenericItanium:
8707 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008708 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008709 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008710 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008711 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008712 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008713 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008714 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008715 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008716 }
David Blaikie83d382b2011-09-23 05:06:16 +00008717 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008718}
8719
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008720CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008721
8722size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008723 return ASTRecordLayouts.getMemorySize() +
8724 llvm::capacity_in_bytes(ObjCLayouts) +
8725 llvm::capacity_in_bytes(KeyFunctions) +
8726 llvm::capacity_in_bytes(ObjCImpls) +
8727 llvm::capacity_in_bytes(BlockVarCopyInits) +
8728 llvm::capacity_in_bytes(DeclAttrs) +
8729 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8730 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8731 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8732 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8733 llvm::capacity_in_bytes(OverriddenMethods) +
8734 llvm::capacity_in_bytes(Types) +
8735 llvm::capacity_in_bytes(VariableArrayTypes) +
8736 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008737}
Ted Kremenek540017e2011-10-06 05:00:56 +00008738
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008739/// getIntTypeForBitwidth -
8740/// sets integer QualTy according to specified details:
8741/// bitwidth, signed/unsigned.
8742/// Returns empty type if there is no appropriate target types.
8743QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8744 unsigned Signed) const {
8745 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8746 CanQualType QualTy = getFromTargetType(Ty);
8747 if (!QualTy && DestWidth == 128)
8748 return Signed ? Int128Ty : UnsignedInt128Ty;
8749 return QualTy;
8750}
8751
8752/// getRealTypeForBitwidth -
8753/// sets floating point QualTy according to specified bitwidth.
8754/// Returns empty type if there is no appropriate target types.
8755QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8756 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8757 switch (Ty) {
8758 case TargetInfo::Float:
8759 return FloatTy;
8760 case TargetInfo::Double:
8761 return DoubleTy;
8762 case TargetInfo::LongDouble:
8763 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00008764 case TargetInfo::Float128:
8765 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008766 case TargetInfo::NoFloat:
8767 return QualType();
8768 }
8769
8770 llvm_unreachable("Unhandled TargetInfo::RealType value");
8771}
8772
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008773void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8774 if (Number > 1)
8775 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008776}
8777
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008778unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008779 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008780 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008781}
8782
David Majnemer2206bf52014-03-05 08:57:59 +00008783void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8784 if (Number > 1)
8785 StaticLocalNumbers[VD] = Number;
8786}
8787
8788unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008789 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00008790 return I != StaticLocalNumbers.end() ? I->second : 1;
8791}
8792
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008793MangleNumberingContext &
8794ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008795 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8796 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8797 if (!MCtx)
8798 MCtx = createMangleNumberingContext();
8799 return *MCtx;
8800}
8801
8802MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8803 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008804}
8805
David Majnemere7a818f2015-03-06 18:53:55 +00008806const CXXConstructorDecl *
8807ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8808 return ABI->getCopyConstructorForExceptionObject(
8809 cast<CXXRecordDecl>(RD->getFirstDecl()));
8810}
8811
8812void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8813 CXXConstructorDecl *CD) {
8814 return ABI->addCopyConstructorForExceptionObject(
8815 cast<CXXRecordDecl>(RD->getFirstDecl()),
8816 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8817}
8818
David Majnemerdfa6d202015-03-11 18:36:39 +00008819void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8820 unsigned ParmIdx, Expr *DAE) {
8821 ABI->addDefaultArgExprForConstructor(
8822 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8823}
8824
8825Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8826 unsigned ParmIdx) {
8827 return ABI->getDefaultArgExprForConstructor(
8828 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8829}
8830
David Majnemer00350522015-08-31 18:48:39 +00008831void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8832 TypedefNameDecl *DD) {
8833 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8834}
8835
8836TypedefNameDecl *
8837ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8838 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8839}
8840
8841void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8842 DeclaratorDecl *DD) {
8843 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8844}
8845
8846DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8847 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8848}
8849
Ted Kremenek540017e2011-10-06 05:00:56 +00008850void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8851 ParamIndices[D] = index;
8852}
8853
8854unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8855 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8856 assert(I != ParamIndices.end() &&
8857 "ParmIndices lacks entry set by ParmVarDecl");
8858 return I->second;
8859}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008860
Richard Smithe6c01442013-06-05 00:46:14 +00008861APValue *
8862ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8863 bool MayCreate) {
8864 assert(E && E->getStorageDuration() == SD_Static &&
8865 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008866 if (MayCreate) {
8867 APValue *&MTVI = MaterializedTemporaryValues[E];
8868 if (!MTVI)
8869 MTVI = new (*this) APValue;
8870 return MTVI;
8871 }
Richard Smithe6c01442013-06-05 00:46:14 +00008872
David Majnemer2dcef9e2015-08-13 23:50:15 +00008873 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008874}
8875
Fariborz Jahanian615de762013-05-28 17:37:39 +00008876bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8877 const llvm::Triple &T = getTargetInfo().getTriple();
8878 if (!T.isOSDarwin())
8879 return false;
8880
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008881 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8882 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8883 return false;
8884
Fariborz Jahanian615de762013-05-28 17:37:39 +00008885 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8886 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8887 uint64_t Size = sizeChars.getQuantity();
8888 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8889 unsigned Align = alignChars.getQuantity();
8890 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8891 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8892}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008893
8894namespace {
8895
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008896ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8897 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008898 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008899 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008900 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008901 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008902 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008903}
8904
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008905/// Template specializations to abstract away from pointers and TypeLocs.
8906/// @{
8907template <typename T>
8908ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8909 return ast_type_traits::DynTypedNode::create(*Node);
8910}
8911template <>
8912ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8913 return ast_type_traits::DynTypedNode::create(Node);
8914}
8915template <>
8916ast_type_traits::DynTypedNode
8917createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8918 return ast_type_traits::DynTypedNode::create(Node);
8919}
8920/// @}
8921
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008922 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8923 /// parents as defined by the \c RecursiveASTVisitor.
8924 ///
8925 /// Note that the relationship described here is purely in terms of AST
8926 /// traversal - there are other relationships (for example declaration context)
8927 /// in the AST that are better modeled by special matchers.
8928 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008929 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008930 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008931 public:
8932 /// \brief Builds and returns the translation unit's parent map.
8933 ///
8934 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008935 static std::pair<ASTContext::ParentMapPointers *,
8936 ASTContext::ParentMapOtherNodes *>
8937 buildMap(TranslationUnitDecl &TU) {
8938 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8939 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008940 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008941 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008942 }
8943
8944 private:
8945 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8946
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008947 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8948 ASTContext::ParentMapOtherNodes *OtherParents)
8949 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008950
8951 bool shouldVisitTemplateInstantiations() const {
8952 return true;
8953 }
8954 bool shouldVisitImplicitCode() const {
8955 return true;
8956 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008957
Richard Smith85838722015-11-24 03:09:01 +00008958 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8959 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008960 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00008961 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008962 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008963 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008964 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008965 // FIXME: Currently we add the same parent multiple times, but only
8966 // when no memoization data is available for the type.
8967 // For example when we visit all subexpressions of template
8968 // instantiations; this is suboptimal, but benign: the only way to
8969 // visit those is with hasAncestor / hasParent, and those do not create
8970 // new matches.
8971 // The plan is to enable DynTypedNode to be storable in a map or hash
8972 // map. The main problem there is to implement hash functions /
8973 // comparison operators for all types that DynTypedNode supports that
8974 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008975 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008976 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008977 if (const auto *D = ParentStack.back().get<Decl>())
8978 NodeOrVector = D;
8979 else if (const auto *S = ParentStack.back().get<Stmt>())
8980 NodeOrVector = S;
8981 else
8982 NodeOrVector =
8983 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008984 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008985 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8986 auto *Vector = new ASTContext::ParentVector(
8987 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008988 if (auto *Node =
8989 NodeOrVector
8990 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8991 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008992 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008993 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008994
8995 auto *Vector =
8996 NodeOrVector.template get<ASTContext::ParentVector *>();
8997 // Skip duplicates for types that have memoization data.
8998 // We must check that the type has memoization data before calling
8999 // std::find() because DynTypedNode::operator== can't compare all
9000 // types.
9001 bool Found = ParentStack.back().getMemoizationData() &&
9002 std::find(Vector->begin(), Vector->end(),
9003 ParentStack.back()) != Vector->end();
9004 if (!Found)
9005 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009006 }
9007 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009008 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009009 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009010 ParentStack.pop_back();
9011 return Result;
9012 }
9013
9014 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009015 return TraverseNode(DeclNode, DeclNode,
9016 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009017 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009018 }
9019
9020 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009021 return TraverseNode(StmtNode, StmtNode,
9022 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009023 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009024 }
9025
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009026 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009027 return TraverseNode(
9028 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9029 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9030 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009031 }
9032
9033 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9034 return TraverseNode(
9035 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009036 [&] {
9037 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9038 },
9039 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009040 }
9041
9042 ASTContext::ParentMapPointers *Parents;
9043 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009044 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9045
9046 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9047 };
9048
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009049} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009050
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009051template <typename NodeTy, typename MapTy>
9052static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9053 const MapTy &Map) {
9054 auto I = Map.find(Node);
9055 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009056 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009057 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009058 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009059 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009060 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009061 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009062}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009063
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009064ASTContext::DynTypedNodeList
9065ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9066 if (!PointerParents) {
9067 // We always need to run over the whole translation unit, as
9068 // hasAncestor can escape any subtree.
9069 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9070 PointerParents.reset(Maps.first);
9071 OtherParents.reset(Maps.second);
9072 }
9073 if (Node.getNodeKind().hasPointerIdentity())
9074 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9075 return getDynNodeFromMap(Node, *OtherParents);
9076}
9077
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009078bool
9079ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9080 const ObjCMethodDecl *MethodImpl) {
9081 // No point trying to match an unavailable/deprecated mothod.
9082 if (MethodDecl->hasAttr<UnavailableAttr>()
9083 || MethodDecl->hasAttr<DeprecatedAttr>())
9084 return false;
9085 if (MethodDecl->getObjCDeclQualifier() !=
9086 MethodImpl->getObjCDeclQualifier())
9087 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009088 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009089 return false;
9090
9091 if (MethodDecl->param_size() != MethodImpl->param_size())
9092 return false;
9093
9094 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9095 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9096 EF = MethodDecl->param_end();
9097 IM != EM && IF != EF; ++IM, ++IF) {
9098 const ParmVarDecl *DeclVar = (*IF);
9099 const ParmVarDecl *ImplVar = (*IM);
9100 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9101 return false;
9102 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9103 return false;
9104 }
9105 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9106
9107}
Richard Smith053f6c62014-05-16 23:01:30 +00009108
9109// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9110// doesn't include ASTContext.h
9111template
9112clang::LazyGenerationalUpdatePtr<
9113 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9114clang::LazyGenerationalUpdatePtr<
9115 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9116 const clang::ASTContext &Ctx, Decl *Value);