blob: 4a831d90e64587ca59e4705426fcf232af418c67 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000687 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000689 return CreateMicrosoftCXXABI(*this);
690 }
David Blaikie8a40f702012-01-17 06:56:22 +0000691 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000692}
693
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 const LangOptions &LOpts) {
696 if (LOpts.FakeAddressSpaceMap) {
697 // The fake address space map must have a distinct entry for each
698 // language-specific address space.
699 static const unsigned FakeAddrSpaceMap[] = {
700 1, // opencl_global
701 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000702 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000703 4, // opencl_generic
704 5, // cuda_device
705 6, // cuda_constant
706 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 }
712}
713
David Tweed31d09b02013-09-13 12:04:22 +0000714static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
715 const LangOptions &LangOpts) {
716 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000717 case LangOptions::ASMM_Target:
718 return TI.useAddressSpaceMapMangling();
719 case LangOptions::ASMM_On:
720 return true;
721 case LangOptions::ASMM_Off:
722 return false;
723 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000724 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000725}
726
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000727ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000728 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000729 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
731 DependentTemplateSpecializationTypes(this_()),
732 SubstTemplateTemplateParmPacks(this_()),
733 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
734 UInt128Decl(nullptr), Float128StubDecl(nullptr),
735 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
736 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
739 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
740 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000741 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
742 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000744 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
745 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
746 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
747 Comments(SM), CommentsLoaded(false),
748 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000749 TUDecl = TranslationUnitDecl::Create(*this);
750}
751
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000752ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000753 ReleaseParentMapEntries();
754
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000758
Manuel Klimeka7328992013-06-03 13:51:33 +0000759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
Reid Kleckner588c9372014-02-19 23:44:52 +0000786 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000787}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000788
Manuel Klimek95403e62014-05-21 13:28:59 +0000789void ASTContext::ReleaseParentMapEntries() {
790 if (!AllParents) return;
791 for (const auto &Entry : *AllParents) {
792 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
793 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
794 } else {
795 assert(Entry.second.is<ParentVector *>());
796 delete Entry.second.get<ParentVector *>();
797 }
798 }
799}
800
Douglas Gregor1a809332010-05-23 18:26:36 +0000801void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000802 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000803}
804
Mike Stump11289f42009-09-09 15:08:12 +0000805void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000806ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
807 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000808}
809
Chris Lattner4eb445d2007-01-26 01:27:23 +0000810void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000811 llvm::errs() << "\n*** AST Context Stats:\n";
812 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000813
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000815#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000816#define ABSTRACT_TYPE(Name, Parent)
817#include "clang/AST/TypeNodes.def"
818 0 // Extra
819 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000820
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
822 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000823 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000824 }
825
Douglas Gregora30d0462009-05-26 14:40:08 +0000826 unsigned Idx = 0;
827 unsigned TotalBytes = 0;
828#define TYPE(Name, Parent) \
829 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << " " << counts[Idx] << " " << #Name \
831 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 TotalBytes += counts[Idx] * sizeof(Name##Type); \
833 ++Idx;
834#define ABSTRACT_TYPE(Name, Parent)
835#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chandler Carruth3c147a72011-07-04 05:32:14 +0000837 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
838
Douglas Gregor7454c562010-07-02 20:37:36 +0000839 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000840 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
841 << NumImplicitDefaultConstructors
842 << " implicit default constructors created\n";
843 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
844 << NumImplicitCopyConstructors
845 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000846 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000847 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
848 << NumImplicitMoveConstructors
849 << " implicit move constructors created\n";
850 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
851 << NumImplicitCopyAssignmentOperators
852 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000853 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000854 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
855 << NumImplicitMoveAssignmentOperators
856 << " implicit move assignment operators created\n";
857 llvm::errs() << NumImplicitDestructorsDeclared << "/"
858 << NumImplicitDestructors
859 << " implicit destructors created\n";
860
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000861 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000862 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000863 ExternalSource->PrintStats();
864 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000865
Douglas Gregor5b11d492010-07-25 17:53:33 +0000866 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000867}
868
Richard Smith42413142015-05-15 20:05:43 +0000869void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
870 bool NotifyListeners) {
871 if (NotifyListeners)
872 if (auto *Listener = getASTMutationListener())
873 Listener->RedefinedHiddenDefinition(ND, M);
874
875 if (getLangOpts().ModulesLocalVisibility)
876 MergedDefModules[ND].push_back(M);
877 else
878 ND->setHidden(false);
879}
880
881void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
882 auto It = MergedDefModules.find(ND);
883 if (It == MergedDefModules.end())
884 return;
885
886 auto &Merged = It->second;
887 llvm::DenseSet<Module*> Found;
888 for (Module *&M : Merged)
889 if (!Found.insert(M).second)
890 M = nullptr;
891 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
892}
893
Richard Smithf19e1272015-03-07 00:04:49 +0000894ExternCContextDecl *ASTContext::getExternCContextDecl() const {
895 if (!ExternCContext)
896 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
897
898 return ExternCContext;
899}
900
Alp Toker2dea15b2013-12-17 01:22:38 +0000901RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
902 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000903 SourceLocation Loc;
904 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000905 if (getLangOpts().CPlusPlus)
906 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
907 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000908 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000909 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
910 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000911 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000912 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
913 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000914 return NewDecl;
915}
916
917TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
918 StringRef Name) const {
919 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
920 TypedefDecl *NewDecl = TypedefDecl::Create(
921 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
922 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
923 NewDecl->setImplicit();
924 return NewDecl;
925}
926
Douglas Gregor801c99d2011-08-12 06:49:56 +0000927TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000928 if (!Int128Decl)
929 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000930 return Int128Decl;
931}
932
933TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 if (!UInt128Decl)
935 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000936 return UInt128Decl;
937}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000938
Nico Webere1687c52013-06-20 21:44:55 +0000939TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000940 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000941 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000942 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000943
Nico Webere1687c52013-06-20 21:44:55 +0000944 return Float128StubDecl;
945}
946
John McCall48f2d582009-10-23 23:03:21 +0000947void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000948 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000949 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000950 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000951}
952
Douglas Gregore8bbc122011-09-02 00:18:52 +0000953void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
954 assert((!this->Target || this->Target == &Target) &&
955 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000956 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000957
Douglas Gregore8bbc122011-09-02 00:18:52 +0000958 this->Target = &Target;
959
960 ABI.reset(createCXXABI(Target));
961 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000962 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963
Chris Lattner970e54e2006-11-12 00:37:36 +0000964 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000965 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000966
Chris Lattner970e54e2006-11-12 00:37:36 +0000967 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000968 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000969 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000970 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000971 InitBuiltinType(CharTy, BuiltinType::Char_S);
972 else
973 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000974 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000975 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
976 InitBuiltinType(ShortTy, BuiltinType::Short);
977 InitBuiltinType(IntTy, BuiltinType::Int);
978 InitBuiltinType(LongTy, BuiltinType::Long);
979 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000980
Chris Lattner970e54e2006-11-12 00:37:36 +0000981 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000982 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
983 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
984 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
985 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
986 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000987
Chris Lattner970e54e2006-11-12 00:37:36 +0000988 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000989 InitBuiltinType(FloatTy, BuiltinType::Float);
990 InitBuiltinType(DoubleTy, BuiltinType::Double);
991 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000992
Chris Lattnerf122cef2009-04-30 02:43:43 +0000993 // GNU extension, 128-bit integers.
994 InitBuiltinType(Int128Ty, BuiltinType::Int128);
995 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
996
Hans Wennborg0d81e012013-05-10 10:08:40 +0000997 // C++ 3.9.1p5
998 if (TargetInfo::isTypeSigned(Target.getWCharType()))
999 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1000 else // -fshort-wchar makes wchar_t be unsigned.
1001 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1002 if (LangOpts.CPlusPlus && LangOpts.WChar)
1003 WideCharTy = WCharTy;
1004 else {
1005 // C99 (or C++ using -fno-wchar).
1006 WideCharTy = getFromTargetType(Target.getWCharType());
1007 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001008
James Molloy36365542012-05-04 10:55:22 +00001009 WIntTy = getFromTargetType(Target.getWIntType());
1010
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001011 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1012 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1013 else // C99
1014 Char16Ty = getFromTargetType(Target.getChar16Type());
1015
1016 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1017 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1018 else // C99
1019 Char32Ty = getFromTargetType(Target.getChar32Type());
1020
Douglas Gregor4619e432008-12-05 23:32:09 +00001021 // Placeholder type for type-dependent expressions whose type is
1022 // completely unknown. No code should ever check a type against
1023 // DependentTy and users should never see it; however, it is here to
1024 // help diagnose failures to properly check for type-dependent
1025 // expressions.
1026 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027
John McCall36e7fe32010-10-12 00:20:44 +00001028 // Placeholder type for functions.
1029 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1030
John McCall0009fcc2011-04-26 20:42:42 +00001031 // Placeholder type for bound members.
1032 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1033
John McCall526ab472011-10-25 17:37:35 +00001034 // Placeholder type for pseudo-objects.
1035 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1036
John McCall31996342011-04-07 08:22:57 +00001037 // "any" type; useful for debugger-like clients.
1038 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1039
John McCall8a6b59a2011-10-17 18:09:15 +00001040 // Placeholder type for unbridged ARC casts.
1041 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1042
Eli Friedman34866c72012-08-31 00:14:07 +00001043 // Placeholder type for builtin functions.
1044 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1045
Chris Lattner970e54e2006-11-12 00:37:36 +00001046 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001047 FloatComplexTy = getComplexType(FloatTy);
1048 DoubleComplexTy = getComplexType(DoubleTy);
1049 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001050
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001051 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001052 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1053 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001054 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001055
1056 if (LangOpts.OpenCL) {
1057 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1058 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1059 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1060 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1061 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1062 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001063
Guy Benyei61054192013-02-07 10:55:47 +00001064 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001065 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001066 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001067
1068 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001069 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1070 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001071
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001072 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001073
1074 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001075
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001076 // void * type
1077 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001078
1079 // nullptr type (C++0x 2.14.7)
1080 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001081
1082 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1083 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001084
1085 // Builtin type used to help define __builtin_va_list.
1086 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001087}
1088
David Blaikie9c902b52011-09-25 23:23:43 +00001089DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001090 return SourceMgr.getDiagnostics();
1091}
1092
Douglas Gregor561eceb2010-08-30 16:49:28 +00001093AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1094 AttrVec *&Result = DeclAttrs[D];
1095 if (!Result) {
1096 void *Mem = Allocate(sizeof(AttrVec));
1097 Result = new (Mem) AttrVec;
1098 }
1099
1100 return *Result;
1101}
1102
1103/// \brief Erase the attributes corresponding to the given declaration.
1104void ASTContext::eraseDeclAttrs(const Decl *D) {
1105 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1106 if (Pos != DeclAttrs.end()) {
1107 Pos->second->~AttrVec();
1108 DeclAttrs.erase(Pos);
1109 }
1110}
1111
Larisse Voufo39a1e502013-08-06 01:03:05 +00001112// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001113MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001114ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001115 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001116 return getTemplateOrSpecializationInfo(Var)
1117 .dyn_cast<MemberSpecializationInfo *>();
1118}
1119
1120ASTContext::TemplateOrSpecializationInfo
1121ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1122 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1123 TemplateOrInstantiation.find(Var);
1124 if (Pos == TemplateOrInstantiation.end())
1125 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001126
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001127 return Pos->second;
1128}
1129
Mike Stump11289f42009-09-09 15:08:12 +00001130void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001131ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001132 TemplateSpecializationKind TSK,
1133 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001134 assert(Inst->isStaticDataMember() && "Not a static data member");
1135 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001136 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1137 Tmpl, TSK, PointOfInstantiation));
1138}
1139
1140void
1141ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1142 TemplateOrSpecializationInfo TSI) {
1143 assert(!TemplateOrInstantiation[Inst] &&
1144 "Already noted what the variable was instantiated from");
1145 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001146}
1147
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001148FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1149 const FunctionDecl *FD){
1150 assert(FD && "Specialization is 0");
1151 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001152 = ClassScopeSpecializationPattern.find(FD);
1153 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001154 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001155
1156 return Pos->second;
1157}
1158
1159void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1160 FunctionDecl *Pattern) {
1161 assert(FD && "Specialization is 0");
1162 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001163 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001164}
1165
John McCalle61f2ba2009-11-18 02:36:19 +00001166NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001167ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001168 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001169 = InstantiatedFromUsingDecl.find(UUD);
1170 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001171 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001172
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001173 return Pos->second;
1174}
1175
1176void
John McCallb96ec562009-12-04 22:46:56 +00001177ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1178 assert((isa<UsingDecl>(Pattern) ||
1179 isa<UnresolvedUsingValueDecl>(Pattern) ||
1180 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1181 "pattern decl is not a using decl");
1182 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1183 InstantiatedFromUsingDecl[Inst] = Pattern;
1184}
1185
1186UsingShadowDecl *
1187ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1188 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1189 = InstantiatedFromUsingShadowDecl.find(Inst);
1190 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001191 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001192
1193 return Pos->second;
1194}
1195
1196void
1197ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1198 UsingShadowDecl *Pattern) {
1199 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1200 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001201}
1202
Anders Carlsson5da84842009-09-01 04:26:58 +00001203FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1204 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1205 = InstantiatedFromUnnamedFieldDecl.find(Field);
1206 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001207 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001208
Anders Carlsson5da84842009-09-01 04:26:58 +00001209 return Pos->second;
1210}
1211
1212void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1213 FieldDecl *Tmpl) {
1214 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1215 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1216 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1217 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001218
Anders Carlsson5da84842009-09-01 04:26:58 +00001219 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1220}
1221
Douglas Gregor832940b2010-03-02 23:58:15 +00001222ASTContext::overridden_cxx_method_iterator
1223ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1224 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001225 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001226 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001227 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001228
1229 return Pos->second.begin();
1230}
1231
1232ASTContext::overridden_cxx_method_iterator
1233ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1234 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001235 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001236 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001237 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001238
1239 return Pos->second.end();
1240}
1241
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001242unsigned
1243ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1244 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001245 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001246 if (Pos == OverriddenMethods.end())
1247 return 0;
1248
1249 return Pos->second.size();
1250}
1251
Douglas Gregor832940b2010-03-02 23:58:15 +00001252void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1253 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001254 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001255 OverriddenMethods[Method].push_back(Overridden);
1256}
1257
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001258void ASTContext::getOverriddenMethods(
1259 const NamedDecl *D,
1260 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001261 assert(D);
1262
1263 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001264 Overridden.append(overridden_methods_begin(CXXMethod),
1265 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001266 return;
1267 }
1268
1269 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1270 if (!Method)
1271 return;
1272
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001273 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1274 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001275 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001276}
1277
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001278void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1279 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1280 assert(!Import->isFromASTFile() && "Non-local import declaration");
1281 if (!FirstLocalImport) {
1282 FirstLocalImport = Import;
1283 LastLocalImport = Import;
1284 return;
1285 }
1286
1287 LastLocalImport->NextLocalImport = Import;
1288 LastLocalImport = Import;
1289}
1290
Chris Lattner53cfe802007-07-18 17:52:12 +00001291//===----------------------------------------------------------------------===//
1292// Type Sizing and Analysis
1293//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001294
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001295/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1296/// scalar floating point type.
1297const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001298 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001299 assert(BT && "Not a floating point type!");
1300 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001301 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001302 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001303 case BuiltinType::Float: return Target->getFloatFormat();
1304 case BuiltinType::Double: return Target->getDoubleFormat();
1305 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001306 }
1307}
1308
Rafael Espindola71eccb32013-08-08 19:53:46 +00001309CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001310 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001311
John McCall94268702010-10-08 18:24:19 +00001312 bool UseAlignAttrOnly = false;
1313 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1314 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001315
John McCall94268702010-10-08 18:24:19 +00001316 // __attribute__((aligned)) can increase or decrease alignment
1317 // *except* on a struct or struct member, where it only increases
1318 // alignment unless 'packed' is also specified.
1319 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001320 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001321 // ignore that possibility; Sema should diagnose it.
1322 if (isa<FieldDecl>(D)) {
1323 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1324 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1325 } else {
1326 UseAlignAttrOnly = true;
1327 }
1328 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001329 else if (isa<FieldDecl>(D))
1330 UseAlignAttrOnly =
1331 D->hasAttr<PackedAttr>() ||
1332 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001333
John McCall4e819612011-01-20 07:57:12 +00001334 // If we're using the align attribute only, just ignore everything
1335 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001336 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001337 // do nothing
1338
John McCall94268702010-10-08 18:24:19 +00001339 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001340 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001341 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001342 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001343 T = RT->getPointeeType();
1344 else
1345 T = getPointerType(RT->getPointeeType());
1346 }
Richard Smithf6d70302014-06-10 23:34:28 +00001347 QualType BaseT = getBaseElementType(T);
1348 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001349 // Adjust alignments of declarations with array type by the
1350 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001351 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001352 unsigned MinWidth = Target->getLargeArrayMinWidth();
1353 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001354 if (isa<VariableArrayType>(arrayType))
1355 Align = std::max(Align, Target->getLargeArrayAlign());
1356 else if (isa<ConstantArrayType>(arrayType) &&
1357 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1358 Align = std::max(Align, Target->getLargeArrayAlign());
1359 }
John McCall33ddac02011-01-19 10:06:00 +00001360 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001361 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001362 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001363 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001364 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1365 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001366 }
John McCall4e819612011-01-20 07:57:12 +00001367
1368 // Fields can be subject to extra alignment constraints, like if
1369 // the field is packed, the struct is packed, or the struct has a
1370 // a max-field-alignment constraint (#pragma pack). So calculate
1371 // the actual alignment of the field within the struct, and then
1372 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001373 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1374 const RecordDecl *Parent = Field->getParent();
1375 // We can only produce a sensible answer if the record is valid.
1376 if (!Parent->isInvalidDecl()) {
1377 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001378
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001379 // Start with the record's overall alignment.
1380 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001381
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001382 // Use the GCD of that and the offset within the record.
1383 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1384 if (Offset > 0) {
1385 // Alignment is always a power of 2, so the GCD will be a power of 2,
1386 // which means we get to do this crazy thing instead of Euclid's.
1387 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1388 if (LowBitOfOffset < FieldAlign)
1389 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1390 }
1391
1392 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001393 }
Charles Davis3fc51072010-02-23 04:52:00 +00001394 }
Chris Lattner68061312009-01-24 21:53:27 +00001395 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001396
Ken Dyckcc56c542011-01-15 18:38:59 +00001397 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001398}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001399
John McCallf1249922012-08-21 04:10:00 +00001400// getTypeInfoDataSizeInChars - Return the size of a type, in
1401// chars. If the type is a record, its data size is returned. This is
1402// the size of the memcpy that's performed when assigning this type
1403// using a trivial copy/move assignment operator.
1404std::pair<CharUnits, CharUnits>
1405ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1406 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1407
1408 // In C++, objects can sometimes be allocated into the tail padding
1409 // of a base-class subobject. We decide whether that's possible
1410 // during class layout, so here we can just trust the layout results.
1411 if (getLangOpts().CPlusPlus) {
1412 if (const RecordType *RT = T->getAs<RecordType>()) {
1413 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1414 sizeAndAlign.first = layout.getDataSize();
1415 }
1416 }
1417
1418 return sizeAndAlign;
1419}
1420
Richard Trieu04d2d942013-05-14 21:59:17 +00001421/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1422/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1423std::pair<CharUnits, CharUnits>
1424static getConstantArrayInfoInChars(const ASTContext &Context,
1425 const ConstantArrayType *CAT) {
1426 std::pair<CharUnits, CharUnits> EltInfo =
1427 Context.getTypeInfoInChars(CAT->getElementType());
1428 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001429 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1430 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001431 "Overflow in array type char size evaluation");
1432 uint64_t Width = EltInfo.first.getQuantity() * Size;
1433 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001434 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1435 Context.getTargetInfo().getPointerWidth(0) == 64)
1436 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001437 return std::make_pair(CharUnits::fromQuantity(Width),
1438 CharUnits::fromQuantity(Align));
1439}
1440
John McCall87fe5d52010-05-20 01:18:31 +00001441std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001442ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001443 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1444 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001445 TypeInfo Info = getTypeInfo(T);
1446 return std::make_pair(toCharUnitsFromBits(Info.Width),
1447 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001448}
1449
1450std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001451ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001452 return getTypeInfoInChars(T.getTypePtr());
1453}
1454
David Majnemer34b57492014-07-30 01:30:47 +00001455bool ASTContext::isAlignmentRequired(const Type *T) const {
1456 return getTypeInfo(T).AlignIsRequired;
1457}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001458
David Majnemer34b57492014-07-30 01:30:47 +00001459bool ASTContext::isAlignmentRequired(QualType T) const {
1460 return isAlignmentRequired(T.getTypePtr());
1461}
1462
1463TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001464 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1465 if (I != MemoizedTypeInfo.end())
1466 return I->second;
1467
1468 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1469 TypeInfo TI = getTypeInfoImpl(T);
1470 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001471 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001472}
1473
1474/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1475/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001476///
1477/// FIXME: Pointers into different addr spaces could have different sizes and
1478/// alignment requirements: getPointerInfo should take an AddrSpace, this
1479/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001480TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1481 uint64_t Width = 0;
1482 unsigned Align = 8;
1483 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001484 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001485#define TYPE(Class, Base)
1486#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001487#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001488#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001489#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1490 case Type::Class: \
1491 assert(!T->isDependentType() && "should not see dependent types here"); \
1492 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001493#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001494 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001495
Chris Lattner355332d2007-07-13 22:27:08 +00001496 case Type::FunctionNoProto:
1497 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001498 // GCC extension: alignof(function) = 32 bits
1499 Width = 0;
1500 Align = 32;
1501 break;
1502
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001503 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001504 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001505 Width = 0;
1506 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1507 break;
1508
Steve Naroff5c131802007-08-30 01:06:46 +00001509 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001510 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001511
David Majnemer34b57492014-07-30 01:30:47 +00001512 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001513 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001514 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001515 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001516 Width = EltInfo.Width * Size;
1517 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001518 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1519 getTargetInfo().getPointerWidth(0) == 64)
1520 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001521 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001522 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001523 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001524 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001525 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001526 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1527 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001528 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001529 // If the alignment is not a power of 2, round up to the next power of 2.
1530 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001531 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001532 Align = llvm::NextPowerOf2(Align);
1533 Width = llvm::RoundUpToAlignment(Width, Align);
1534 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001535 // Adjust the alignment based on the target max.
1536 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1537 if (TargetVectorAlign && TargetVectorAlign < Align)
1538 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001539 break;
1540 }
Chris Lattner647fb222007-07-18 18:26:58 +00001541
Chris Lattner7570e9c2008-03-08 08:52:55 +00001542 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001543 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001544 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001545 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001546 // GCC extension: alignof(void) = 8 bits.
1547 Width = 0;
1548 Align = 8;
1549 break;
1550
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getBoolWidth();
1553 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001555 case BuiltinType::Char_S:
1556 case BuiltinType::Char_U:
1557 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001559 Width = Target->getCharWidth();
1560 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001561 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001562 case BuiltinType::WChar_S:
1563 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001564 Width = Target->getWCharWidth();
1565 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001566 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001567 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001568 Width = Target->getChar16Width();
1569 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001570 break;
1571 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001572 Width = Target->getChar32Width();
1573 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001574 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001575 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001576 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001577 Width = Target->getShortWidth();
1578 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001579 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001580 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001581 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001582 Width = Target->getIntWidth();
1583 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001584 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001585 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001586 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001587 Width = Target->getLongWidth();
1588 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001589 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001590 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001591 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getLongLongWidth();
1593 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001594 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001595 case BuiltinType::Int128:
1596 case BuiltinType::UInt128:
1597 Width = 128;
1598 Align = 128; // int128_t is 128-bit aligned on all targets.
1599 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001600 case BuiltinType::Half:
1601 Width = Target->getHalfWidth();
1602 Align = Target->getHalfAlign();
1603 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001604 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getFloatWidth();
1606 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 break;
1608 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getDoubleWidth();
1610 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001611 break;
1612 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001613 Width = Target->getLongDoubleWidth();
1614 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001615 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001616 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001617 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1618 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001619 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001620 case BuiltinType::ObjCId:
1621 case BuiltinType::ObjCClass:
1622 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001623 Width = Target->getPointerWidth(0);
1624 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001625 break;
Guy Benyei61054192013-02-07 10:55:47 +00001626 case BuiltinType::OCLSampler:
1627 // Samplers are modeled as integers.
1628 Width = Target->getIntWidth();
1629 Align = Target->getIntAlign();
1630 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001631 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001632 case BuiltinType::OCLImage1d:
1633 case BuiltinType::OCLImage1dArray:
1634 case BuiltinType::OCLImage1dBuffer:
1635 case BuiltinType::OCLImage2d:
1636 case BuiltinType::OCLImage2dArray:
1637 case BuiltinType::OCLImage3d:
1638 // Currently these types are pointers to opaque types.
1639 Width = Target->getPointerWidth(0);
1640 Align = Target->getPointerAlign(0);
1641 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001642 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001643 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001644 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001645 Width = Target->getPointerWidth(0);
1646 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001647 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001648 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001649 unsigned AS = getTargetAddressSpace(
1650 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001651 Width = Target->getPointerWidth(AS);
1652 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001653 break;
1654 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001655 case Type::LValueReference:
1656 case Type::RValueReference: {
1657 // alignof and sizeof should never enter this code path here, so we go
1658 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001659 unsigned AS = getTargetAddressSpace(
1660 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001661 Width = Target->getPointerWidth(AS);
1662 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001663 break;
1664 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001665 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001666 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001667 Width = Target->getPointerWidth(AS);
1668 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001669 break;
1670 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001671 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001672 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001673 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001674 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001675 }
Chris Lattner647fb222007-07-18 18:26:58 +00001676 case Type::Complex: {
1677 // Complex types have the same alignment as their elements, but twice the
1678 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001679 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1680 Width = EltInfo.Width * 2;
1681 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001682 break;
1683 }
John McCall8b07ec22010-05-15 11:32:37 +00001684 case Type::ObjCObject:
1685 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001686 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001687 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001688 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001689 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001690 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001691 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001692 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001693 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001694 break;
1695 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001696 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001697 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001698 const TagType *TT = cast<TagType>(T);
1699
1700 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001701 Width = 8;
1702 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001703 break;
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
David Majnemer475b25e2015-01-21 10:54:38 +00001706 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1707 const EnumDecl *ED = ET->getDecl();
1708 TypeInfo Info =
1709 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1710 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1711 Info.Align = AttrAlign;
1712 Info.AlignIsRequired = true;
1713 }
1714 return Info;
1715 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001716
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001717 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001718 const RecordDecl *RD = RT->getDecl();
1719 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001720 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001721 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001722 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001723 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001724 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001725
Chris Lattner63d2b362009-10-22 05:17:15 +00001726 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001727 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1728 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001729
Richard Smith30482bc2011-02-20 03:19:35 +00001730 case Type::Auto: {
1731 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001732 assert(!A->getDeducedType().isNull() &&
1733 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001734 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001735 }
1736
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001737 case Type::Paren:
1738 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1739
Douglas Gregoref462e62009-04-30 17:32:17 +00001740 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001741 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001742 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001743 // If the typedef has an aligned attribute on it, it overrides any computed
1744 // alignment we have. This violates the GCC documentation (which says that
1745 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001746 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001747 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001748 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001749 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001750 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001751 AlignIsRequired = Info.AlignIsRequired;
1752 }
David Majnemer34b57492014-07-30 01:30:47 +00001753 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001754 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001755 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001756
Abramo Bagnara6150c882010-05-11 21:36:43 +00001757 case Type::Elaborated:
1758 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001759
John McCall81904512011-01-06 01:58:22 +00001760 case Type::Attributed:
1761 return getTypeInfo(
1762 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1763
Eli Friedman0dfb8892011-10-06 23:00:33 +00001764 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001765 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001766 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1767 Width = Info.Width;
1768 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001769
1770 // If the size of the type doesn't exceed the platform's max
1771 // atomic promotion width, make the size and alignment more
1772 // favorable to atomic operations:
1773 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1774 // Round the size up to a power of 2.
1775 if (!llvm::isPowerOf2_64(Width))
1776 Width = llvm::NextPowerOf2(Width);
1777
1778 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001779 Align = static_cast<unsigned>(Width);
1780 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001781 }
1782
Douglas Gregoref462e62009-04-30 17:32:17 +00001783 }
Mike Stump11289f42009-09-09 15:08:12 +00001784
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001785 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001786 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001787}
1788
Ken Dyckcc56c542011-01-15 18:38:59 +00001789/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1790CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1791 return CharUnits::fromQuantity(BitSize / getCharWidth());
1792}
1793
Ken Dyckb0fcc592011-02-11 01:54:29 +00001794/// toBits - Convert a size in characters to a size in characters.
1795int64_t ASTContext::toBits(CharUnits CharSize) const {
1796 return CharSize.getQuantity() * getCharWidth();
1797}
1798
Ken Dyck8c89d592009-12-22 14:23:30 +00001799/// getTypeSizeInChars - Return the size of the specified type, in characters.
1800/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001801CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001802 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001803}
Jay Foad39c79802011-01-12 09:06:06 +00001804CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001805 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001806}
1807
Ken Dycka6046ab2010-01-26 17:25:18 +00001808/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001809/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001810CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001811 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001812}
Jay Foad39c79802011-01-12 09:06:06 +00001813CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001814 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001815}
1816
Chris Lattnera3402cd2009-01-27 18:08:34 +00001817/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1818/// type for the current target in bits. This can be different than the ABI
1819/// alignment in cases where it is beneficial for performance to overalign
1820/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001821unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001822 TypeInfo TI = getTypeInfo(T);
1823 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001824
David Majnemere1544562015-04-24 01:25:05 +00001825 T = T->getBaseElementTypeUnsafe();
1826
1827 // The preferred alignment of member pointers is that of a pointer.
1828 if (T->isMemberPointerType())
1829 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1830
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001831 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1832 return ABIAlign; // Never overalign on XCore.
1833
Eli Friedman7ab09572009-05-25 21:27:19 +00001834 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001835 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001836 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001837 if (const EnumType *ET = T->getAs<EnumType>())
1838 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001839 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001840 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1841 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001842 // Don't increase the alignment if an alignment attribute was specified on a
1843 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001844 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001845 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001846
Chris Lattnera3402cd2009-01-27 18:08:34 +00001847 return ABIAlign;
1848}
1849
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001850/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1851/// for __attribute__((aligned)) on this target, to be used if no alignment
1852/// value is specified.
1853unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1854 return getTargetInfo().getDefaultAlignForAttributeAligned();
1855}
1856
Ulrich Weigandfa806422013-05-06 16:23:57 +00001857/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1858/// to a global variable of the specified type.
1859unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1860 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1861}
1862
1863/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1864/// should be given to a global variable of the specified type.
1865CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1866 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1867}
1868
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001869/// DeepCollectObjCIvars -
1870/// This routine first collects all declared, but not synthesized, ivars in
1871/// super class and then collects all ivars, including those synthesized for
1872/// current class. This routine is used for implementation of current class
1873/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001874///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001875void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1876 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001877 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001878 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1879 DeepCollectObjCIvars(SuperClass, false, Ivars);
1880 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001881 for (const auto *I : OI->ivars())
1882 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001883 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001884 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001885 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001886 Iv= Iv->getNextIvar())
1887 Ivars.push_back(Iv);
1888 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001889}
1890
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001891/// CollectInheritedProtocols - Collect all protocols in current class and
1892/// those inherited by it.
1893void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001894 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001895 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001896 // We can use protocol_iterator here instead of
1897 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001898 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001899 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001900 for (auto *P : Proto->protocols()) {
1901 Protocols.insert(P->getCanonicalDecl());
1902 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001903 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001904 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001905
1906 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001907 for (const auto *Cat : OI->visible_categories())
1908 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001909
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001910 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1911 while (SD) {
1912 CollectInheritedProtocols(SD, Protocols);
1913 SD = SD->getSuperClass();
1914 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001915 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001916 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001917 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001918 for (const auto *P : Proto->protocols())
1919 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001920 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001921 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001922 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001923 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001924 for (const auto *P : Proto->protocols())
1925 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001926 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001927 }
1928}
1929
Jay Foad39c79802011-01-12 09:06:06 +00001930unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001931 unsigned count = 0;
1932 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001933 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001934 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001935
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001936 // Count ivar defined in this class's implementation. This
1937 // includes synthesized ivars.
1938 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001939 count += ImplDecl->ivar_size();
1940
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001941 return count;
1942}
1943
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001944bool ASTContext::isSentinelNullExpr(const Expr *E) {
1945 if (!E)
1946 return false;
1947
1948 // nullptr_t is always treated as null.
1949 if (E->getType()->isNullPtrType()) return true;
1950
1951 if (E->getType()->isAnyPointerType() &&
1952 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1953 Expr::NPC_ValueDependentIsNull))
1954 return true;
1955
1956 // Unfortunately, __null has type 'int'.
1957 if (isa<GNUNullExpr>(E)) return true;
1958
1959 return false;
1960}
1961
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001962/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1963ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1964 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1965 I = ObjCImpls.find(D);
1966 if (I != ObjCImpls.end())
1967 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001968 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001969}
1970/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1971ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1972 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1973 I = ObjCImpls.find(D);
1974 if (I != ObjCImpls.end())
1975 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001976 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001977}
1978
1979/// \brief Set the implementation of ObjCInterfaceDecl.
1980void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1981 ObjCImplementationDecl *ImplD) {
1982 assert(IFaceD && ImplD && "Passed null params");
1983 ObjCImpls[IFaceD] = ImplD;
1984}
1985/// \brief Set the implementation of ObjCCategoryDecl.
1986void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1987 ObjCCategoryImplDecl *ImplD) {
1988 assert(CatD && ImplD && "Passed null params");
1989 ObjCImpls[CatD] = ImplD;
1990}
1991
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001992const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1993 const NamedDecl *ND) const {
1994 if (const ObjCInterfaceDecl *ID =
1995 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001996 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001997 if (const ObjCCategoryDecl *CD =
1998 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001999 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002000 if (const ObjCImplDecl *IMD =
2001 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002002 return IMD->getClassInterface();
2003
Craig Topper36250ad2014-05-12 05:36:57 +00002004 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002005}
2006
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002007/// \brief Get the copy initialization expression of VarDecl,or NULL if
2008/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002009Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002010 assert(VD && "Passed null params");
2011 assert(VD->hasAttr<BlocksAttr>() &&
2012 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002013 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002014 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002015 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002016}
2017
2018/// \brief Set the copy inialization expression of a block var decl.
2019void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2020 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002021 assert(VD->hasAttr<BlocksAttr>() &&
2022 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002023 BlockVarCopyInits[VD] = Init;
2024}
2025
John McCallbcd03502009-12-07 02:54:59 +00002026TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002027 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002028 if (!DataSize)
2029 DataSize = TypeLoc::getFullDataSizeForType(T);
2030 else
2031 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002032 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002033
John McCallbcd03502009-12-07 02:54:59 +00002034 TypeSourceInfo *TInfo =
2035 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2036 new (TInfo) TypeSourceInfo(T);
2037 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002038}
2039
John McCallbcd03502009-12-07 02:54:59 +00002040TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002041 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002042 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002043 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002044 return DI;
2045}
2046
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002047const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002048ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002049 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002050}
2051
2052const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002053ASTContext::getASTObjCImplementationLayout(
2054 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002055 return getObjCLayout(D->getClassInterface(), D);
2056}
2057
Chris Lattner983a8bb2007-07-13 22:13:22 +00002058//===----------------------------------------------------------------------===//
2059// Type creation/memoization methods
2060//===----------------------------------------------------------------------===//
2061
Jay Foad39c79802011-01-12 09:06:06 +00002062QualType
John McCall33ddac02011-01-19 10:06:00 +00002063ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2064 unsigned fastQuals = quals.getFastQualifiers();
2065 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002066
2067 // Check if we've already instantiated this type.
2068 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002069 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002070 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002071 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2072 assert(eq->getQualifiers() == quals);
2073 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002074 }
2075
John McCall33ddac02011-01-19 10:06:00 +00002076 // If the base type is not canonical, make the appropriate canonical type.
2077 QualType canon;
2078 if (!baseType->isCanonicalUnqualified()) {
2079 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002080 canonSplit.Quals.addConsistentQualifiers(quals);
2081 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002082
2083 // Re-find the insert position.
2084 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2085 }
2086
2087 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2088 ExtQualNodes.InsertNode(eq, insertPos);
2089 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002090}
2091
Jay Foad39c79802011-01-12 09:06:06 +00002092QualType
2093ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002094 QualType CanT = getCanonicalType(T);
2095 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002096 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002097
John McCall8ccfcb52009-09-24 19:53:00 +00002098 // If we are composing extended qualifiers together, merge together
2099 // into one ExtQuals node.
2100 QualifierCollector Quals;
2101 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002102
John McCall8ccfcb52009-09-24 19:53:00 +00002103 // If this type already has an address space specified, it cannot get
2104 // another one.
2105 assert(!Quals.hasAddressSpace() &&
2106 "Type cannot be in multiple addr spaces!");
2107 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002108
John McCall8ccfcb52009-09-24 19:53:00 +00002109 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002110}
2111
Chris Lattnerd60183d2009-02-18 22:53:11 +00002112QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002113 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002114 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002115 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002116 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002117
John McCall53fa7142010-12-24 02:08:15 +00002118 if (const PointerType *ptr = T->getAs<PointerType>()) {
2119 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002120 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002121 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2122 return getPointerType(ResultType);
2123 }
2124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
John McCall8ccfcb52009-09-24 19:53:00 +00002126 // If we are composing extended qualifiers together, merge together
2127 // into one ExtQuals node.
2128 QualifierCollector Quals;
2129 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002130
John McCall8ccfcb52009-09-24 19:53:00 +00002131 // If this type already has an ObjCGC specified, it cannot get
2132 // another one.
2133 assert(!Quals.hasObjCGCAttr() &&
2134 "Type cannot have multiple ObjCGCs!");
2135 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002136
John McCall8ccfcb52009-09-24 19:53:00 +00002137 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002138}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002139
John McCall4f5019e2010-12-19 02:44:49 +00002140const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2141 FunctionType::ExtInfo Info) {
2142 if (T->getExtInfo() == Info)
2143 return T;
2144
2145 QualType Result;
2146 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002147 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002148 } else {
2149 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2150 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2151 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002152 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002153 }
2154
2155 return cast<FunctionType>(Result.getTypePtr());
2156}
2157
Richard Smith2a7d4812013-05-04 07:00:32 +00002158void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2159 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002160 FD = FD->getMostRecentDecl();
2161 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002162 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2163 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002164 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002165 if (FunctionDecl *Next = FD->getPreviousDecl())
2166 FD = Next;
2167 else
2168 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002169 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002170 if (ASTMutationListener *L = getASTMutationListener())
2171 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002172}
2173
Richard Smith0b3a4622014-11-13 20:01:57 +00002174/// Get a function type and produce the equivalent function type with the
2175/// specified exception specification. Type sugar that can be present on a
2176/// declaration of a function with an exception specification is permitted
2177/// and preserved. Other type sugar (for instance, typedefs) is not.
2178static QualType getFunctionTypeWithExceptionSpec(
2179 ASTContext &Context, QualType Orig,
2180 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2181 // Might have some parens.
2182 if (auto *PT = dyn_cast<ParenType>(Orig))
2183 return Context.getParenType(
2184 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2185
2186 // Might have a calling-convention attribute.
2187 if (auto *AT = dyn_cast<AttributedType>(Orig))
2188 return Context.getAttributedType(
2189 AT->getAttrKind(),
2190 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2191 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2192 ESI));
2193
2194 // Anything else must be a function type. Rebuild it with the new exception
2195 // specification.
2196 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2197 return Context.getFunctionType(
2198 Proto->getReturnType(), Proto->getParamTypes(),
2199 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2200}
2201
2202void ASTContext::adjustExceptionSpec(
2203 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2204 bool AsWritten) {
2205 // Update the type.
2206 QualType Updated =
2207 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2208 FD->setType(Updated);
2209
2210 if (!AsWritten)
2211 return;
2212
2213 // Update the type in the type source information too.
2214 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2215 // If the type and the type-as-written differ, we may need to update
2216 // the type-as-written too.
2217 if (TSInfo->getType() != FD->getType())
2218 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2219
2220 // FIXME: When we get proper type location information for exceptions,
2221 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2222 // up the TypeSourceInfo;
2223 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2224 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2225 "TypeLoc size mismatch from updating exception specification");
2226 TSInfo->overrideType(Updated);
2227 }
2228}
2229
Chris Lattnerc6395932007-06-22 20:56:16 +00002230/// getComplexType - Return the uniqued reference to the type for a complex
2231/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002232QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002233 // Unique pointers, to guarantee there is only one pointer of a particular
2234 // structure.
2235 llvm::FoldingSetNodeID ID;
2236 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002237
Craig Topper36250ad2014-05-12 05:36:57 +00002238 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002239 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2240 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002241
Chris Lattnerc6395932007-06-22 20:56:16 +00002242 // If the pointee type isn't canonical, this won't be a canonical type either,
2243 // so fill in the canonical type field.
2244 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002245 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002246 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002247
Chris Lattnerc6395932007-06-22 20:56:16 +00002248 // Get the new insert position for the node we care about.
2249 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002250 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002251 }
John McCall90d1c2d2009-09-24 23:30:46 +00002252 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002253 Types.push_back(New);
2254 ComplexTypes.InsertNode(New, InsertPos);
2255 return QualType(New, 0);
2256}
2257
Chris Lattner970e54e2006-11-12 00:37:36 +00002258/// getPointerType - Return the uniqued reference to the type for a pointer to
2259/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002260QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002261 // Unique pointers, to guarantee there is only one pointer of a particular
2262 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002263 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002264 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002265
Craig Topper36250ad2014-05-12 05:36:57 +00002266 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002267 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002268 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattner7ccecb92006-11-12 08:50:50 +00002270 // If the pointee type isn't canonical, this won't be a canonical type either,
2271 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002272 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002273 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002274 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002275
Bob Wilsonc8541f22013-03-15 17:12:43 +00002276 // Get the new insert position for the node we care about.
2277 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002278 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002279 }
John McCall90d1c2d2009-09-24 23:30:46 +00002280 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002281 Types.push_back(New);
2282 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002283 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002284}
2285
Reid Kleckner0503a872013-12-05 01:23:43 +00002286QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2287 llvm::FoldingSetNodeID ID;
2288 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002289 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002290 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2291 if (AT)
2292 return QualType(AT, 0);
2293
2294 QualType Canonical = getCanonicalType(New);
2295
2296 // Get the new insert position for the node we care about.
2297 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002298 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002299
2300 AT = new (*this, TypeAlignment)
2301 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2302 Types.push_back(AT);
2303 AdjustedTypes.InsertNode(AT, InsertPos);
2304 return QualType(AT, 0);
2305}
2306
Reid Kleckner8a365022013-06-24 17:51:48 +00002307QualType ASTContext::getDecayedType(QualType T) const {
2308 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2309
Reid Kleckner8a365022013-06-24 17:51:48 +00002310 QualType Decayed;
2311
2312 // C99 6.7.5.3p7:
2313 // A declaration of a parameter as "array of type" shall be
2314 // adjusted to "qualified pointer to type", where the type
2315 // qualifiers (if any) are those specified within the [ and ] of
2316 // the array type derivation.
2317 if (T->isArrayType())
2318 Decayed = getArrayDecayedType(T);
2319
2320 // C99 6.7.5.3p8:
2321 // A declaration of a parameter as "function returning type"
2322 // shall be adjusted to "pointer to function returning type", as
2323 // in 6.3.2.1.
2324 if (T->isFunctionType())
2325 Decayed = getPointerType(T);
2326
Reid Kleckner0503a872013-12-05 01:23:43 +00002327 llvm::FoldingSetNodeID ID;
2328 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002329 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002330 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2331 if (AT)
2332 return QualType(AT, 0);
2333
Reid Kleckner8a365022013-06-24 17:51:48 +00002334 QualType Canonical = getCanonicalType(Decayed);
2335
2336 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002337 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002338 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002339
Reid Kleckner0503a872013-12-05 01:23:43 +00002340 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2341 Types.push_back(AT);
2342 AdjustedTypes.InsertNode(AT, InsertPos);
2343 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002344}
2345
Mike Stump11289f42009-09-09 15:08:12 +00002346/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002347/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002348QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002349 assert(T->isFunctionType() && "block of function types only");
2350 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002351 // structure.
2352 llvm::FoldingSetNodeID ID;
2353 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002354
Craig Topper36250ad2014-05-12 05:36:57 +00002355 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002356 if (BlockPointerType *PT =
2357 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2358 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002359
2360 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002361 // type either so fill in the canonical type field.
2362 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002363 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002364 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002365
Steve Naroffec33ed92008-08-27 16:04:49 +00002366 // Get the new insert position for the node we care about.
2367 BlockPointerType *NewIP =
2368 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002369 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002370 }
John McCall90d1c2d2009-09-24 23:30:46 +00002371 BlockPointerType *New
2372 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002373 Types.push_back(New);
2374 BlockPointerTypes.InsertNode(New, InsertPos);
2375 return QualType(New, 0);
2376}
2377
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002378/// getLValueReferenceType - Return the uniqued reference to the type for an
2379/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002380QualType
2381ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002382 assert(getCanonicalType(T) != OverloadTy &&
2383 "Unresolved overloaded function type");
2384
Bill Wendling3708c182007-05-27 10:15:43 +00002385 // Unique pointers, to guarantee there is only one pointer of a particular
2386 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002387 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002388 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002389
Craig Topper36250ad2014-05-12 05:36:57 +00002390 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002391 if (LValueReferenceType *RT =
2392 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002393 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002394
John McCallfc93cf92009-10-22 22:37:11 +00002395 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2396
Bill Wendling3708c182007-05-27 10:15:43 +00002397 // If the referencee type isn't canonical, this won't be a canonical type
2398 // either, so fill in the canonical type field.
2399 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002400 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2401 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2402 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002403
Bill Wendling3708c182007-05-27 10:15:43 +00002404 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002405 LValueReferenceType *NewIP =
2406 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002407 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002408 }
2409
John McCall90d1c2d2009-09-24 23:30:46 +00002410 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002411 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2412 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002413 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002414 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002415
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002416 return QualType(New, 0);
2417}
2418
2419/// getRValueReferenceType - Return the uniqued reference to the type for an
2420/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002421QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002422 // Unique pointers, to guarantee there is only one pointer of a particular
2423 // structure.
2424 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002425 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002426
Craig Topper36250ad2014-05-12 05:36:57 +00002427 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002428 if (RValueReferenceType *RT =
2429 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2430 return QualType(RT, 0);
2431
John McCallfc93cf92009-10-22 22:37:11 +00002432 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2433
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002434 // If the referencee type isn't canonical, this won't be a canonical type
2435 // either, so fill in the canonical type field.
2436 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002437 if (InnerRef || !T.isCanonical()) {
2438 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2439 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002440
2441 // Get the new insert position for the node we care about.
2442 RValueReferenceType *NewIP =
2443 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002444 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002445 }
2446
John McCall90d1c2d2009-09-24 23:30:46 +00002447 RValueReferenceType *New
2448 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002449 Types.push_back(New);
2450 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002451 return QualType(New, 0);
2452}
2453
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002454/// getMemberPointerType - Return the uniqued reference to the type for a
2455/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002456QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002457 // Unique pointers, to guarantee there is only one pointer of a particular
2458 // structure.
2459 llvm::FoldingSetNodeID ID;
2460 MemberPointerType::Profile(ID, T, Cls);
2461
Craig Topper36250ad2014-05-12 05:36:57 +00002462 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002463 if (MemberPointerType *PT =
2464 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2465 return QualType(PT, 0);
2466
2467 // If the pointee or class type isn't canonical, this won't be a canonical
2468 // type either, so fill in the canonical type field.
2469 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002470 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002471 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2472
2473 // Get the new insert position for the node we care about.
2474 MemberPointerType *NewIP =
2475 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002476 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002477 }
John McCall90d1c2d2009-09-24 23:30:46 +00002478 MemberPointerType *New
2479 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002480 Types.push_back(New);
2481 MemberPointerTypes.InsertNode(New, InsertPos);
2482 return QualType(New, 0);
2483}
2484
Mike Stump11289f42009-09-09 15:08:12 +00002485/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002486/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002487QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002488 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002489 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002490 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002491 assert((EltTy->isDependentType() ||
2492 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002493 "Constant array of VLAs is illegal!");
2494
Chris Lattnere2df3f92009-05-13 04:12:56 +00002495 // Convert the array size into a canonical width matching the pointer size for
2496 // the target.
2497 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002498 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002499 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002500
Chris Lattner23b7eb62007-06-15 23:05:46 +00002501 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002502 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002503
Craig Topper36250ad2014-05-12 05:36:57 +00002504 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002505 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002506 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002507 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002508
John McCall33ddac02011-01-19 10:06:00 +00002509 // If the element type isn't canonical or has qualifiers, this won't
2510 // be a canonical type either, so fill in the canonical type field.
2511 QualType Canon;
2512 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2513 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002514 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002515 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002516 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002517
Chris Lattner36f8e652007-01-27 08:31:04 +00002518 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002519 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002520 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002521 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
John McCall90d1c2d2009-09-24 23:30:46 +00002524 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002525 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002526 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002527 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002528 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002529}
2530
John McCall06549462011-01-18 08:40:38 +00002531/// getVariableArrayDecayedType - Turns the given type, which may be
2532/// variably-modified, into the corresponding type with all the known
2533/// sizes replaced with [*].
2534QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2535 // Vastly most common case.
2536 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002537
John McCall06549462011-01-18 08:40:38 +00002538 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002539
John McCall06549462011-01-18 08:40:38 +00002540 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002541 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002542 switch (ty->getTypeClass()) {
2543#define TYPE(Class, Base)
2544#define ABSTRACT_TYPE(Class, Base)
2545#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2546#include "clang/AST/TypeNodes.def"
2547 llvm_unreachable("didn't desugar past all non-canonical types?");
2548
2549 // These types should never be variably-modified.
2550 case Type::Builtin:
2551 case Type::Complex:
2552 case Type::Vector:
2553 case Type::ExtVector:
2554 case Type::DependentSizedExtVector:
2555 case Type::ObjCObject:
2556 case Type::ObjCInterface:
2557 case Type::ObjCObjectPointer:
2558 case Type::Record:
2559 case Type::Enum:
2560 case Type::UnresolvedUsing:
2561 case Type::TypeOfExpr:
2562 case Type::TypeOf:
2563 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002564 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002565 case Type::DependentName:
2566 case Type::InjectedClassName:
2567 case Type::TemplateSpecialization:
2568 case Type::DependentTemplateSpecialization:
2569 case Type::TemplateTypeParm:
2570 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002571 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002572 case Type::PackExpansion:
2573 llvm_unreachable("type should never be variably-modified");
2574
2575 // These types can be variably-modified but should never need to
2576 // further decay.
2577 case Type::FunctionNoProto:
2578 case Type::FunctionProto:
2579 case Type::BlockPointer:
2580 case Type::MemberPointer:
2581 return type;
2582
2583 // These types can be variably-modified. All these modifications
2584 // preserve structure except as noted by comments.
2585 // TODO: if we ever care about optimizing VLAs, there are no-op
2586 // optimizations available here.
2587 case Type::Pointer:
2588 result = getPointerType(getVariableArrayDecayedType(
2589 cast<PointerType>(ty)->getPointeeType()));
2590 break;
2591
2592 case Type::LValueReference: {
2593 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2594 result = getLValueReferenceType(
2595 getVariableArrayDecayedType(lv->getPointeeType()),
2596 lv->isSpelledAsLValue());
2597 break;
2598 }
2599
2600 case Type::RValueReference: {
2601 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2602 result = getRValueReferenceType(
2603 getVariableArrayDecayedType(lv->getPointeeType()));
2604 break;
2605 }
2606
Eli Friedman0dfb8892011-10-06 23:00:33 +00002607 case Type::Atomic: {
2608 const AtomicType *at = cast<AtomicType>(ty);
2609 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2610 break;
2611 }
2612
John McCall06549462011-01-18 08:40:38 +00002613 case Type::ConstantArray: {
2614 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2615 result = getConstantArrayType(
2616 getVariableArrayDecayedType(cat->getElementType()),
2617 cat->getSize(),
2618 cat->getSizeModifier(),
2619 cat->getIndexTypeCVRQualifiers());
2620 break;
2621 }
2622
2623 case Type::DependentSizedArray: {
2624 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2625 result = getDependentSizedArrayType(
2626 getVariableArrayDecayedType(dat->getElementType()),
2627 dat->getSizeExpr(),
2628 dat->getSizeModifier(),
2629 dat->getIndexTypeCVRQualifiers(),
2630 dat->getBracketsRange());
2631 break;
2632 }
2633
2634 // Turn incomplete types into [*] types.
2635 case Type::IncompleteArray: {
2636 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2637 result = getVariableArrayType(
2638 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002639 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002640 ArrayType::Normal,
2641 iat->getIndexTypeCVRQualifiers(),
2642 SourceRange());
2643 break;
2644 }
2645
2646 // Turn VLA types into [*] types.
2647 case Type::VariableArray: {
2648 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2649 result = getVariableArrayType(
2650 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002651 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002652 ArrayType::Star,
2653 vat->getIndexTypeCVRQualifiers(),
2654 vat->getBracketsRange());
2655 break;
2656 }
2657 }
2658
2659 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002660 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002661}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002662
Steve Naroffcadebd02007-08-30 18:14:25 +00002663/// getVariableArrayType - Returns a non-unique reference to the type for a
2664/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002665QualType ASTContext::getVariableArrayType(QualType EltTy,
2666 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002667 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002668 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002669 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002670 // Since we don't unique expressions, it isn't possible to unique VLA's
2671 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002672 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002673
John McCall33ddac02011-01-19 10:06:00 +00002674 // Be sure to pull qualifiers off the element type.
2675 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2676 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002677 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002678 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002679 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002680 }
2681
John McCall90d1c2d2009-09-24 23:30:46 +00002682 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002683 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002684
2685 VariableArrayTypes.push_back(New);
2686 Types.push_back(New);
2687 return QualType(New, 0);
2688}
2689
Douglas Gregor4619e432008-12-05 23:32:09 +00002690/// getDependentSizedArrayType - Returns a non-unique reference to
2691/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002692/// type.
John McCall33ddac02011-01-19 10:06:00 +00002693QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2694 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002695 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002696 unsigned elementTypeQuals,
2697 SourceRange brackets) const {
2698 assert((!numElements || numElements->isTypeDependent() ||
2699 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002700 "Size must be type- or value-dependent!");
2701
John McCall33ddac02011-01-19 10:06:00 +00002702 // Dependently-sized array types that do not have a specified number
2703 // of elements will have their sizes deduced from a dependent
2704 // initializer. We do no canonicalization here at all, which is okay
2705 // because they can't be used in most locations.
2706 if (!numElements) {
2707 DependentSizedArrayType *newType
2708 = new (*this, TypeAlignment)
2709 DependentSizedArrayType(*this, elementType, QualType(),
2710 numElements, ASM, elementTypeQuals,
2711 brackets);
2712 Types.push_back(newType);
2713 return QualType(newType, 0);
2714 }
2715
2716 // Otherwise, we actually build a new type every time, but we
2717 // also build a canonical type.
2718
2719 SplitQualType canonElementType = getCanonicalType(elementType).split();
2720
Craig Topper36250ad2014-05-12 05:36:57 +00002721 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002722 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002723 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002724 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002725 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002726
John McCall33ddac02011-01-19 10:06:00 +00002727 // Look for an existing type with these properties.
2728 DependentSizedArrayType *canonTy =
2729 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002730
John McCall33ddac02011-01-19 10:06:00 +00002731 // If we don't have one, build one.
2732 if (!canonTy) {
2733 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002734 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002735 QualType(), numElements, ASM, elementTypeQuals,
2736 brackets);
2737 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2738 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002739 }
2740
John McCall33ddac02011-01-19 10:06:00 +00002741 // Apply qualifiers from the element type to the array.
2742 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002743 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002744
John McCall33ddac02011-01-19 10:06:00 +00002745 // If we didn't need extra canonicalization for the element type,
2746 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002747 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002748 return canon;
2749
2750 // Otherwise, we need to build a type which follows the spelling
2751 // of the element type.
2752 DependentSizedArrayType *sugaredType
2753 = new (*this, TypeAlignment)
2754 DependentSizedArrayType(*this, elementType, canon, numElements,
2755 ASM, elementTypeQuals, brackets);
2756 Types.push_back(sugaredType);
2757 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002758}
2759
John McCall33ddac02011-01-19 10:06:00 +00002760QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002761 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002762 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002763 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002764 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002765
Craig Topper36250ad2014-05-12 05:36:57 +00002766 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002767 if (IncompleteArrayType *iat =
2768 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2769 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002770
2771 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002772 // either, so fill in the canonical type field. We also have to pull
2773 // qualifiers off the element type.
2774 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002775
John McCall33ddac02011-01-19 10:06:00 +00002776 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2777 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002778 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002779 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002780 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002781
2782 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002783 IncompleteArrayType *existing =
2784 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2785 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002786 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002787
John McCall33ddac02011-01-19 10:06:00 +00002788 IncompleteArrayType *newType = new (*this, TypeAlignment)
2789 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002790
John McCall33ddac02011-01-19 10:06:00 +00002791 IncompleteArrayTypes.InsertNode(newType, insertPos);
2792 Types.push_back(newType);
2793 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002794}
2795
Steve Naroff91fcddb2007-07-18 18:00:27 +00002796/// getVectorType - Return the unique reference to a vector type of
2797/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002798QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002799 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002800 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002801
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002802 // Check if we've already instantiated a vector of this type.
2803 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002804 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002805
Craig Topper36250ad2014-05-12 05:36:57 +00002806 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002807 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2808 return QualType(VTP, 0);
2809
2810 // If the element type isn't canonical, this won't be a canonical type either,
2811 // so fill in the canonical type field.
2812 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002813 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002814 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002815
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002816 // Get the new insert position for the node we care about.
2817 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002818 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002819 }
John McCall90d1c2d2009-09-24 23:30:46 +00002820 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002821 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002822 VectorTypes.InsertNode(New, InsertPos);
2823 Types.push_back(New);
2824 return QualType(New, 0);
2825}
2826
Nate Begemance4d7fc2008-04-18 23:10:10 +00002827/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002828/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002829QualType
2830ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002831 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002832
Steve Naroff91fcddb2007-07-18 18:00:27 +00002833 // Check if we've already instantiated a vector of this type.
2834 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002835 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002836 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002837 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002838 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2839 return QualType(VTP, 0);
2840
2841 // If the element type isn't canonical, this won't be a canonical type either,
2842 // so fill in the canonical type field.
2843 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002844 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002845 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002846
Steve Naroff91fcddb2007-07-18 18:00:27 +00002847 // Get the new insert position for the node we care about.
2848 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002849 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002850 }
John McCall90d1c2d2009-09-24 23:30:46 +00002851 ExtVectorType *New = new (*this, TypeAlignment)
2852 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002853 VectorTypes.InsertNode(New, InsertPos);
2854 Types.push_back(New);
2855 return QualType(New, 0);
2856}
2857
Jay Foad39c79802011-01-12 09:06:06 +00002858QualType
2859ASTContext::getDependentSizedExtVectorType(QualType vecType,
2860 Expr *SizeExpr,
2861 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002862 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002863 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002864 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002865
Craig Topper36250ad2014-05-12 05:36:57 +00002866 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002867 DependentSizedExtVectorType *Canon
2868 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2869 DependentSizedExtVectorType *New;
2870 if (Canon) {
2871 // We already have a canonical version of this array type; use it as
2872 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002873 New = new (*this, TypeAlignment)
2874 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2875 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002876 } else {
2877 QualType CanonVecTy = getCanonicalType(vecType);
2878 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002879 New = new (*this, TypeAlignment)
2880 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2881 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002882
2883 DependentSizedExtVectorType *CanonCheck
2884 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2885 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2886 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002887 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2888 } else {
2889 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2890 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002891 New = new (*this, TypeAlignment)
2892 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002893 }
2894 }
Mike Stump11289f42009-09-09 15:08:12 +00002895
Douglas Gregor758a8692009-06-17 21:51:59 +00002896 Types.push_back(New);
2897 return QualType(New, 0);
2898}
2899
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002900/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002901///
Jay Foad39c79802011-01-12 09:06:06 +00002902QualType
2903ASTContext::getFunctionNoProtoType(QualType ResultTy,
2904 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002905 const CallingConv CallConv = Info.getCC();
2906
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002907 // Unique functions, to guarantee there is only one function of a particular
2908 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002909 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002910 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002911
Craig Topper36250ad2014-05-12 05:36:57 +00002912 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002913 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002914 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002915 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002916
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002917 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002918 if (!ResultTy.isCanonical()) {
2919 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002920
Chris Lattner47955de2007-01-27 08:37:20 +00002921 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002922 FunctionNoProtoType *NewIP =
2923 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002924 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002925 }
Mike Stump11289f42009-09-09 15:08:12 +00002926
Roman Divacky65b88cd2011-03-01 17:40:53 +00002927 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002928 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002929 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002930 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002931 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002932 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002933}
2934
Douglas Gregorcd780372013-01-17 23:36:45 +00002935/// \brief Determine whether \p T is canonical as the result type of a function.
2936static bool isCanonicalResultType(QualType T) {
2937 return T.isCanonical() &&
2938 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2939 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2940}
2941
Jay Foad39c79802011-01-12 09:06:06 +00002942QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002943ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002944 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002945 size_t NumArgs = ArgArray.size();
2946
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002947 // Unique functions, to guarantee there is only one function of a particular
2948 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002949 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002950 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2951 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002952
Craig Topper36250ad2014-05-12 05:36:57 +00002953 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002954 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002955 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002956 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002957
2958 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002959 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002960 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002961 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002962 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002963 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002964 isCanonical = false;
2965
2966 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002967 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002968 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002969 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002970 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002971 CanonicalArgs.reserve(NumArgs);
2972 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002973 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002974
John McCalldb40c7f2010-12-14 08:05:40 +00002975 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002976 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002977 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002978
Douglas Gregorcd780372013-01-17 23:36:45 +00002979 // Result types do not have ARC lifetime qualifiers.
2980 QualType CanResultTy = getCanonicalType(ResultTy);
2981 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2982 Qualifiers Qs = CanResultTy.getQualifiers();
2983 Qs.removeObjCLifetime();
2984 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2985 }
2986
Jordan Rose5c382722013-03-08 21:51:21 +00002987 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002988
Chris Lattnerfd4de792007-01-27 01:15:32 +00002989 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002990 FunctionProtoType *NewIP =
2991 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002992 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002993 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002994
John McCall31168b02011-06-15 23:02:42 +00002995 // FunctionProtoType objects are allocated with extra bytes after
2996 // them for three variable size arrays at the end:
2997 // - parameter types
2998 // - exception types
2999 // - consumed-arguments flags
3000 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003001 // expression, or information used to resolve the exception
3002 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003003 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003004 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003005 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3006 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3007 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003008 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003009 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003010 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003011 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003012 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003013 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003014 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003015 Size += NumArgs * sizeof(bool);
3016
John McCalldb40c7f2010-12-14 08:05:40 +00003017 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003018 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003019 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003020 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003021 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003022 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003023}
Chris Lattneref51c202006-11-10 07:17:23 +00003024
John McCalle78aac42010-03-10 03:28:59 +00003025#ifndef NDEBUG
3026static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3027 if (!isa<CXXRecordDecl>(D)) return false;
3028 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3029 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3030 return true;
3031 if (RD->getDescribedClassTemplate() &&
3032 !isa<ClassTemplateSpecializationDecl>(RD))
3033 return true;
3034 return false;
3035}
3036#endif
3037
3038/// getInjectedClassNameType - Return the unique reference to the
3039/// injected class name type for the specified templated declaration.
3040QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003041 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003042 assert(NeedsInjectedClassNameType(Decl));
3043 if (Decl->TypeForDecl) {
3044 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003045 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003046 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3047 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3048 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3049 } else {
John McCall424cec92011-01-19 06:33:43 +00003050 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003051 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003052 Decl->TypeForDecl = newType;
3053 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003054 }
3055 return QualType(Decl->TypeForDecl, 0);
3056}
3057
Douglas Gregor83a586e2008-04-13 21:07:44 +00003058/// getTypeDeclType - Return the unique reference to the type for the
3059/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003060QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003061 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003062 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003063
Richard Smithdda56e42011-04-15 14:24:37 +00003064 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003065 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003066
John McCall96f0b5f2010-03-10 06:48:02 +00003067 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3068 "Template type parameter types are always available.");
3069
John McCall81e38502010-02-16 03:57:14 +00003070 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003071 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003072 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003073 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003074 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003075 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003076 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003077 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003078 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003079 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3080 Decl->TypeForDecl = newType;
3081 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003082 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003083 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003084
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003085 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003086}
3087
Chris Lattner32d920b2007-01-26 02:01:53 +00003088/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003089/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003090QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003091ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3092 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003093 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003094
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003095 if (Canonical.isNull())
3096 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003097 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003098 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003099 Decl->TypeForDecl = newType;
3100 Types.push_back(newType);
3101 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003102}
3103
Jay Foad39c79802011-01-12 09:06:06 +00003104QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003105 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3106
Douglas Gregorec9fd132012-01-14 16:38:05 +00003107 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003108 if (PrevDecl->TypeForDecl)
3109 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3110
John McCall424cec92011-01-19 06:33:43 +00003111 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3112 Decl->TypeForDecl = newType;
3113 Types.push_back(newType);
3114 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003115}
3116
Jay Foad39c79802011-01-12 09:06:06 +00003117QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003118 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3119
Douglas Gregorec9fd132012-01-14 16:38:05 +00003120 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003121 if (PrevDecl->TypeForDecl)
3122 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3123
John McCall424cec92011-01-19 06:33:43 +00003124 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3125 Decl->TypeForDecl = newType;
3126 Types.push_back(newType);
3127 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003128}
3129
John McCall81904512011-01-06 01:58:22 +00003130QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3131 QualType modifiedType,
3132 QualType equivalentType) {
3133 llvm::FoldingSetNodeID id;
3134 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3135
Craig Topper36250ad2014-05-12 05:36:57 +00003136 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003137 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3138 if (type) return QualType(type, 0);
3139
3140 QualType canon = getCanonicalType(equivalentType);
3141 type = new (*this, TypeAlignment)
3142 AttributedType(canon, attrKind, modifiedType, equivalentType);
3143
3144 Types.push_back(type);
3145 AttributedTypes.InsertNode(type, insertPos);
3146
3147 return QualType(type, 0);
3148}
3149
3150
John McCallcebee162009-10-18 09:09:24 +00003151/// \brief Retrieve a substitution-result type.
3152QualType
3153ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003154 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003155 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003156 && "replacement types must always be canonical");
3157
3158 llvm::FoldingSetNodeID ID;
3159 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003160 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003161 SubstTemplateTypeParmType *SubstParm
3162 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3163
3164 if (!SubstParm) {
3165 SubstParm = new (*this, TypeAlignment)
3166 SubstTemplateTypeParmType(Parm, Replacement);
3167 Types.push_back(SubstParm);
3168 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3169 }
3170
3171 return QualType(SubstParm, 0);
3172}
3173
Douglas Gregorada4b792011-01-14 02:55:32 +00003174/// \brief Retrieve a
3175QualType ASTContext::getSubstTemplateTypeParmPackType(
3176 const TemplateTypeParmType *Parm,
3177 const TemplateArgument &ArgPack) {
3178#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003179 for (const auto &P : ArgPack.pack_elements()) {
3180 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3181 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003182 }
3183#endif
3184
3185 llvm::FoldingSetNodeID ID;
3186 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003187 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003188 if (SubstTemplateTypeParmPackType *SubstParm
3189 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3190 return QualType(SubstParm, 0);
3191
3192 QualType Canon;
3193 if (!Parm->isCanonicalUnqualified()) {
3194 Canon = getCanonicalType(QualType(Parm, 0));
3195 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3196 ArgPack);
3197 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3198 }
3199
3200 SubstTemplateTypeParmPackType *SubstParm
3201 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3202 ArgPack);
3203 Types.push_back(SubstParm);
3204 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3205 return QualType(SubstParm, 0);
3206}
3207
Douglas Gregoreff93e02009-02-05 23:33:38 +00003208/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003209/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003210/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003211QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003212 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003213 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003214 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003215 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003216 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003217 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003218 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3219
3220 if (TypeParm)
3221 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003222
Chandler Carruth08836322011-05-01 00:51:33 +00003223 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003224 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003225 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003226
3227 TemplateTypeParmType *TypeCheck
3228 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3229 assert(!TypeCheck && "Template type parameter canonical type broken");
3230 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003231 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003232 TypeParm = new (*this, TypeAlignment)
3233 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003234
3235 Types.push_back(TypeParm);
3236 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3237
3238 return QualType(TypeParm, 0);
3239}
3240
John McCalle78aac42010-03-10 03:28:59 +00003241TypeSourceInfo *
3242ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3243 SourceLocation NameLoc,
3244 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003245 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003246 assert(!Name.getAsDependentTemplateName() &&
3247 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003248 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003249
3250 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003251 TemplateSpecializationTypeLoc TL =
3252 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003253 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003254 TL.setTemplateNameLoc(NameLoc);
3255 TL.setLAngleLoc(Args.getLAngleLoc());
3256 TL.setRAngleLoc(Args.getRAngleLoc());
3257 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3258 TL.setArgLocInfo(i, Args[i].getLocInfo());
3259 return DI;
3260}
3261
Mike Stump11289f42009-09-09 15:08:12 +00003262QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003263ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003264 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003265 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003266 assert(!Template.getAsDependentTemplateName() &&
3267 "No dependent template names here!");
3268
John McCall6b51f282009-11-23 01:53:49 +00003269 unsigned NumArgs = Args.size();
3270
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003271 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003272 ArgVec.reserve(NumArgs);
3273 for (unsigned i = 0; i != NumArgs; ++i)
3274 ArgVec.push_back(Args[i].getArgument());
3275
John McCall2408e322010-04-27 00:57:59 +00003276 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003277 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003278}
3279
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003280#ifndef NDEBUG
3281static bool hasAnyPackExpansions(const TemplateArgument *Args,
3282 unsigned NumArgs) {
3283 for (unsigned I = 0; I != NumArgs; ++I)
3284 if (Args[I].isPackExpansion())
3285 return true;
3286
3287 return true;
3288}
3289#endif
3290
John McCall0ad16662009-10-29 08:12:44 +00003291QualType
3292ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003293 const TemplateArgument *Args,
3294 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003295 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003296 assert(!Template.getAsDependentTemplateName() &&
3297 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003298 // Look through qualified template names.
3299 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3300 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003301
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003302 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003303 Template.getAsTemplateDecl() &&
3304 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003305 QualType CanonType;
3306 if (!Underlying.isNull())
3307 CanonType = getCanonicalType(Underlying);
3308 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003309 // We can get here with an alias template when the specialization contains
3310 // a pack expansion that does not match up with a parameter pack.
3311 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3312 "Caller must compute aliased type");
3313 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003314 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3315 NumArgs);
3316 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003317
Douglas Gregora8e02e72009-07-28 23:00:59 +00003318 // Allocate the (non-canonical) template specialization type, but don't
3319 // try to unique it: these types typically have location information that
3320 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003321 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3322 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003323 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003324 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003325 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003326 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3327 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003328
Douglas Gregor8bf42052009-02-09 18:46:07 +00003329 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003330 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003331}
3332
Mike Stump11289f42009-09-09 15:08:12 +00003333QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003334ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3335 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003336 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003337 assert(!Template.getAsDependentTemplateName() &&
3338 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003339
Douglas Gregore29139c2011-03-03 17:04:51 +00003340 // Look through qualified template names.
3341 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3342 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003343
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003344 // Build the canonical template specialization type.
3345 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003346 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003347 CanonArgs.reserve(NumArgs);
3348 for (unsigned I = 0; I != NumArgs; ++I)
3349 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3350
3351 // Determine whether this canonical template specialization type already
3352 // exists.
3353 llvm::FoldingSetNodeID ID;
3354 TemplateSpecializationType::Profile(ID, CanonTemplate,
3355 CanonArgs.data(), NumArgs, *this);
3356
Craig Topper36250ad2014-05-12 05:36:57 +00003357 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003358 TemplateSpecializationType *Spec
3359 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3360
3361 if (!Spec) {
3362 // Allocate a new canonical template specialization type.
3363 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3364 sizeof(TemplateArgument) * NumArgs),
3365 TypeAlignment);
3366 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3367 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003368 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003369 Types.push_back(Spec);
3370 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3371 }
3372
3373 assert(Spec->isDependentType() &&
3374 "Non-dependent template-id type must have a canonical type");
3375 return QualType(Spec, 0);
3376}
3377
3378QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003379ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3380 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003381 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003382 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003383 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003384
Craig Topper36250ad2014-05-12 05:36:57 +00003385 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003386 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003387 if (T)
3388 return QualType(T, 0);
3389
Douglas Gregorc42075a2010-02-04 18:10:26 +00003390 QualType Canon = NamedType;
3391 if (!Canon.isCanonical()) {
3392 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003393 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3394 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003395 (void)CheckT;
3396 }
3397
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003398 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003399 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003400 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003401 return QualType(T, 0);
3402}
3403
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003404QualType
Jay Foad39c79802011-01-12 09:06:06 +00003405ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003406 llvm::FoldingSetNodeID ID;
3407 ParenType::Profile(ID, InnerType);
3408
Craig Topper36250ad2014-05-12 05:36:57 +00003409 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003410 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3411 if (T)
3412 return QualType(T, 0);
3413
3414 QualType Canon = InnerType;
3415 if (!Canon.isCanonical()) {
3416 Canon = getCanonicalType(InnerType);
3417 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3418 assert(!CheckT && "Paren canonical type broken");
3419 (void)CheckT;
3420 }
3421
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003422 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003423 Types.push_back(T);
3424 ParenTypes.InsertNode(T, InsertPos);
3425 return QualType(T, 0);
3426}
3427
Douglas Gregor02085352010-03-31 20:19:30 +00003428QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3429 NestedNameSpecifier *NNS,
3430 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003431 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003432 if (Canon.isNull()) {
3433 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003434 ElaboratedTypeKeyword CanonKeyword = Keyword;
3435 if (Keyword == ETK_None)
3436 CanonKeyword = ETK_Typename;
3437
3438 if (CanonNNS != NNS || CanonKeyword != Keyword)
3439 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003440 }
3441
3442 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003443 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003444
Craig Topper36250ad2014-05-12 05:36:57 +00003445 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003446 DependentNameType *T
3447 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003448 if (T)
3449 return QualType(T, 0);
3450
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003451 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003452 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003453 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003454 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003455}
3456
Mike Stump11289f42009-09-09 15:08:12 +00003457QualType
John McCallc392f372010-06-11 00:33:02 +00003458ASTContext::getDependentTemplateSpecializationType(
3459 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003460 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003461 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003462 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003463 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003464 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003465 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3466 ArgCopy.push_back(Args[I].getArgument());
3467 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3468 ArgCopy.size(),
3469 ArgCopy.data());
3470}
3471
3472QualType
3473ASTContext::getDependentTemplateSpecializationType(
3474 ElaboratedTypeKeyword Keyword,
3475 NestedNameSpecifier *NNS,
3476 const IdentifierInfo *Name,
3477 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003478 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003479 assert((!NNS || NNS->isDependent()) &&
3480 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003481
Douglas Gregorc42075a2010-02-04 18:10:26 +00003482 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003483 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3484 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003485
Craig Topper36250ad2014-05-12 05:36:57 +00003486 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003487 DependentTemplateSpecializationType *T
3488 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003489 if (T)
3490 return QualType(T, 0);
3491
John McCallc392f372010-06-11 00:33:02 +00003492 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003493
John McCallc392f372010-06-11 00:33:02 +00003494 ElaboratedTypeKeyword CanonKeyword = Keyword;
3495 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3496
3497 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003498 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003499 for (unsigned I = 0; I != NumArgs; ++I) {
3500 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3501 if (!CanonArgs[I].structurallyEquals(Args[I]))
3502 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003503 }
3504
John McCallc392f372010-06-11 00:33:02 +00003505 QualType Canon;
3506 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3507 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3508 Name, NumArgs,
3509 CanonArgs.data());
3510
3511 // Find the insert position again.
3512 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3513 }
3514
3515 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3516 sizeof(TemplateArgument) * NumArgs),
3517 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003518 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003519 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003520 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003521 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003522 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003523}
3524
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003525QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003526 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003527 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003528 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003529
3530 assert(Pattern->containsUnexpandedParameterPack() &&
3531 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003532 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003533 PackExpansionType *T
3534 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3535 if (T)
3536 return QualType(T, 0);
3537
3538 QualType Canon;
3539 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003540 Canon = getCanonicalType(Pattern);
3541 // The canonical type might not contain an unexpanded parameter pack, if it
3542 // contains an alias template specialization which ignores one of its
3543 // parameters.
3544 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003545 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003546
Richard Smith68eea502012-07-16 00:20:35 +00003547 // Find the insert position again, in case we inserted an element into
3548 // PackExpansionTypes and invalidated our insert position.
3549 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3550 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003551 }
3552
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003553 T = new (*this, TypeAlignment)
3554 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003555 Types.push_back(T);
3556 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003557 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003558}
3559
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003560/// CmpProtocolNames - Comparison predicate for sorting protocols
3561/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003562static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3563 ObjCProtocolDecl *const *RHS) {
3564 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003565}
3566
John McCall8b07ec22010-05-15 11:32:37 +00003567static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003568 unsigned NumProtocols) {
3569 if (NumProtocols == 0) return true;
3570
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003571 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3572 return false;
3573
John McCallfc93cf92009-10-22 22:37:11 +00003574 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003575 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003576 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003577 return false;
3578 return true;
3579}
3580
3581static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003582 unsigned &NumProtocols) {
3583 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003584
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003585 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003586 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003587
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003588 // Canonicalize.
3589 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3590 Protocols[I] = Protocols[I]->getCanonicalDecl();
3591
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003592 // Remove duplicates.
3593 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3594 NumProtocols = ProtocolsEnd-Protocols;
3595}
3596
John McCall8b07ec22010-05-15 11:32:37 +00003597QualType ASTContext::getObjCObjectType(QualType BaseType,
3598 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003599 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003600 // If the base type is an interface and there aren't any protocols
3601 // to add, then the interface type will do just fine.
3602 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3603 return BaseType;
3604
3605 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003606 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003607 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003608 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003609 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3610 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003611
John McCall8b07ec22010-05-15 11:32:37 +00003612 // Build the canonical type, which has the canonical base type and
3613 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003614 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003615 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3616 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3617 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003618 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003619 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003620 unsigned UniqueCount = NumProtocols;
3621
John McCallfc93cf92009-10-22 22:37:11 +00003622 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003623 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3624 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003625 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003626 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3627 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003628 }
3629
3630 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003631 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3632 }
3633
3634 unsigned Size = sizeof(ObjCObjectTypeImpl);
3635 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3636 void *Mem = Allocate(Size, TypeAlignment);
3637 ObjCObjectTypeImpl *T =
3638 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3639
3640 Types.push_back(T);
3641 ObjCObjectTypes.InsertNode(T, InsertPos);
3642 return QualType(T, 0);
3643}
3644
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003645/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3646/// protocol list adopt all protocols in QT's qualified-id protocol
3647/// list.
3648bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3649 ObjCInterfaceDecl *IC) {
3650 if (!QT->isObjCQualifiedIdType())
3651 return false;
3652
3653 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3654 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003655 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003656 if (!IC->ClassImplementsProtocol(Proto, false))
3657 return false;
3658 }
3659 return true;
3660 }
3661 return false;
3662}
3663
3664/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3665/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3666/// of protocols.
3667bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3668 ObjCInterfaceDecl *IDecl) {
3669 if (!QT->isObjCQualifiedIdType())
3670 return false;
3671 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3672 if (!OPT)
3673 return false;
3674 if (!IDecl->hasDefinition())
3675 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003676 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3677 CollectInheritedProtocols(IDecl, InheritedProtocols);
3678 if (InheritedProtocols.empty())
3679 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003680 // Check that if every protocol in list of id<plist> conforms to a protcol
3681 // of IDecl's, then bridge casting is ok.
3682 bool Conforms = false;
3683 for (auto *Proto : OPT->quals()) {
3684 Conforms = false;
3685 for (auto *PI : InheritedProtocols) {
3686 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3687 Conforms = true;
3688 break;
3689 }
3690 }
3691 if (!Conforms)
3692 break;
3693 }
3694 if (Conforms)
3695 return true;
3696
Aaron Ballman83731462014-03-17 16:14:00 +00003697 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003698 // If both the right and left sides have qualifiers.
3699 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003700 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003701 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003702 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003703 break;
3704 }
3705 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003706 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003707 }
3708 return true;
3709}
3710
John McCall8b07ec22010-05-15 11:32:37 +00003711/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3712/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003713QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003714 llvm::FoldingSetNodeID ID;
3715 ObjCObjectPointerType::Profile(ID, ObjectT);
3716
Craig Topper36250ad2014-05-12 05:36:57 +00003717 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003718 if (ObjCObjectPointerType *QT =
3719 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3720 return QualType(QT, 0);
3721
3722 // Find the canonical object type.
3723 QualType Canonical;
3724 if (!ObjectT.isCanonical()) {
3725 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3726
3727 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003728 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3729 }
3730
Douglas Gregorf85bee62010-02-08 22:59:26 +00003731 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003732 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3733 ObjCObjectPointerType *QType =
3734 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003735
Steve Narofffb4330f2009-06-17 22:40:22 +00003736 Types.push_back(QType);
3737 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003738 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003739}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003740
Douglas Gregor1c283312010-08-11 12:19:30 +00003741/// getObjCInterfaceType - Return the unique reference to the type for the
3742/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003743QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3744 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003745 if (Decl->TypeForDecl)
3746 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003747
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003748 if (PrevDecl) {
3749 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3750 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3751 return QualType(PrevDecl->TypeForDecl, 0);
3752 }
3753
Douglas Gregor7671e532011-12-16 16:34:57 +00003754 // Prefer the definition, if there is one.
3755 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3756 Decl = Def;
3757
Douglas Gregor1c283312010-08-11 12:19:30 +00003758 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3759 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3760 Decl->TypeForDecl = T;
3761 Types.push_back(T);
3762 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003763}
3764
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003765/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3766/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003767/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003768/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003769/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003770QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003771 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003772 if (tofExpr->isTypeDependent()) {
3773 llvm::FoldingSetNodeID ID;
3774 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003775
Craig Topper36250ad2014-05-12 05:36:57 +00003776 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003777 DependentTypeOfExprType *Canon
3778 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3779 if (Canon) {
3780 // We already have a "canonical" version of an identical, dependent
3781 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003782 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003783 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003784 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003785 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003786 Canon
3787 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003788 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3789 toe = Canon;
3790 }
3791 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003792 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003793 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003794 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003795 Types.push_back(toe);
3796 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003797}
3798
Steve Naroffa773cd52007-08-01 18:02:17 +00003799/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003800/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003801/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003802/// an issue. This doesn't affect the type checker, since it operates
3803/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003804QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003805 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003806 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003807 Types.push_back(tot);
3808 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003809}
3810
Anders Carlssonad6bd352009-06-24 21:24:56 +00003811
Richard Smith8eb1d322014-06-05 20:13:13 +00003812/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3813/// nodes. This would never be helpful, since each such type has its own
3814/// expression, and would not give a significant memory saving, since there
3815/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003816QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003817 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003818
3819 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003820 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003821 // unique dependent type. Two such decltype-specifiers refer to the same
3822 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003823 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003824 llvm::FoldingSetNodeID ID;
3825 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003826
Craig Topper36250ad2014-05-12 05:36:57 +00003827 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003828 DependentDecltypeType *Canon
3829 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003830 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003831 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003832 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003833 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003834 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003835 dt = new (*this, TypeAlignment)
3836 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003837 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003838 dt = new (*this, TypeAlignment)
3839 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003840 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003841 Types.push_back(dt);
3842 return QualType(dt, 0);
3843}
3844
Alexis Hunte852b102011-05-24 22:41:36 +00003845/// getUnaryTransformationType - We don't unique these, since the memory
3846/// savings are minimal and these are rare.
3847QualType ASTContext::getUnaryTransformType(QualType BaseType,
3848 QualType UnderlyingType,
3849 UnaryTransformType::UTTKind Kind)
3850 const {
3851 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003852 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3853 Kind,
3854 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003855 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003856 Types.push_back(Ty);
3857 return QualType(Ty, 0);
3858}
3859
Richard Smith2a7d4812013-05-04 07:00:32 +00003860/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3861/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3862/// canonical deduced-but-dependent 'auto' type.
3863QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003864 bool IsDependent) const {
3865 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003866 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003867
Richard Smith2a7d4812013-05-04 07:00:32 +00003868 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003869 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003870 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003871 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003872 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3873 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003874
Richard Smith74aeef52013-04-26 16:15:35 +00003875 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003876 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003877 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003878 Types.push_back(AT);
3879 if (InsertPos)
3880 AutoTypes.InsertNode(AT, InsertPos);
3881 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003882}
3883
Eli Friedman0dfb8892011-10-06 23:00:33 +00003884/// getAtomicType - Return the uniqued reference to the atomic type for
3885/// the given value type.
3886QualType ASTContext::getAtomicType(QualType T) const {
3887 // Unique pointers, to guarantee there is only one pointer of a particular
3888 // structure.
3889 llvm::FoldingSetNodeID ID;
3890 AtomicType::Profile(ID, T);
3891
Craig Topper36250ad2014-05-12 05:36:57 +00003892 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003893 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3894 return QualType(AT, 0);
3895
3896 // If the atomic value type isn't canonical, this won't be a canonical type
3897 // either, so fill in the canonical type field.
3898 QualType Canonical;
3899 if (!T.isCanonical()) {
3900 Canonical = getAtomicType(getCanonicalType(T));
3901
3902 // Get the new insert position for the node we care about.
3903 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003904 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003905 }
3906 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3907 Types.push_back(New);
3908 AtomicTypes.InsertNode(New, InsertPos);
3909 return QualType(New, 0);
3910}
3911
Richard Smith02e85f32011-04-14 22:09:26 +00003912/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3913QualType ASTContext::getAutoDeductType() const {
3914 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003915 AutoDeductTy = QualType(
3916 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003917 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003918 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003919 return AutoDeductTy;
3920}
3921
3922/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3923QualType ASTContext::getAutoRRefDeductType() const {
3924 if (AutoRRefDeductTy.isNull())
3925 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3926 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3927 return AutoRRefDeductTy;
3928}
3929
Chris Lattnerfb072462007-01-23 05:45:31 +00003930/// getTagDeclType - Return the unique reference to the type for the
3931/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003932QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003933 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003934 // FIXME: What is the design on getTagDeclType when it requires casting
3935 // away const? mutable?
3936 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003937}
3938
Mike Stump11289f42009-09-09 15:08:12 +00003939/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3940/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3941/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003942CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003943 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003944}
Chris Lattnerfb072462007-01-23 05:45:31 +00003945
Hans Wennborg27541db2011-10-27 08:29:09 +00003946/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3947CanQualType ASTContext::getIntMaxType() const {
3948 return getFromTargetType(Target->getIntMaxType());
3949}
3950
3951/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3952CanQualType ASTContext::getUIntMaxType() const {
3953 return getFromTargetType(Target->getUIntMaxType());
3954}
3955
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003956/// getSignedWCharType - Return the type of "signed wchar_t".
3957/// Used when in C++, as a GCC extension.
3958QualType ASTContext::getSignedWCharType() const {
3959 // FIXME: derive from "Target" ?
3960 return WCharTy;
3961}
3962
3963/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3964/// Used when in C++, as a GCC extension.
3965QualType ASTContext::getUnsignedWCharType() const {
3966 // FIXME: derive from "Target" ?
3967 return UnsignedIntTy;
3968}
3969
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003970QualType ASTContext::getIntPtrType() const {
3971 return getFromTargetType(Target->getIntPtrType());
3972}
3973
3974QualType ASTContext::getUIntPtrType() const {
3975 return getCorrespondingUnsignedType(getIntPtrType());
3976}
3977
Hans Wennborg27541db2011-10-27 08:29:09 +00003978/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003979/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3980QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003981 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003982}
3983
Eli Friedman4e91899e2012-11-27 02:58:24 +00003984/// \brief Return the unique type for "pid_t" defined in
3985/// <sys/types.h>. We need this to compute the correct type for vfork().
3986QualType ASTContext::getProcessIDType() const {
3987 return getFromTargetType(Target->getProcessIDType());
3988}
3989
Chris Lattnera21ad802008-04-02 05:18:44 +00003990//===----------------------------------------------------------------------===//
3991// Type Operators
3992//===----------------------------------------------------------------------===//
3993
Jay Foad39c79802011-01-12 09:06:06 +00003994CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003995 // Push qualifiers into arrays, and then discard any remaining
3996 // qualifiers.
3997 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003998 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003999 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004000 QualType Result;
4001 if (isa<ArrayType>(Ty)) {
4002 Result = getArrayDecayedType(QualType(Ty,0));
4003 } else if (isa<FunctionType>(Ty)) {
4004 Result = getPointerType(QualType(Ty, 0));
4005 } else {
4006 Result = QualType(Ty, 0);
4007 }
4008
4009 return CanQualType::CreateUnsafe(Result);
4010}
4011
John McCall6c9dd522011-01-18 07:41:22 +00004012QualType ASTContext::getUnqualifiedArrayType(QualType type,
4013 Qualifiers &quals) {
4014 SplitQualType splitType = type.getSplitUnqualifiedType();
4015
4016 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4017 // the unqualified desugared type and then drops it on the floor.
4018 // We then have to strip that sugar back off with
4019 // getUnqualifiedDesugaredType(), which is silly.
4020 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004021 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004022
4023 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004024 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004025 quals = splitType.Quals;
4026 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004027 }
4028
John McCall6c9dd522011-01-18 07:41:22 +00004029 // Otherwise, recurse on the array's element type.
4030 QualType elementType = AT->getElementType();
4031 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4032
4033 // If that didn't change the element type, AT has no qualifiers, so we
4034 // can just use the results in splitType.
4035 if (elementType == unqualElementType) {
4036 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004037 quals = splitType.Quals;
4038 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004039 }
4040
4041 // Otherwise, add in the qualifiers from the outermost type, then
4042 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004043 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004044
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004045 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004046 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004047 CAT->getSizeModifier(), 0);
4048 }
4049
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004050 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004051 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004052 }
4053
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004054 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004055 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004056 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004057 VAT->getSizeModifier(),
4058 VAT->getIndexTypeCVRQualifiers(),
4059 VAT->getBracketsRange());
4060 }
4061
4062 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004063 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004064 DSAT->getSizeModifier(), 0,
4065 SourceRange());
4066}
4067
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004068/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4069/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4070/// they point to and return true. If T1 and T2 aren't pointer types
4071/// or pointer-to-member types, or if they are not similar at this
4072/// level, returns false and leaves T1 and T2 unchanged. Top-level
4073/// qualifiers on T1 and T2 are ignored. This function will typically
4074/// be called in a loop that successively "unwraps" pointer and
4075/// pointer-to-member types to compare them at each level.
4076bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4077 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4078 *T2PtrType = T2->getAs<PointerType>();
4079 if (T1PtrType && T2PtrType) {
4080 T1 = T1PtrType->getPointeeType();
4081 T2 = T2PtrType->getPointeeType();
4082 return true;
4083 }
4084
4085 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4086 *T2MPType = T2->getAs<MemberPointerType>();
4087 if (T1MPType && T2MPType &&
4088 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4089 QualType(T2MPType->getClass(), 0))) {
4090 T1 = T1MPType->getPointeeType();
4091 T2 = T2MPType->getPointeeType();
4092 return true;
4093 }
4094
David Blaikiebbafb8a2012-03-11 07:00:24 +00004095 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004096 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4097 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4098 if (T1OPType && T2OPType) {
4099 T1 = T1OPType->getPointeeType();
4100 T2 = T2OPType->getPointeeType();
4101 return true;
4102 }
4103 }
4104
4105 // FIXME: Block pointers, too?
4106
4107 return false;
4108}
4109
Jay Foad39c79802011-01-12 09:06:06 +00004110DeclarationNameInfo
4111ASTContext::getNameForTemplate(TemplateName Name,
4112 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004113 switch (Name.getKind()) {
4114 case TemplateName::QualifiedTemplate:
4115 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004116 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004117 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4118 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004119
John McCalld9dfe3a2011-06-30 08:33:18 +00004120 case TemplateName::OverloadedTemplate: {
4121 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4122 // DNInfo work in progress: CHECKME: what about DNLoc?
4123 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4124 }
4125
4126 case TemplateName::DependentTemplate: {
4127 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004128 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004129 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004130 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4131 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004132 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004133 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4134 // DNInfo work in progress: FIXME: source locations?
4135 DeclarationNameLoc DNLoc;
4136 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4137 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4138 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004139 }
4140 }
4141
John McCalld9dfe3a2011-06-30 08:33:18 +00004142 case TemplateName::SubstTemplateTemplateParm: {
4143 SubstTemplateTemplateParmStorage *subst
4144 = Name.getAsSubstTemplateTemplateParm();
4145 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4146 NameLoc);
4147 }
4148
4149 case TemplateName::SubstTemplateTemplateParmPack: {
4150 SubstTemplateTemplateParmPackStorage *subst
4151 = Name.getAsSubstTemplateTemplateParmPack();
4152 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4153 NameLoc);
4154 }
4155 }
4156
4157 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004158}
4159
Jay Foad39c79802011-01-12 09:06:06 +00004160TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004161 switch (Name.getKind()) {
4162 case TemplateName::QualifiedTemplate:
4163 case TemplateName::Template: {
4164 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004165 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004166 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004167 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4168
4169 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004170 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004171 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004172
John McCalld9dfe3a2011-06-30 08:33:18 +00004173 case TemplateName::OverloadedTemplate:
4174 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004175
John McCalld9dfe3a2011-06-30 08:33:18 +00004176 case TemplateName::DependentTemplate: {
4177 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4178 assert(DTN && "Non-dependent template names must refer to template decls.");
4179 return DTN->CanonicalTemplateName;
4180 }
4181
4182 case TemplateName::SubstTemplateTemplateParm: {
4183 SubstTemplateTemplateParmStorage *subst
4184 = Name.getAsSubstTemplateTemplateParm();
4185 return getCanonicalTemplateName(subst->getReplacement());
4186 }
4187
4188 case TemplateName::SubstTemplateTemplateParmPack: {
4189 SubstTemplateTemplateParmPackStorage *subst
4190 = Name.getAsSubstTemplateTemplateParmPack();
4191 TemplateTemplateParmDecl *canonParameter
4192 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4193 TemplateArgument canonArgPack
4194 = getCanonicalTemplateArgument(subst->getArgumentPack());
4195 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4196 }
4197 }
4198
4199 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004200}
4201
Douglas Gregoradee3e32009-11-11 23:06:43 +00004202bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4203 X = getCanonicalTemplateName(X);
4204 Y = getCanonicalTemplateName(Y);
4205 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4206}
4207
Mike Stump11289f42009-09-09 15:08:12 +00004208TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004209ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004210 switch (Arg.getKind()) {
4211 case TemplateArgument::Null:
4212 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004213
Douglas Gregora8e02e72009-07-28 23:00:59 +00004214 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004215 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004216
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004217 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004218 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004219 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004220 }
Mike Stump11289f42009-09-09 15:08:12 +00004221
Eli Friedmanb826a002012-09-26 02:36:12 +00004222 case TemplateArgument::NullPtr:
4223 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4224 /*isNullPtr*/true);
4225
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004226 case TemplateArgument::Template:
4227 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004228
4229 case TemplateArgument::TemplateExpansion:
4230 return TemplateArgument(getCanonicalTemplateName(
4231 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004232 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004233
Douglas Gregora8e02e72009-07-28 23:00:59 +00004234 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004235 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004236
Douglas Gregora8e02e72009-07-28 23:00:59 +00004237 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004238 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004239
Douglas Gregora8e02e72009-07-28 23:00:59 +00004240 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004241 if (Arg.pack_size() == 0)
4242 return Arg;
4243
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004244 TemplateArgument *CanonArgs
4245 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004246 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004247 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004248 AEnd = Arg.pack_end();
4249 A != AEnd; (void)++A, ++Idx)
4250 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004251
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004252 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004253 }
4254 }
4255
4256 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004257 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004258}
4259
Douglas Gregor333489b2009-03-27 23:10:48 +00004260NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004261ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004262 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004263 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004264
4265 switch (NNS->getKind()) {
4266 case NestedNameSpecifier::Identifier:
4267 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004268 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004269 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4270 NNS->getAsIdentifier());
4271
4272 case NestedNameSpecifier::Namespace:
4273 // A namespace is canonical; build a nested-name-specifier with
4274 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004275 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004276 NNS->getAsNamespace()->getOriginalNamespace());
4277
4278 case NestedNameSpecifier::NamespaceAlias:
4279 // A namespace is canonical; build a nested-name-specifier with
4280 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004281 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004282 NNS->getAsNamespaceAlias()->getNamespace()
4283 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004284
4285 case NestedNameSpecifier::TypeSpec:
4286 case NestedNameSpecifier::TypeSpecWithTemplate: {
4287 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004288
4289 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4290 // break it apart into its prefix and identifier, then reconsititute those
4291 // as the canonical nested-name-specifier. This is required to canonicalize
4292 // a dependent nested-name-specifier involving typedefs of dependent-name
4293 // types, e.g.,
4294 // typedef typename T::type T1;
4295 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004296 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4297 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004298 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004299
Eli Friedman5358a0a2012-03-03 04:09:56 +00004300 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4301 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4302 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004303 return NestedNameSpecifier::Create(*this, nullptr, false,
4304 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004305 }
4306
4307 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004308 case NestedNameSpecifier::Super:
4309 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004310 return NNS;
4311 }
4312
David Blaikie8a40f702012-01-17 06:56:22 +00004313 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004314}
4315
Chris Lattner7adf0762008-08-04 07:31:14 +00004316
Jay Foad39c79802011-01-12 09:06:06 +00004317const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004318 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004319 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004320 // Handle the common positive case fast.
4321 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4322 return AT;
4323 }
Mike Stump11289f42009-09-09 15:08:12 +00004324
John McCall8ccfcb52009-09-24 19:53:00 +00004325 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004326 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004327 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004328
John McCall8ccfcb52009-09-24 19:53:00 +00004329 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004330 // implements C99 6.7.3p8: "If the specification of an array type includes
4331 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004332
Chris Lattner7adf0762008-08-04 07:31:14 +00004333 // If we get here, we either have type qualifiers on the type, or we have
4334 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004335 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004336
John McCall33ddac02011-01-19 10:06:00 +00004337 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004338 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004339
Chris Lattner7adf0762008-08-04 07:31:14 +00004340 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004341 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004342 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004343 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004344
Chris Lattner7adf0762008-08-04 07:31:14 +00004345 // Otherwise, we have an array and we have qualifiers on it. Push the
4346 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004347 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004348
Chris Lattner7adf0762008-08-04 07:31:14 +00004349 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4350 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4351 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004352 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004353 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4354 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4355 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004356 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004357
Mike Stump11289f42009-09-09 15:08:12 +00004358 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004359 = dyn_cast<DependentSizedArrayType>(ATy))
4360 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004361 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004362 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004363 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004364 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004365 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004366
Chris Lattner7adf0762008-08-04 07:31:14 +00004367 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004368 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004369 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004370 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004371 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004372 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004373}
4374
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004375QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004376 if (T->isArrayType() || T->isFunctionType())
4377 return getDecayedType(T);
4378 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004379}
4380
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004381QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004382 T = getVariableArrayDecayedType(T);
4383 T = getAdjustedParameterType(T);
4384 return T.getUnqualifiedType();
4385}
4386
David Majnemerd09a51c2015-03-03 01:50:05 +00004387QualType ASTContext::getExceptionObjectType(QualType T) const {
4388 // C++ [except.throw]p3:
4389 // A throw-expression initializes a temporary object, called the exception
4390 // object, the type of which is determined by removing any top-level
4391 // cv-qualifiers from the static type of the operand of throw and adjusting
4392 // the type from "array of T" or "function returning T" to "pointer to T"
4393 // or "pointer to function returning T", [...]
4394 T = getVariableArrayDecayedType(T);
4395 if (T->isArrayType() || T->isFunctionType())
4396 T = getDecayedType(T);
4397 return T.getUnqualifiedType();
4398}
4399
Chris Lattnera21ad802008-04-02 05:18:44 +00004400/// getArrayDecayedType - Return the properly qualified result of decaying the
4401/// specified array type to a pointer. This operation is non-trivial when
4402/// handling typedefs etc. The canonical type of "T" must be an array type,
4403/// this returns a pointer to a properly qualified element of the array.
4404///
4405/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004406QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004407 // Get the element type with 'getAsArrayType' so that we don't lose any
4408 // typedefs in the element type of the array. This also handles propagation
4409 // of type qualifiers from the array type into the element type if present
4410 // (C99 6.7.3p8).
4411 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4412 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004413
Chris Lattner7adf0762008-08-04 07:31:14 +00004414 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004415
4416 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004417 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004418}
4419
John McCall33ddac02011-01-19 10:06:00 +00004420QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4421 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004422}
4423
John McCall33ddac02011-01-19 10:06:00 +00004424QualType ASTContext::getBaseElementType(QualType type) const {
4425 Qualifiers qs;
4426 while (true) {
4427 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004428 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004429 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004430
John McCall33ddac02011-01-19 10:06:00 +00004431 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004432 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004433 }
Mike Stump11289f42009-09-09 15:08:12 +00004434
John McCall33ddac02011-01-19 10:06:00 +00004435 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004436}
4437
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004438/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004439uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004440ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4441 uint64_t ElementCount = 1;
4442 do {
4443 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004444 CA = dyn_cast_or_null<ConstantArrayType>(
4445 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004446 } while (CA);
4447 return ElementCount;
4448}
4449
Steve Naroff0af91202007-04-27 21:51:21 +00004450/// getFloatingRank - Return a relative rank for floating point types.
4451/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004452static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004453 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004454 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004455
John McCall9dd450b2009-09-21 23:43:11 +00004456 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4457 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004458 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004459 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004460 case BuiltinType::Float: return FloatRank;
4461 case BuiltinType::Double: return DoubleRank;
4462 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004463 }
4464}
4465
Mike Stump11289f42009-09-09 15:08:12 +00004466/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4467/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004468/// 'typeDomain' is a real floating point or complex type.
4469/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004470QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4471 QualType Domain) const {
4472 FloatingRank EltRank = getFloatingRank(Size);
4473 if (Domain->isComplexType()) {
4474 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004475 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004476 case FloatRank: return FloatComplexTy;
4477 case DoubleRank: return DoubleComplexTy;
4478 case LongDoubleRank: return LongDoubleComplexTy;
4479 }
Steve Naroff0af91202007-04-27 21:51:21 +00004480 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004481
4482 assert(Domain->isRealFloatingType() && "Unknown domain!");
4483 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004484 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004485 case FloatRank: return FloatTy;
4486 case DoubleRank: return DoubleTy;
4487 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004488 }
David Blaikief47fa302012-01-17 02:30:50 +00004489 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004490}
4491
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004492/// getFloatingTypeOrder - Compare the rank of the two specified floating
4493/// point types, ignoring the domain of the type (i.e. 'double' ==
4494/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004495/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004496int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004497 FloatingRank LHSR = getFloatingRank(LHS);
4498 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004499
Chris Lattnerb90739d2008-04-06 23:38:49 +00004500 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004501 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004502 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004503 return 1;
4504 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004505}
4506
Chris Lattner76a00cf2008-04-06 22:59:24 +00004507/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4508/// routine will assert if passed a built-in type that isn't an integer or enum,
4509/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004510unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004511 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004512
Chris Lattner76a00cf2008-04-06 22:59:24 +00004513 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004514 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004515 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004516 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004517 case BuiltinType::Char_S:
4518 case BuiltinType::Char_U:
4519 case BuiltinType::SChar:
4520 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004521 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004522 case BuiltinType::Short:
4523 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004524 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004525 case BuiltinType::Int:
4526 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004527 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004528 case BuiltinType::Long:
4529 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004530 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004531 case BuiltinType::LongLong:
4532 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004533 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004534 case BuiltinType::Int128:
4535 case BuiltinType::UInt128:
4536 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004537 }
4538}
4539
Eli Friedman629ffb92009-08-20 04:21:42 +00004540/// \brief Whether this is a promotable bitfield reference according
4541/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4542///
4543/// \returns the type this bit-field will promote to, or NULL if no
4544/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004545QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004546 if (E->isTypeDependent() || E->isValueDependent())
4547 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004548
4549 // FIXME: We should not do this unless E->refersToBitField() is true. This
4550 // matters in C where getSourceBitField() will find bit-fields for various
4551 // cases where the source expression is not a bit-field designator.
4552
John McCalld25db7e2013-05-06 21:39:12 +00004553 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004554 if (!Field)
4555 return QualType();
4556
4557 QualType FT = Field->getType();
4558
Richard Smithcaf33902011-10-10 18:28:20 +00004559 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004560 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004561 // C++ [conv.prom]p5:
4562 // A prvalue for an integral bit-field can be converted to a prvalue of type
4563 // int if int can represent all the values of the bit-field; otherwise, it
4564 // can be converted to unsigned int if unsigned int can represent all the
4565 // values of the bit-field. If the bit-field is larger yet, no integral
4566 // promotion applies to it.
4567 // C11 6.3.1.1/2:
4568 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4569 // If an int can represent all values of the original type (as restricted by
4570 // the width, for a bit-field), the value is converted to an int; otherwise,
4571 // it is converted to an unsigned int.
4572 //
4573 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4574 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004575 if (BitWidth < IntSize)
4576 return IntTy;
4577
4578 if (BitWidth == IntSize)
4579 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4580
4581 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004582 // like the base type. GCC has some weird bugs in this area that we
4583 // deliberately do not follow (GCC follows a pre-standard resolution to
4584 // C's DR315 which treats bit-width as being part of the type, and this leaks
4585 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004586 return QualType();
4587}
4588
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004589/// getPromotedIntegerType - Returns the type that Promotable will
4590/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4591/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004592QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004593 assert(!Promotable.isNull());
4594 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004595 if (const EnumType *ET = Promotable->getAs<EnumType>())
4596 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004597
4598 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4599 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4600 // (3.9.1) can be converted to a prvalue of the first of the following
4601 // types that can represent all the values of its underlying type:
4602 // int, unsigned int, long int, unsigned long int, long long int, or
4603 // unsigned long long int [...]
4604 // FIXME: Is there some better way to compute this?
4605 if (BT->getKind() == BuiltinType::WChar_S ||
4606 BT->getKind() == BuiltinType::WChar_U ||
4607 BT->getKind() == BuiltinType::Char16 ||
4608 BT->getKind() == BuiltinType::Char32) {
4609 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4610 uint64_t FromSize = getTypeSize(BT);
4611 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4612 LongLongTy, UnsignedLongLongTy };
4613 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4614 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4615 if (FromSize < ToSize ||
4616 (FromSize == ToSize &&
4617 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4618 return PromoteTypes[Idx];
4619 }
4620 llvm_unreachable("char type should fit into long long");
4621 }
4622 }
4623
4624 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004625 if (Promotable->isSignedIntegerType())
4626 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004627 uint64_t PromotableSize = getIntWidth(Promotable);
4628 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004629 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4630 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4631}
4632
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004633/// \brief Recurses in pointer/array types until it finds an objc retainable
4634/// type and returns its ownership.
4635Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4636 while (!T.isNull()) {
4637 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4638 return T.getObjCLifetime();
4639 if (T->isArrayType())
4640 T = getBaseElementType(T);
4641 else if (const PointerType *PT = T->getAs<PointerType>())
4642 T = PT->getPointeeType();
4643 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004644 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004645 else
4646 break;
4647 }
4648
4649 return Qualifiers::OCL_None;
4650}
4651
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004652static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4653 // Incomplete enum types are not treated as integer types.
4654 // FIXME: In C++, enum types are never integer types.
4655 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4656 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004657 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004658}
4659
Mike Stump11289f42009-09-09 15:08:12 +00004660/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004661/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004662/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004663int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004664 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4665 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004666
4667 // Unwrap enums to their underlying type.
4668 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4669 LHSC = getIntegerTypeForEnum(ET);
4670 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4671 RHSC = getIntegerTypeForEnum(ET);
4672
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004673 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004674
Chris Lattner76a00cf2008-04-06 22:59:24 +00004675 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4676 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004677
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004678 unsigned LHSRank = getIntegerRank(LHSC);
4679 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004680
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004681 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4682 if (LHSRank == RHSRank) return 0;
4683 return LHSRank > RHSRank ? 1 : -1;
4684 }
Mike Stump11289f42009-09-09 15:08:12 +00004685
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004686 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4687 if (LHSUnsigned) {
4688 // If the unsigned [LHS] type is larger, return it.
4689 if (LHSRank >= RHSRank)
4690 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004691
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004692 // If the signed type can represent all values of the unsigned type, it
4693 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004694 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004695 return -1;
4696 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004697
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004698 // If the unsigned [RHS] type is larger, return it.
4699 if (RHSRank >= LHSRank)
4700 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004701
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004702 // If the signed type can represent all values of the unsigned type, it
4703 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004704 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004705 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004706}
Anders Carlsson98f07902007-08-17 05:31:46 +00004707
Mike Stump11289f42009-09-09 15:08:12 +00004708// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004709QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004710 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004711 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004712 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004713
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004714 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004715
Anders Carlsson98f07902007-08-17 05:31:46 +00004716 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004717 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004718 // int flags;
4719 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004720 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004721 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004722 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004723 FieldTypes[3] = LongTy;
4724
Anders Carlsson98f07902007-08-17 05:31:46 +00004725 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004726 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004727 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004728 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004729 SourceLocation(), nullptr,
4730 FieldTypes[i], /*TInfo=*/nullptr,
4731 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004732 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004733 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004734 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004735 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004736 }
4737
Douglas Gregord5058122010-02-11 01:19:42 +00004738 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004739 }
Mike Stump11289f42009-09-09 15:08:12 +00004740
Anders Carlsson98f07902007-08-17 05:31:46 +00004741 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004742}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004743
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004744QualType ASTContext::getObjCSuperType() const {
4745 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004746 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004747 TUDecl->addDecl(ObjCSuperTypeDecl);
4748 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4749 }
4750 return ObjCSuperType;
4751}
4752
Douglas Gregor512b0772009-04-23 22:29:11 +00004753void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004754 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004755 assert(Rec && "Invalid CFConstantStringType");
4756 CFConstantStringTypeDecl = Rec->getDecl();
4757}
4758
Jay Foad39c79802011-01-12 09:06:06 +00004759QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004760 if (BlockDescriptorType)
4761 return getTagDeclType(BlockDescriptorType);
4762
Alp Toker2dea15b2013-12-17 01:22:38 +00004763 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004764 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004765 RD = buildImplicitRecord("__block_descriptor");
4766 RD->startDefinition();
4767
Mike Stumpd0153282009-10-20 02:12:22 +00004768 QualType FieldTypes[] = {
4769 UnsignedLongTy,
4770 UnsignedLongTy,
4771 };
4772
Craig Topperd6d31ac2013-07-15 08:24:27 +00004773 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004774 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004775 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004776 };
4777
4778 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004779 FieldDecl *Field = FieldDecl::Create(
4780 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004781 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4782 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004783 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004784 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004785 }
4786
Alp Toker2dea15b2013-12-17 01:22:38 +00004787 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004788
Alp Toker2dea15b2013-12-17 01:22:38 +00004789 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004790
4791 return getTagDeclType(BlockDescriptorType);
4792}
4793
Jay Foad39c79802011-01-12 09:06:06 +00004794QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004795 if (BlockDescriptorExtendedType)
4796 return getTagDeclType(BlockDescriptorExtendedType);
4797
Alp Toker2dea15b2013-12-17 01:22:38 +00004798 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004799 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004800 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4801 RD->startDefinition();
4802
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004803 QualType FieldTypes[] = {
4804 UnsignedLongTy,
4805 UnsignedLongTy,
4806 getPointerType(VoidPtrTy),
4807 getPointerType(VoidPtrTy)
4808 };
4809
Craig Topperd6d31ac2013-07-15 08:24:27 +00004810 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004811 "reserved",
4812 "Size",
4813 "CopyFuncPtr",
4814 "DestroyFuncPtr"
4815 };
4816
4817 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004818 FieldDecl *Field = FieldDecl::Create(
4819 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004820 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4821 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004822 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004823 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004824 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004825 }
4826
Alp Toker2dea15b2013-12-17 01:22:38 +00004827 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004828
Alp Toker2dea15b2013-12-17 01:22:38 +00004829 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004830 return getTagDeclType(BlockDescriptorExtendedType);
4831}
4832
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004833/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4834/// requires copy/dispose. Note that this must match the logic
4835/// in buildByrefHelpers.
4836bool ASTContext::BlockRequiresCopying(QualType Ty,
4837 const VarDecl *D) {
4838 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4839 const Expr *copyExpr = getBlockVarCopyInits(D);
4840 if (!copyExpr && record->hasTrivialDestructor()) return false;
4841
Mike Stump94967902009-10-21 18:16:27 +00004842 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004843 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004844
4845 if (!Ty->isObjCRetainableType()) return false;
4846
4847 Qualifiers qs = Ty.getQualifiers();
4848
4849 // If we have lifetime, that dominates.
4850 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4851 assert(getLangOpts().ObjCAutoRefCount);
4852
4853 switch (lifetime) {
4854 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4855
4856 // These are just bits as far as the runtime is concerned.
4857 case Qualifiers::OCL_ExplicitNone:
4858 case Qualifiers::OCL_Autoreleasing:
4859 return false;
4860
4861 // Tell the runtime that this is ARC __weak, called by the
4862 // byref routines.
4863 case Qualifiers::OCL_Weak:
4864 // ARC __strong __block variables need to be retained.
4865 case Qualifiers::OCL_Strong:
4866 return true;
4867 }
4868 llvm_unreachable("fell out of lifetime switch!");
4869 }
4870 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4871 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004872}
4873
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004874bool ASTContext::getByrefLifetime(QualType Ty,
4875 Qualifiers::ObjCLifetime &LifeTime,
4876 bool &HasByrefExtendedLayout) const {
4877
4878 if (!getLangOpts().ObjC1 ||
4879 getLangOpts().getGC() != LangOptions::NonGC)
4880 return false;
4881
4882 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004883 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004884 HasByrefExtendedLayout = true;
4885 LifeTime = Qualifiers::OCL_None;
4886 }
4887 else if (getLangOpts().ObjCAutoRefCount)
4888 LifeTime = Ty.getObjCLifetime();
4889 // MRR.
4890 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4891 LifeTime = Qualifiers::OCL_ExplicitNone;
4892 else
4893 LifeTime = Qualifiers::OCL_None;
4894 return true;
4895}
4896
Douglas Gregorbab8a962011-09-08 01:46:34 +00004897TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4898 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004899 ObjCInstanceTypeDecl =
4900 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004901 return ObjCInstanceTypeDecl;
4902}
4903
Anders Carlsson18acd442007-10-29 06:33:42 +00004904// This returns true if a type has been typedefed to BOOL:
4905// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004906static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004907 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004908 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4909 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004910
Anders Carlssond8499822007-10-29 05:01:08 +00004911 return false;
4912}
4913
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004914/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004915/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004916CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004917 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4918 return CharUnits::Zero();
4919
Ken Dyck40775002010-01-11 17:06:35 +00004920 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004921
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004922 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004923 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004924 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004925 // Treat arrays as pointers, since that's how they're passed in.
4926 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004927 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004928 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004929}
4930
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004931bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4932 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4933 VD->getType()->isIntegralOrEnumerationType() &&
Alexey Bataev15413ea2015-05-20 11:57:02 +00004934 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004935}
4936
Ken Dyck40775002010-01-11 17:06:35 +00004937static inline
4938std::string charUnitsToString(const CharUnits &CU) {
4939 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004940}
4941
John McCall351762c2011-02-07 10:33:21 +00004942/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004943/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004944std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4945 std::string S;
4946
David Chisnall950a9512009-11-17 19:33:30 +00004947 const BlockDecl *Decl = Expr->getBlockDecl();
4948 QualType BlockTy =
4949 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4950 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004951 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004952 getObjCEncodingForMethodParameter(
4953 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4954 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004955 else
Alp Toker314cc812014-01-25 16:55:45 +00004956 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004957 // Compute size of all parameters.
4958 // Start with computing size of a pointer in number of bytes.
4959 // FIXME: There might(should) be a better way of doing this computation!
4960 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004961 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4962 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004963 for (auto PI : Decl->params()) {
4964 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004965 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004966 if (sz.isZero())
4967 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004968 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004969 ParmOffset += sz;
4970 }
4971 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004972 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004973 // Block pointer and offset.
4974 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004975
4976 // Argument types.
4977 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004978 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004979 QualType PType = PVDecl->getOriginalType();
4980 if (const ArrayType *AT =
4981 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4982 // Use array's original type only if it has known number of
4983 // elements.
4984 if (!isa<ConstantArrayType>(AT))
4985 PType = PVDecl->getType();
4986 } else if (PType->isFunctionType())
4987 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004988 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004989 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4990 S, true /*Extended*/);
4991 else
4992 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004993 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004994 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004995 }
John McCall351762c2011-02-07 10:33:21 +00004996
4997 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004998}
4999
Douglas Gregora9d84932011-05-27 01:19:52 +00005000bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005001 std::string& S) {
5002 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005003 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005004 CharUnits ParmOffset;
5005 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005006 for (auto PI : Decl->params()) {
5007 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005008 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005009 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005010 continue;
5011
David Chisnall50e4eba2010-12-30 14:05:53 +00005012 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005013 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005014 ParmOffset += sz;
5015 }
5016 S += charUnitsToString(ParmOffset);
5017 ParmOffset = CharUnits::Zero();
5018
5019 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005020 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005021 QualType PType = PVDecl->getOriginalType();
5022 if (const ArrayType *AT =
5023 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5024 // Use array's original type only if it has known number of
5025 // elements.
5026 if (!isa<ConstantArrayType>(AT))
5027 PType = PVDecl->getType();
5028 } else if (PType->isFunctionType())
5029 PType = PVDecl->getType();
5030 getObjCEncodingForType(PType, S);
5031 S += charUnitsToString(ParmOffset);
5032 ParmOffset += getObjCEncodingTypeSize(PType);
5033 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005034
5035 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005036}
5037
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005038/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5039/// method parameter or return type. If Extended, include class names and
5040/// block object types.
5041void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5042 QualType T, std::string& S,
5043 bool Extended) const {
5044 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5045 getObjCEncodingForTypeQualifier(QT, S);
5046 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005047 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005048 true /*OutermostType*/,
5049 false /*EncodingProperty*/,
5050 false /*StructField*/,
5051 Extended /*EncodeBlockParameters*/,
5052 Extended /*EncodeClassNames*/);
5053}
5054
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005055/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005056/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005057bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005058 std::string& S,
5059 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005060 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005061 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005062 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5063 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005064 // Compute size of all parameters.
5065 // Start with computing size of a pointer in number of bytes.
5066 // FIXME: There might(should) be a better way of doing this computation!
5067 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005068 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005069 // The first two arguments (self and _cmd) are pointers; account for
5070 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005071 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005072 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005073 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005074 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005075 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005076 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005077 continue;
5078
Ken Dyck40775002010-01-11 17:06:35 +00005079 assert (sz.isPositive() &&
5080 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005081 ParmOffset += sz;
5082 }
Ken Dyck40775002010-01-11 17:06:35 +00005083 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005084 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005085 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005086
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005087 // Argument types.
5088 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005089 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005090 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005091 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005092 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005093 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005094 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5095 // Use array's original type only if it has known number of
5096 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005097 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005098 PType = PVDecl->getType();
5099 } else if (PType->isFunctionType())
5100 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005101 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5102 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005103 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005104 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005105 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005106
5107 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005108}
5109
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005110ObjCPropertyImplDecl *
5111ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5112 const ObjCPropertyDecl *PD,
5113 const Decl *Container) const {
5114 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005115 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005116 if (const ObjCCategoryImplDecl *CID =
5117 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005118 for (auto *PID : CID->property_impls())
5119 if (PID->getPropertyDecl() == PD)
5120 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005121 } else {
5122 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5123 for (auto *PID : OID->property_impls())
5124 if (PID->getPropertyDecl() == PD)
5125 return PID;
5126 }
5127 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005128}
5129
Daniel Dunbar4932b362008-08-28 04:38:10 +00005130/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005131/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005132/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5133/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005134/// Property attributes are stored as a comma-delimited C string. The simple
5135/// attributes readonly and bycopy are encoded as single characters. The
5136/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5137/// encoded as single characters, followed by an identifier. Property types
5138/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005139/// these attributes are defined by the following enumeration:
5140/// @code
5141/// enum PropertyAttributes {
5142/// kPropertyReadOnly = 'R', // property is read-only.
5143/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5144/// kPropertyByref = '&', // property is a reference to the value last assigned
5145/// kPropertyDynamic = 'D', // property is dynamic
5146/// kPropertyGetter = 'G', // followed by getter selector name
5147/// kPropertySetter = 'S', // followed by setter selector name
5148/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005149/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005150/// kPropertyWeak = 'W' // 'weak' property
5151/// kPropertyStrong = 'P' // property GC'able
5152/// kPropertyNonAtomic = 'N' // property non-atomic
5153/// };
5154/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005155void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005156 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005157 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005158 // Collect information from the property implementation decl(s).
5159 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005160 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005161
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005162 if (ObjCPropertyImplDecl *PropertyImpDecl =
5163 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5164 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5165 Dynamic = true;
5166 else
5167 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005168 }
5169
5170 // FIXME: This is not very efficient.
5171 S = "T";
5172
5173 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005174 // GCC has some special rules regarding encoding of properties which
5175 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005176 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005177
5178 if (PD->isReadOnly()) {
5179 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005180 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5181 S += ",C";
5182 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5183 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005184 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5185 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005186 } else {
5187 switch (PD->getSetterKind()) {
5188 case ObjCPropertyDecl::Assign: break;
5189 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005190 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005191 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005192 }
5193 }
5194
5195 // It really isn't clear at all what this means, since properties
5196 // are "dynamic by default".
5197 if (Dynamic)
5198 S += ",D";
5199
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005200 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5201 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005202
Daniel Dunbar4932b362008-08-28 04:38:10 +00005203 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5204 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005205 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005206 }
5207
5208 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5209 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005210 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005211 }
5212
5213 if (SynthesizePID) {
5214 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5215 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005216 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005217 }
5218
5219 // FIXME: OBJCGC: weak & strong
5220}
5221
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005222/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005223/// Another legacy compatibility encoding: 32-bit longs are encoded as
5224/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005225/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5226///
5227void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005228 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005229 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005230 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005231 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005232 else
Jay Foad39c79802011-01-12 09:06:06 +00005233 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005234 PointeeTy = IntTy;
5235 }
5236 }
5237}
5238
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005239void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005240 const FieldDecl *Field,
5241 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005242 // We follow the behavior of gcc, expanding structures which are
5243 // directly pointed to, and expanding embedded structures. Note that
5244 // these rules are sufficient to prevent recursive encoding of the
5245 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005246 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005247 true /* outermost type */, false, false,
5248 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005249}
5250
Joe Groff98ac7d22014-07-07 22:25:15 +00005251void ASTContext::getObjCEncodingForPropertyType(QualType T,
5252 std::string& S) const {
5253 // Encode result type.
5254 // GCC has some special rules regarding encoding of properties which
5255 // closely resembles encoding of ivars.
5256 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5257 true /* outermost type */,
5258 true /* encoding property */);
5259}
5260
John McCall393a78d2012-12-20 02:45:14 +00005261static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5262 BuiltinType::Kind kind) {
5263 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005264 case BuiltinType::Void: return 'v';
5265 case BuiltinType::Bool: return 'B';
5266 case BuiltinType::Char_U:
5267 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005268 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005269 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005270 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005271 case BuiltinType::UInt: return 'I';
5272 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005273 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005274 case BuiltinType::UInt128: return 'T';
5275 case BuiltinType::ULongLong: return 'Q';
5276 case BuiltinType::Char_S:
5277 case BuiltinType::SChar: return 'c';
5278 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005279 case BuiltinType::WChar_S:
5280 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005281 case BuiltinType::Int: return 'i';
5282 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005283 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005284 case BuiltinType::LongLong: return 'q';
5285 case BuiltinType::Int128: return 't';
5286 case BuiltinType::Float: return 'f';
5287 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005288 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005289 case BuiltinType::NullPtr: return '*'; // like char*
5290
5291 case BuiltinType::Half:
5292 // FIXME: potentially need @encodes for these!
5293 return ' ';
5294
5295 case BuiltinType::ObjCId:
5296 case BuiltinType::ObjCClass:
5297 case BuiltinType::ObjCSel:
5298 llvm_unreachable("@encoding ObjC primitive type");
5299
5300 // OpenCL and placeholder types don't need @encodings.
5301 case BuiltinType::OCLImage1d:
5302 case BuiltinType::OCLImage1dArray:
5303 case BuiltinType::OCLImage1dBuffer:
5304 case BuiltinType::OCLImage2d:
5305 case BuiltinType::OCLImage2dArray:
5306 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005307 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005308 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005309 case BuiltinType::Dependent:
5310#define BUILTIN_TYPE(KIND, ID)
5311#define PLACEHOLDER_TYPE(KIND, ID) \
5312 case BuiltinType::KIND:
5313#include "clang/AST/BuiltinTypes.def"
5314 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005315 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005316 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005317}
5318
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005319static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5320 EnumDecl *Enum = ET->getDecl();
5321
5322 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5323 if (!Enum->isFixed())
5324 return 'i';
5325
5326 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005327 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5328 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005329}
5330
Jay Foad39c79802011-01-12 09:06:06 +00005331static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005332 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005333 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005334 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005335 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5336 // The GNU runtime requires more information; bitfields are encoded as b,
5337 // then the offset (in bits) of the first element, then the type of the
5338 // bitfield, then the size in bits. For example, in this structure:
5339 //
5340 // struct
5341 // {
5342 // int integer;
5343 // int flags:2;
5344 // };
5345 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5346 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5347 // information is not especially sensible, but we're stuck with it for
5348 // compatibility with GCC, although providing it breaks anything that
5349 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005350 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005351 const RecordDecl *RD = FD->getParent();
5352 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005353 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005354 if (const EnumType *ET = T->getAs<EnumType>())
5355 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005356 else {
5357 const BuiltinType *BT = T->castAs<BuiltinType>();
5358 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5359 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005360 }
Richard Smithcaf33902011-10-10 18:28:20 +00005361 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005362}
5363
Daniel Dunbar07d07852009-10-18 21:17:35 +00005364// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005365void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5366 bool ExpandPointedToStructures,
5367 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005368 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005369 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005370 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005371 bool StructField,
5372 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005373 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005374 bool EncodePointerToObjCTypedef,
5375 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005376 CanQualType CT = getCanonicalType(T);
5377 switch (CT->getTypeClass()) {
5378 case Type::Builtin:
5379 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005380 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005381 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005382 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5383 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5384 else
5385 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005386 return;
Mike Stump11289f42009-09-09 15:08:12 +00005387
John McCall393a78d2012-12-20 02:45:14 +00005388 case Type::Complex: {
5389 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005390 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005391 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005392 return;
5393 }
John McCall393a78d2012-12-20 02:45:14 +00005394
5395 case Type::Atomic: {
5396 const AtomicType *AT = T->castAs<AtomicType>();
5397 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005398 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005399 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005400 }
John McCall393a78d2012-12-20 02:45:14 +00005401
5402 // encoding for pointer or reference types.
5403 case Type::Pointer:
5404 case Type::LValueReference:
5405 case Type::RValueReference: {
5406 QualType PointeeTy;
5407 if (isa<PointerType>(CT)) {
5408 const PointerType *PT = T->castAs<PointerType>();
5409 if (PT->isObjCSelType()) {
5410 S += ':';
5411 return;
5412 }
5413 PointeeTy = PT->getPointeeType();
5414 } else {
5415 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5416 }
5417
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005418 bool isReadOnly = false;
5419 // For historical/compatibility reasons, the read-only qualifier of the
5420 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5421 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005422 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005423 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005424 if (OutermostType && T.isConstQualified()) {
5425 isReadOnly = true;
5426 S += 'r';
5427 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005428 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005429 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005430 while (P->getAs<PointerType>())
5431 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005432 if (P.isConstQualified()) {
5433 isReadOnly = true;
5434 S += 'r';
5435 }
5436 }
5437 if (isReadOnly) {
5438 // Another legacy compatibility encoding. Some ObjC qualifier and type
5439 // combinations need to be rearranged.
5440 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005441 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005442 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005443 }
Mike Stump11289f42009-09-09 15:08:12 +00005444
Anders Carlssond8499822007-10-29 05:01:08 +00005445 if (PointeeTy->isCharType()) {
5446 // char pointer types should be encoded as '*' unless it is a
5447 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005448 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005449 S += '*';
5450 return;
5451 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005452 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005453 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5454 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5455 S += '#';
5456 return;
5457 }
5458 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5459 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5460 S += '@';
5461 return;
5462 }
5463 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005464 }
Anders Carlssond8499822007-10-29 05:01:08 +00005465 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005466 getLegacyIntegralTypeEncoding(PointeeTy);
5467
Mike Stump11289f42009-09-09 15:08:12 +00005468 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005469 nullptr, false, false, false, false, false, false,
5470 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005471 return;
5472 }
John McCall393a78d2012-12-20 02:45:14 +00005473
5474 case Type::ConstantArray:
5475 case Type::IncompleteArray:
5476 case Type::VariableArray: {
5477 const ArrayType *AT = cast<ArrayType>(CT);
5478
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005479 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005480 // Incomplete arrays are encoded as a pointer to the array element.
5481 S += '^';
5482
Mike Stump11289f42009-09-09 15:08:12 +00005483 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005484 false, ExpandStructures, FD);
5485 } else {
5486 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005487
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005488 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5489 S += llvm::utostr(CAT->getSize().getZExtValue());
5490 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005491 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005492 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5493 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005494 S += '0';
5495 }
Mike Stump11289f42009-09-09 15:08:12 +00005496
5497 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005498 false, ExpandStructures, FD,
5499 false, false, false, false, false, false,
5500 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005501 S += ']';
5502 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005503 return;
5504 }
Mike Stump11289f42009-09-09 15:08:12 +00005505
John McCall393a78d2012-12-20 02:45:14 +00005506 case Type::FunctionNoProto:
5507 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005508 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005509 return;
Mike Stump11289f42009-09-09 15:08:12 +00005510
John McCall393a78d2012-12-20 02:45:14 +00005511 case Type::Record: {
5512 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005513 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005514 // Anonymous structures print as '?'
5515 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5516 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005517 if (ClassTemplateSpecializationDecl *Spec
5518 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5519 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005520 llvm::raw_string_ostream OS(S);
5521 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005522 TemplateArgs.data(),
5523 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005524 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005525 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005526 } else {
5527 S += '?';
5528 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005529 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005530 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005531 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005532 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005533 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005534 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005535 if (FD) {
5536 S += '"';
5537 S += Field->getNameAsString();
5538 S += '"';
5539 }
Mike Stump11289f42009-09-09 15:08:12 +00005540
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005541 // Special case bit-fields.
5542 if (Field->isBitField()) {
5543 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005544 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005545 } else {
5546 QualType qt = Field->getType();
5547 getLegacyIntegralTypeEncoding(qt);
5548 getObjCEncodingForTypeImpl(qt, S, false, true,
5549 FD, /*OutermostType*/false,
5550 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005551 /*StructField*/true,
5552 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005553 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005554 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005555 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005556 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005557 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005558 return;
5559 }
Mike Stump11289f42009-09-09 15:08:12 +00005560
John McCall393a78d2012-12-20 02:45:14 +00005561 case Type::BlockPointer: {
5562 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005563 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005564 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005565 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005566
5567 S += '<';
5568 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005569 getObjCEncodingForTypeImpl(
5570 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5571 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005572 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5573 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005574 // Block self
5575 S += "@?";
5576 // Block parameters
5577 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005578 for (const auto &I : FPT->param_types())
5579 getObjCEncodingForTypeImpl(
5580 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5581 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005582 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5583 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005584 }
5585 S += '>';
5586 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005587 return;
5588 }
Mike Stump11289f42009-09-09 15:08:12 +00005589
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005590 case Type::ObjCObject: {
5591 // hack to match legacy encoding of *id and *Class
5592 QualType Ty = getObjCObjectPointerType(CT);
5593 if (Ty->isObjCIdType()) {
5594 S += "{objc_object=}";
5595 return;
5596 }
5597 else if (Ty->isObjCClassType()) {
5598 S += "{objc_class=}";
5599 return;
5600 }
5601 }
5602
John McCall393a78d2012-12-20 02:45:14 +00005603 case Type::ObjCInterface: {
5604 // Ignore protocol qualifiers when mangling at this level.
5605 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005606
John McCall393a78d2012-12-20 02:45:14 +00005607 // The assumption seems to be that this assert will succeed
5608 // because nested levels will have filtered out 'id' and 'Class'.
5609 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005610 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005611 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005612 S += '{';
5613 const IdentifierInfo *II = OI->getIdentifier();
5614 S += II->getName();
5615 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005616 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005617 DeepCollectObjCIvars(OI, true, Ivars);
5618 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005619 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005620 if (Field->isBitField())
5621 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005622 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005623 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5624 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005625 EncodePointerToObjCTypedef,
5626 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005627 }
5628 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005629 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005630 }
Mike Stump11289f42009-09-09 15:08:12 +00005631
John McCall393a78d2012-12-20 02:45:14 +00005632 case Type::ObjCObjectPointer: {
5633 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005634 if (OPT->isObjCIdType()) {
5635 S += '@';
5636 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005637 }
Mike Stump11289f42009-09-09 15:08:12 +00005638
Steve Narofff0c86112009-10-28 22:03:49 +00005639 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5640 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5641 // Since this is a binary compatibility issue, need to consult with runtime
5642 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005643 S += '#';
5644 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005645 }
Mike Stump11289f42009-09-09 15:08:12 +00005646
Chris Lattnere7cabb92009-07-13 00:10:46 +00005647 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005648 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005649 ExpandPointedToStructures,
5650 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005651 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005652 // Note that we do extended encoding of protocol qualifer list
5653 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005654 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005655 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005656 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005657 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005658 S += '>';
5659 }
5660 S += '"';
5661 }
5662 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005663 }
Mike Stump11289f42009-09-09 15:08:12 +00005664
Chris Lattnere7cabb92009-07-13 00:10:46 +00005665 QualType PointeeTy = OPT->getPointeeType();
5666 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005667 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5668 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005669 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005670 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005671 // {...};
5672 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005673 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005674 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005675 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5676 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5677 DeepCollectObjCIvars(OI, true, Ivars);
5678 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5679 if (cast<FieldDecl>(Ivars[i]) == FD) {
5680 S += '{';
5681 S += OI->getIdentifier()->getName();
5682 S += '}';
5683 return;
5684 }
5685 }
5686 }
Mike Stump11289f42009-09-09 15:08:12 +00005687 getObjCEncodingForTypeImpl(PointeeTy, S,
5688 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005689 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005690 false, false, false, false, false,
5691 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005692 return;
5693 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005694
5695 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005696 if (OPT->getInterfaceDecl() &&
5697 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005698 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005699 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005700 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005701 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005702 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005703 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005704 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005705 S += '"';
5706 }
5707 return;
5708 }
Mike Stump11289f42009-09-09 15:08:12 +00005709
John McCalla9e6e8d2010-05-17 23:56:34 +00005710 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005711 // FIXME: we shoul do better than that. 'M' is available.
5712 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005713 // This matches gcc's encoding, even though technically it is insufficient.
5714 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005715 case Type::Vector:
5716 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005717 // Until we have a coherent encoding of these three types, issue warning.
5718 { if (NotEncodedT)
5719 *NotEncodedT = T;
5720 return;
5721 }
5722
5723 // We could see an undeduced auto type here during error recovery.
5724 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005725 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005726 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005727
Richard Smith27d807c2013-04-30 13:56:41 +00005728
John McCall393a78d2012-12-20 02:45:14 +00005729#define ABSTRACT_TYPE(KIND, BASE)
5730#define TYPE(KIND, BASE)
5731#define DEPENDENT_TYPE(KIND, BASE) \
5732 case Type::KIND:
5733#define NON_CANONICAL_TYPE(KIND, BASE) \
5734 case Type::KIND:
5735#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5736 case Type::KIND:
5737#include "clang/AST/TypeNodes.def"
5738 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005739 }
John McCall393a78d2012-12-20 02:45:14 +00005740 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005741}
5742
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005743void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5744 std::string &S,
5745 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005746 bool includeVBases,
5747 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005748 assert(RDecl && "Expected non-null RecordDecl");
5749 assert(!RDecl->isUnion() && "Should not be called for unions");
5750 if (!RDecl->getDefinition())
5751 return;
5752
5753 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5754 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5755 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5756
5757 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005758 for (const auto &BI : CXXRec->bases()) {
5759 if (!BI.isVirtual()) {
5760 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005761 if (base->isEmpty())
5762 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005763 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005764 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5765 std::make_pair(offs, base));
5766 }
5767 }
5768 }
5769
5770 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005771 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005772 uint64_t offs = layout.getFieldOffset(i);
5773 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005774 std::make_pair(offs, Field));
5775 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005776 }
5777
5778 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005779 for (const auto &BI : CXXRec->vbases()) {
5780 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005781 if (base->isEmpty())
5782 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005783 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005784 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5785 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005786 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5787 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005788 }
5789 }
5790
5791 CharUnits size;
5792 if (CXXRec) {
5793 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5794 } else {
5795 size = layout.getSize();
5796 }
5797
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005798#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005799 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005800#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005801 std::multimap<uint64_t, NamedDecl *>::iterator
5802 CurLayObj = FieldOrBaseOffsets.begin();
5803
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005804 if (CXXRec && CXXRec->isDynamicClass() &&
5805 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005806 if (FD) {
5807 S += "\"_vptr$";
5808 std::string recname = CXXRec->getNameAsString();
5809 if (recname.empty()) recname = "?";
5810 S += recname;
5811 S += '"';
5812 }
5813 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005814#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005815 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005816#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005817 }
5818
5819 if (!RDecl->hasFlexibleArrayMember()) {
5820 // Mark the end of the structure.
5821 uint64_t offs = toBits(size);
5822 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005823 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005824 }
5825
5826 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005827#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005828 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005829 if (CurOffs < CurLayObj->first) {
5830 uint64_t padding = CurLayObj->first - CurOffs;
5831 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5832 // packing/alignment of members is different that normal, in which case
5833 // the encoding will be out-of-sync with the real layout.
5834 // If the runtime switches to just consider the size of types without
5835 // taking into account alignment, we could make padding explicit in the
5836 // encoding (e.g. using arrays of chars). The encoding strings would be
5837 // longer then though.
5838 CurOffs += padding;
5839 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005840#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005841
5842 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005843 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005844 break; // reached end of structure.
5845
5846 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5847 // We expand the bases without their virtual bases since those are going
5848 // in the initial structure. Note that this differs from gcc which
5849 // expands virtual bases each time one is encountered in the hierarchy,
5850 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005851 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5852 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005853 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005854#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005855 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005856#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005857 } else {
5858 FieldDecl *field = cast<FieldDecl>(dcl);
5859 if (FD) {
5860 S += '"';
5861 S += field->getNameAsString();
5862 S += '"';
5863 }
5864
5865 if (field->isBitField()) {
5866 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005867#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005868 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005869#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005870 } else {
5871 QualType qt = field->getType();
5872 getLegacyIntegralTypeEncoding(qt);
5873 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5874 /*OutermostType*/false,
5875 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005876 /*StructField*/true,
5877 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005878#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005879 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005880#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005881 }
5882 }
5883 }
5884}
5885
Mike Stump11289f42009-09-09 15:08:12 +00005886void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005887 std::string& S) const {
5888 if (QT & Decl::OBJC_TQ_In)
5889 S += 'n';
5890 if (QT & Decl::OBJC_TQ_Inout)
5891 S += 'N';
5892 if (QT & Decl::OBJC_TQ_Out)
5893 S += 'o';
5894 if (QT & Decl::OBJC_TQ_Bycopy)
5895 S += 'O';
5896 if (QT & Decl::OBJC_TQ_Byref)
5897 S += 'R';
5898 if (QT & Decl::OBJC_TQ_Oneway)
5899 S += 'V';
5900}
5901
Douglas Gregor3ea72692011-08-12 05:46:01 +00005902TypedefDecl *ASTContext::getObjCIdDecl() const {
5903 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005904 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005905 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005906 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005907 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005908 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005909}
5910
Douglas Gregor52e02802011-08-12 06:17:30 +00005911TypedefDecl *ASTContext::getObjCSelDecl() const {
5912 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005913 QualType T = getPointerType(ObjCBuiltinSelTy);
5914 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005915 }
5916 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005917}
5918
Douglas Gregor0a586182011-08-12 05:59:41 +00005919TypedefDecl *ASTContext::getObjCClassDecl() const {
5920 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005921 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005922 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005923 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005924 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005925 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005926}
5927
Douglas Gregord53ae832012-01-17 18:09:05 +00005928ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5929 if (!ObjCProtocolClassDecl) {
5930 ObjCProtocolClassDecl
5931 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5932 SourceLocation(),
5933 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005934 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005935 SourceLocation(), true);
5936 }
5937
5938 return ObjCProtocolClassDecl;
5939}
5940
Meador Inge5d3fb222012-06-16 03:34:49 +00005941//===----------------------------------------------------------------------===//
5942// __builtin_va_list Construction Functions
5943//===----------------------------------------------------------------------===//
5944
5945static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5946 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005947 QualType T = Context->getPointerType(Context->CharTy);
5948 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005949}
5950
5951static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5952 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005953 QualType T = Context->getPointerType(Context->VoidTy);
5954 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005955}
5956
Tim Northover9bb857a2013-01-31 12:13:10 +00005957static TypedefDecl *
5958CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005959 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005960 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005961 if (Context->getLangOpts().CPlusPlus) {
5962 // namespace std { struct __va_list {
5963 NamespaceDecl *NS;
5964 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5965 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005966 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005967 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005968 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005969 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005970 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005971 }
5972
5973 VaListTagDecl->startDefinition();
5974
5975 const size_t NumFields = 5;
5976 QualType FieldTypes[NumFields];
5977 const char *FieldNames[NumFields];
5978
5979 // void *__stack;
5980 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5981 FieldNames[0] = "__stack";
5982
5983 // void *__gr_top;
5984 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5985 FieldNames[1] = "__gr_top";
5986
5987 // void *__vr_top;
5988 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5989 FieldNames[2] = "__vr_top";
5990
5991 // int __gr_offs;
5992 FieldTypes[3] = Context->IntTy;
5993 FieldNames[3] = "__gr_offs";
5994
5995 // int __vr_offs;
5996 FieldTypes[4] = Context->IntTy;
5997 FieldNames[4] = "__vr_offs";
5998
5999 // Create fields
6000 for (unsigned i = 0; i < NumFields; ++i) {
6001 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6002 VaListTagDecl,
6003 SourceLocation(),
6004 SourceLocation(),
6005 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006006 FieldTypes[i], /*TInfo=*/nullptr,
6007 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006008 /*Mutable=*/false,
6009 ICIS_NoInit);
6010 Field->setAccess(AS_public);
6011 VaListTagDecl->addDecl(Field);
6012 }
6013 VaListTagDecl->completeDefinition();
6014 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6015 Context->VaListTagTy = VaListTagType;
6016
6017 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006018 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006019}
6020
Meador Inge5d3fb222012-06-16 03:34:49 +00006021static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6022 // typedef struct __va_list_tag {
6023 RecordDecl *VaListTagDecl;
6024
Alp Toker2dea15b2013-12-17 01:22:38 +00006025 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006026 VaListTagDecl->startDefinition();
6027
6028 const size_t NumFields = 5;
6029 QualType FieldTypes[NumFields];
6030 const char *FieldNames[NumFields];
6031
6032 // unsigned char gpr;
6033 FieldTypes[0] = Context->UnsignedCharTy;
6034 FieldNames[0] = "gpr";
6035
6036 // unsigned char fpr;
6037 FieldTypes[1] = Context->UnsignedCharTy;
6038 FieldNames[1] = "fpr";
6039
6040 // unsigned short reserved;
6041 FieldTypes[2] = Context->UnsignedShortTy;
6042 FieldNames[2] = "reserved";
6043
6044 // void* overflow_arg_area;
6045 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6046 FieldNames[3] = "overflow_arg_area";
6047
6048 // void* reg_save_area;
6049 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6050 FieldNames[4] = "reg_save_area";
6051
6052 // Create fields
6053 for (unsigned i = 0; i < NumFields; ++i) {
6054 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6055 SourceLocation(),
6056 SourceLocation(),
6057 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006058 FieldTypes[i], /*TInfo=*/nullptr,
6059 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006060 /*Mutable=*/false,
6061 ICIS_NoInit);
6062 Field->setAccess(AS_public);
6063 VaListTagDecl->addDecl(Field);
6064 }
6065 VaListTagDecl->completeDefinition();
6066 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006067 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006068
6069 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006070 TypedefDecl *VaListTagTypedefDecl =
6071 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6072
Meador Inge5d3fb222012-06-16 03:34:49 +00006073 QualType VaListTagTypedefType =
6074 Context->getTypedefType(VaListTagTypedefDecl);
6075
6076 // typedef __va_list_tag __builtin_va_list[1];
6077 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6078 QualType VaListTagArrayType
6079 = Context->getConstantArrayType(VaListTagTypedefType,
6080 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006081 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006082}
6083
6084static TypedefDecl *
6085CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6086 // typedef struct __va_list_tag {
6087 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006088 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006089 VaListTagDecl->startDefinition();
6090
6091 const size_t NumFields = 4;
6092 QualType FieldTypes[NumFields];
6093 const char *FieldNames[NumFields];
6094
6095 // unsigned gp_offset;
6096 FieldTypes[0] = Context->UnsignedIntTy;
6097 FieldNames[0] = "gp_offset";
6098
6099 // unsigned fp_offset;
6100 FieldTypes[1] = Context->UnsignedIntTy;
6101 FieldNames[1] = "fp_offset";
6102
6103 // void* overflow_arg_area;
6104 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6105 FieldNames[2] = "overflow_arg_area";
6106
6107 // void* reg_save_area;
6108 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6109 FieldNames[3] = "reg_save_area";
6110
6111 // Create fields
6112 for (unsigned i = 0; i < NumFields; ++i) {
6113 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6114 VaListTagDecl,
6115 SourceLocation(),
6116 SourceLocation(),
6117 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006118 FieldTypes[i], /*TInfo=*/nullptr,
6119 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006120 /*Mutable=*/false,
6121 ICIS_NoInit);
6122 Field->setAccess(AS_public);
6123 VaListTagDecl->addDecl(Field);
6124 }
6125 VaListTagDecl->completeDefinition();
6126 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006127 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006128
6129 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006130 TypedefDecl *VaListTagTypedefDecl =
6131 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6132
Meador Inge5d3fb222012-06-16 03:34:49 +00006133 QualType VaListTagTypedefType =
6134 Context->getTypedefType(VaListTagTypedefDecl);
6135
6136 // typedef __va_list_tag __builtin_va_list[1];
6137 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6138 QualType VaListTagArrayType
6139 = Context->getConstantArrayType(VaListTagTypedefType,
6140 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006141 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006142}
6143
6144static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6145 // typedef int __builtin_va_list[4];
6146 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6147 QualType IntArrayType
6148 = Context->getConstantArrayType(Context->IntTy,
6149 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006150 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006151}
6152
Logan Chien57086ce2012-10-10 06:56:20 +00006153static TypedefDecl *
6154CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006155 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006156 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006157 if (Context->getLangOpts().CPlusPlus) {
6158 // namespace std { struct __va_list {
6159 NamespaceDecl *NS;
6160 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6161 Context->getTranslationUnitDecl(),
6162 /*Inline*/false, SourceLocation(),
6163 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006164 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006165 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006166 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006167 }
6168
6169 VaListDecl->startDefinition();
6170
6171 // void * __ap;
6172 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6173 VaListDecl,
6174 SourceLocation(),
6175 SourceLocation(),
6176 &Context->Idents.get("__ap"),
6177 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006178 /*TInfo=*/nullptr,
6179 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006180 /*Mutable=*/false,
6181 ICIS_NoInit);
6182 Field->setAccess(AS_public);
6183 VaListDecl->addDecl(Field);
6184
6185 // };
6186 VaListDecl->completeDefinition();
6187
6188 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006189 QualType T = Context->getRecordType(VaListDecl);
6190 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006191}
6192
Ulrich Weigand47445072013-05-06 16:26:41 +00006193static TypedefDecl *
6194CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6195 // typedef struct __va_list_tag {
6196 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006197 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006198 VaListTagDecl->startDefinition();
6199
6200 const size_t NumFields = 4;
6201 QualType FieldTypes[NumFields];
6202 const char *FieldNames[NumFields];
6203
6204 // long __gpr;
6205 FieldTypes[0] = Context->LongTy;
6206 FieldNames[0] = "__gpr";
6207
6208 // long __fpr;
6209 FieldTypes[1] = Context->LongTy;
6210 FieldNames[1] = "__fpr";
6211
6212 // void *__overflow_arg_area;
6213 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6214 FieldNames[2] = "__overflow_arg_area";
6215
6216 // void *__reg_save_area;
6217 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6218 FieldNames[3] = "__reg_save_area";
6219
6220 // Create fields
6221 for (unsigned i = 0; i < NumFields; ++i) {
6222 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6223 VaListTagDecl,
6224 SourceLocation(),
6225 SourceLocation(),
6226 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006227 FieldTypes[i], /*TInfo=*/nullptr,
6228 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006229 /*Mutable=*/false,
6230 ICIS_NoInit);
6231 Field->setAccess(AS_public);
6232 VaListTagDecl->addDecl(Field);
6233 }
6234 VaListTagDecl->completeDefinition();
6235 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6236 Context->VaListTagTy = VaListTagType;
6237
6238 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006239 TypedefDecl *VaListTagTypedefDecl =
6240 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006241 QualType VaListTagTypedefType =
6242 Context->getTypedefType(VaListTagTypedefDecl);
6243
6244 // typedef __va_list_tag __builtin_va_list[1];
6245 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6246 QualType VaListTagArrayType
6247 = Context->getConstantArrayType(VaListTagTypedefType,
6248 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006249
Alp Toker56b5cc92013-12-15 10:36:26 +00006250 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006251}
6252
Meador Inge5d3fb222012-06-16 03:34:49 +00006253static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6254 TargetInfo::BuiltinVaListKind Kind) {
6255 switch (Kind) {
6256 case TargetInfo::CharPtrBuiltinVaList:
6257 return CreateCharPtrBuiltinVaListDecl(Context);
6258 case TargetInfo::VoidPtrBuiltinVaList:
6259 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006260 case TargetInfo::AArch64ABIBuiltinVaList:
6261 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006262 case TargetInfo::PowerABIBuiltinVaList:
6263 return CreatePowerABIBuiltinVaListDecl(Context);
6264 case TargetInfo::X86_64ABIBuiltinVaList:
6265 return CreateX86_64ABIBuiltinVaListDecl(Context);
6266 case TargetInfo::PNaClABIBuiltinVaList:
6267 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006268 case TargetInfo::AAPCSABIBuiltinVaList:
6269 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006270 case TargetInfo::SystemZBuiltinVaList:
6271 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006272 }
6273
6274 llvm_unreachable("Unhandled __builtin_va_list type kind");
6275}
6276
6277TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006278 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006279 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006280 assert(BuiltinVaListDecl->isImplicit());
6281 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006282
6283 return BuiltinVaListDecl;
6284}
6285
Meador Ingecfb60902012-07-01 15:57:25 +00006286QualType ASTContext::getVaListTagType() const {
6287 // Force the creation of VaListTagTy by building the __builtin_va_list
6288 // declaration.
6289 if (VaListTagTy.isNull())
6290 (void) getBuiltinVaListDecl();
6291
6292 return VaListTagTy;
6293}
6294
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006295void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006296 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006297 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006298
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006299 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006300}
6301
John McCalld28ae272009-12-02 08:04:21 +00006302/// \brief Retrieve the template name that corresponds to a non-empty
6303/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006304TemplateName
6305ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6306 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006307 unsigned size = End - Begin;
6308 assert(size > 1 && "set is not overloaded!");
6309
6310 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6311 size * sizeof(FunctionTemplateDecl*));
6312 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6313
6314 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006315 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006316 NamedDecl *D = *I;
6317 assert(isa<FunctionTemplateDecl>(D) ||
6318 (isa<UsingShadowDecl>(D) &&
6319 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6320 *Storage++ = D;
6321 }
6322
6323 return TemplateName(OT);
6324}
6325
Douglas Gregordc572a32009-03-30 22:58:21 +00006326/// \brief Retrieve the template name that represents a qualified
6327/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006328TemplateName
6329ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6330 bool TemplateKeyword,
6331 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006332 assert(NNS && "Missing nested-name-specifier in qualified template name");
6333
Douglas Gregorc42075a2010-02-04 18:10:26 +00006334 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006335 llvm::FoldingSetNodeID ID;
6336 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6337
Craig Topper36250ad2014-05-12 05:36:57 +00006338 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006339 QualifiedTemplateName *QTN =
6340 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6341 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006342 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6343 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006344 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6345 }
6346
6347 return TemplateName(QTN);
6348}
6349
6350/// \brief Retrieve the template name that represents a dependent
6351/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006352TemplateName
6353ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6354 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006355 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006356 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006357
6358 llvm::FoldingSetNodeID ID;
6359 DependentTemplateName::Profile(ID, NNS, Name);
6360
Craig Topper36250ad2014-05-12 05:36:57 +00006361 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006362 DependentTemplateName *QTN =
6363 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6364
6365 if (QTN)
6366 return TemplateName(QTN);
6367
6368 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6369 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006370 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6371 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006372 } else {
6373 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006374 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6375 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006376 DependentTemplateName *CheckQTN =
6377 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6378 assert(!CheckQTN && "Dependent type name canonicalization broken");
6379 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006380 }
6381
6382 DependentTemplateNames.InsertNode(QTN, InsertPos);
6383 return TemplateName(QTN);
6384}
6385
Douglas Gregor71395fa2009-11-04 00:56:37 +00006386/// \brief Retrieve the template name that represents a dependent
6387/// template name such as \c MetaFun::template operator+.
6388TemplateName
6389ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006390 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006391 assert((!NNS || NNS->isDependent()) &&
6392 "Nested name specifier must be dependent");
6393
6394 llvm::FoldingSetNodeID ID;
6395 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006396
6397 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006398 DependentTemplateName *QTN
6399 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006400
6401 if (QTN)
6402 return TemplateName(QTN);
6403
6404 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6405 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006406 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6407 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006408 } else {
6409 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006410 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6411 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006412
6413 DependentTemplateName *CheckQTN
6414 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6415 assert(!CheckQTN && "Dependent template name canonicalization broken");
6416 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006417 }
6418
6419 DependentTemplateNames.InsertNode(QTN, InsertPos);
6420 return TemplateName(QTN);
6421}
6422
Douglas Gregor5590be02011-01-15 06:45:20 +00006423TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006424ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6425 TemplateName replacement) const {
6426 llvm::FoldingSetNodeID ID;
6427 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006428
6429 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006430 SubstTemplateTemplateParmStorage *subst
6431 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6432
6433 if (!subst) {
6434 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6435 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6436 }
6437
6438 return TemplateName(subst);
6439}
6440
6441TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006442ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6443 const TemplateArgument &ArgPack) const {
6444 ASTContext &Self = const_cast<ASTContext &>(*this);
6445 llvm::FoldingSetNodeID ID;
6446 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006447
6448 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006449 SubstTemplateTemplateParmPackStorage *Subst
6450 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6451
6452 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006453 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006454 ArgPack.pack_size(),
6455 ArgPack.pack_begin());
6456 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6457 }
6458
6459 return TemplateName(Subst);
6460}
6461
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006462/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006463/// TargetInfo, produce the corresponding type. The unsigned @p Type
6464/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006465CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006466 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006467 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006468 case TargetInfo::SignedChar: return SignedCharTy;
6469 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006470 case TargetInfo::SignedShort: return ShortTy;
6471 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6472 case TargetInfo::SignedInt: return IntTy;
6473 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6474 case TargetInfo::SignedLong: return LongTy;
6475 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6476 case TargetInfo::SignedLongLong: return LongLongTy;
6477 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6478 }
6479
David Blaikie83d382b2011-09-23 05:06:16 +00006480 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006481}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006482
6483//===----------------------------------------------------------------------===//
6484// Type Predicates.
6485//===----------------------------------------------------------------------===//
6486
Fariborz Jahanian96207692009-02-18 21:49:28 +00006487/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6488/// garbage collection attribute.
6489///
John McCall553d45a2011-01-12 00:34:59 +00006490Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006491 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006492 return Qualifiers::GCNone;
6493
David Blaikiebbafb8a2012-03-11 07:00:24 +00006494 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006495 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6496
6497 // Default behaviour under objective-C's gc is for ObjC pointers
6498 // (or pointers to them) be treated as though they were declared
6499 // as __strong.
6500 if (GCAttrs == Qualifiers::GCNone) {
6501 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6502 return Qualifiers::Strong;
6503 else if (Ty->isPointerType())
6504 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6505 } else {
6506 // It's not valid to set GC attributes on anything that isn't a
6507 // pointer.
6508#ifndef NDEBUG
6509 QualType CT = Ty->getCanonicalTypeInternal();
6510 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6511 CT = AT->getElementType();
6512 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6513#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006514 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006515 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006516}
6517
Chris Lattner49af6a42008-04-07 06:51:04 +00006518//===----------------------------------------------------------------------===//
6519// Type Compatibility Testing
6520//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006521
Mike Stump11289f42009-09-09 15:08:12 +00006522/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006523/// compatible.
6524static bool areCompatVectorTypes(const VectorType *LHS,
6525 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006526 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006527 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006528 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006529}
6530
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006531bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6532 QualType SecondVec) {
6533 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6534 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6535
6536 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6537 return true;
6538
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006539 // Treat Neon vector types and most AltiVec vector types as if they are the
6540 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006541 const VectorType *First = FirstVec->getAs<VectorType>();
6542 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006543 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006544 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006545 First->getVectorKind() != VectorType::AltiVecPixel &&
6546 First->getVectorKind() != VectorType::AltiVecBool &&
6547 Second->getVectorKind() != VectorType::AltiVecPixel &&
6548 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006549 return true;
6550
6551 return false;
6552}
6553
Steve Naroff8e6aee52009-07-23 01:01:38 +00006554//===----------------------------------------------------------------------===//
6555// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6556//===----------------------------------------------------------------------===//
6557
6558/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6559/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006560bool
6561ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6562 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006563 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006564 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006565 for (auto *PI : rProto->protocols())
6566 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006567 return true;
6568 return false;
6569}
6570
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006571/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6572/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006573bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6574 QualType rhs) {
6575 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6576 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6577 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6578
Aaron Ballman83731462014-03-17 16:14:00 +00006579 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006580 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006581 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006582 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6583 match = true;
6584 break;
6585 }
6586 }
6587 if (!match)
6588 return false;
6589 }
6590 return true;
6591}
6592
Steve Naroff8e6aee52009-07-23 01:01:38 +00006593/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6594/// ObjCQualifiedIDType.
6595bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6596 bool compare) {
6597 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006598 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006599 lhs->isObjCIdType() || lhs->isObjCClassType())
6600 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006601 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006602 rhs->isObjCIdType() || rhs->isObjCClassType())
6603 return true;
6604
6605 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006606 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006607
Steve Naroff8e6aee52009-07-23 01:01:38 +00006608 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006609
Steve Naroff8e6aee52009-07-23 01:01:38 +00006610 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006611 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006612 // make sure we check the class hierarchy.
6613 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006614 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006615 // when comparing an id<P> on lhs with a static type on rhs,
6616 // see if static class implements all of id's protocols, directly or
6617 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006618 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006619 return false;
6620 }
6621 }
6622 // If there are no qualifiers and no interface, we have an 'id'.
6623 return true;
6624 }
Mike Stump11289f42009-09-09 15:08:12 +00006625 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006626 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006627 bool match = false;
6628
6629 // when comparing an id<P> on lhs with a static type on rhs,
6630 // see if static class implements all of id's protocols, directly or
6631 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006632 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006633 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6634 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6635 match = true;
6636 break;
6637 }
6638 }
Mike Stump11289f42009-09-09 15:08:12 +00006639 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006640 // make sure we check the class hierarchy.
6641 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006642 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006643 // when comparing an id<P> on lhs with a static type on rhs,
6644 // see if static class implements all of id's protocols, directly or
6645 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006646 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006647 match = true;
6648 break;
6649 }
6650 }
6651 }
6652 if (!match)
6653 return false;
6654 }
Mike Stump11289f42009-09-09 15:08:12 +00006655
Steve Naroff8e6aee52009-07-23 01:01:38 +00006656 return true;
6657 }
Mike Stump11289f42009-09-09 15:08:12 +00006658
Steve Naroff8e6aee52009-07-23 01:01:38 +00006659 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6660 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6661
Mike Stump11289f42009-09-09 15:08:12 +00006662 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006663 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006664 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006665 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006666 bool match = false;
6667
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006668 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006669 // see if static class implements all of id's protocols, directly or
6670 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006671 // First, lhs protocols in the qualifier list must be found, direct
6672 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006673 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006674 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6675 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6676 match = true;
6677 break;
6678 }
6679 }
6680 if (!match)
6681 return false;
6682 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006683
6684 // Static class's protocols, or its super class or category protocols
6685 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6686 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6687 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6688 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6689 // This is rather dubious but matches gcc's behavior. If lhs has
6690 // no type qualifier and its class has no static protocol(s)
6691 // assume that it is mismatch.
6692 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6693 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006694 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006695 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006696 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006697 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6698 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6699 match = true;
6700 break;
6701 }
6702 }
6703 if (!match)
6704 return false;
6705 }
6706 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006707 return true;
6708 }
6709 return false;
6710}
6711
Eli Friedman47f77112008-08-22 00:56:42 +00006712/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006713/// compatible for assignment from RHS to LHS. This handles validation of any
6714/// protocol qualifiers on the LHS or RHS.
6715///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006716bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6717 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006718 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6719 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6720
Steve Naroff1329fa02009-07-15 18:40:39 +00006721 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006722 if (LHS->isObjCUnqualifiedIdOrClass() ||
6723 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006724 return true;
6725
John McCall8b07ec22010-05-15 11:32:37 +00006726 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006727 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6728 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006729 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006730
6731 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6732 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6733 QualType(RHSOPT,0));
6734
John McCall8b07ec22010-05-15 11:32:37 +00006735 // If we have 2 user-defined types, fall into that path.
6736 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006737 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006738
Steve Naroff8e6aee52009-07-23 01:01:38 +00006739 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006740}
6741
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006742/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006743/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006744/// arguments in block literals. When passed as arguments, passing 'A*' where
6745/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6746/// not OK. For the return type, the opposite is not OK.
6747bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6748 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006749 const ObjCObjectPointerType *RHSOPT,
6750 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006751 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006752 return true;
6753
6754 if (LHSOPT->isObjCBuiltinType()) {
6755 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6756 }
6757
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006758 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006759 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6760 QualType(RHSOPT,0),
6761 false);
6762
6763 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6764 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6765 if (LHS && RHS) { // We have 2 user-defined types.
6766 if (LHS != RHS) {
6767 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006768 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006769 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006770 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006771 }
6772 else
6773 return true;
6774 }
6775 return false;
6776}
6777
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006778/// getIntersectionOfProtocols - This routine finds the intersection of set
6779/// of protocols inherited from two distinct objective-c pointer objects.
6780/// It is used to build composite qualifier list of the composite type of
6781/// the conditional expression involving two objective-c pointer objects.
6782static
6783void getIntersectionOfProtocols(ASTContext &Context,
6784 const ObjCObjectPointerType *LHSOPT,
6785 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006786 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006787
John McCall8b07ec22010-05-15 11:32:37 +00006788 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6789 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6790 assert(LHS->getInterface() && "LHS must have an interface base");
6791 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006792
6793 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6794 unsigned LHSNumProtocols = LHS->getNumProtocols();
6795 if (LHSNumProtocols > 0)
6796 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6797 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006798 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006799 Context.CollectInheritedProtocols(LHS->getInterface(),
6800 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006801 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6802 LHSInheritedProtocols.end());
6803 }
6804
6805 unsigned RHSNumProtocols = RHS->getNumProtocols();
6806 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006807 ObjCProtocolDecl **RHSProtocols =
6808 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006809 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6810 if (InheritedProtocolSet.count(RHSProtocols[i]))
6811 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006812 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006813 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006814 Context.CollectInheritedProtocols(RHS->getInterface(),
6815 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006816 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6817 if (InheritedProtocolSet.count(ProtDecl))
6818 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006819 }
6820}
6821
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006822/// areCommonBaseCompatible - Returns common base class of the two classes if
6823/// one found. Note that this is O'2 algorithm. But it will be called as the
6824/// last type comparison in a ?-exp of ObjC pointer types before a
6825/// warning is issued. So, its invokation is extremely rare.
6826QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006827 const ObjCObjectPointerType *Lptr,
6828 const ObjCObjectPointerType *Rptr) {
6829 const ObjCObjectType *LHS = Lptr->getObjectType();
6830 const ObjCObjectType *RHS = Rptr->getObjectType();
6831 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6832 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006833 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006834 return QualType();
6835
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006836 do {
John McCall8b07ec22010-05-15 11:32:37 +00006837 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006838 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006839 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006840 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6841
6842 QualType Result = QualType(LHS, 0);
6843 if (!Protocols.empty())
6844 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6845 Result = getObjCObjectPointerType(Result);
6846 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006847 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006848 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006849
6850 return QualType();
6851}
6852
John McCall8b07ec22010-05-15 11:32:37 +00006853bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6854 const ObjCObjectType *RHS) {
6855 assert(LHS->getInterface() && "LHS is not an interface type");
6856 assert(RHS->getInterface() && "RHS is not an interface type");
6857
Chris Lattner49af6a42008-04-07 06:51:04 +00006858 // Verify that the base decls are compatible: the RHS must be a subclass of
6859 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006860 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006861 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006862
Chris Lattner49af6a42008-04-07 06:51:04 +00006863 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6864 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006865 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006866 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006867
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006868 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6869 // More detailed analysis is required.
6870 // OK, if LHS is same or a superclass of RHS *and*
6871 // this LHS, or as RHS's super class is assignment compatible with LHS.
6872 bool IsSuperClass =
6873 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6874 if (IsSuperClass) {
6875 // OK if conversion of LHS to SuperClass results in narrowing of types
6876 // ; i.e., SuperClass may implement at least one of the protocols
6877 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6878 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6879 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6880 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6881 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6882 // qualifiers.
6883 for (auto *RHSPI : RHS->quals())
6884 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6885 // If there is no protocols associated with RHS, it is not a match.
6886 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006887 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006888
6889 for (const auto *LHSProto : LHS->quals()) {
6890 bool SuperImplementsProtocol = false;
6891 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6892 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6893 SuperImplementsProtocol = true;
6894 break;
6895 }
6896 if (!SuperImplementsProtocol)
6897 return false;
6898 }
6899 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006900 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006901 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006902}
6903
Steve Naroffb7605152009-02-12 17:52:19 +00006904bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6905 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006906 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6907 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006908
Steve Naroff7cae42b2009-07-10 23:34:53 +00006909 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006910 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006911
6912 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6913 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006914}
6915
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006916bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6917 return canAssignObjCInterfaces(
6918 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6919 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6920}
6921
Mike Stump11289f42009-09-09 15:08:12 +00006922/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006923/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006924/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006925/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006926bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6927 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006928 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006929 return hasSameType(LHS, RHS);
6930
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006931 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006932}
6933
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006934bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006935 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006936}
6937
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006938bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6939 return !mergeTypes(LHS, RHS, true).isNull();
6940}
6941
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006942/// mergeTransparentUnionType - if T is a transparent union type and a member
6943/// of T is compatible with SubType, return the merged type, else return
6944/// QualType()
6945QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6946 bool OfBlockPointer,
6947 bool Unqualified) {
6948 if (const RecordType *UT = T->getAsUnionType()) {
6949 RecordDecl *UD = UT->getDecl();
6950 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006951 for (const auto *I : UD->fields()) {
6952 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006953 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6954 if (!MT.isNull())
6955 return MT;
6956 }
6957 }
6958 }
6959
6960 return QualType();
6961}
6962
Alp Toker9cacbab2014-01-20 20:26:09 +00006963/// mergeFunctionParameterTypes - merge two types which appear as function
6964/// parameter types
6965QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6966 bool OfBlockPointer,
6967 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006968 // GNU extension: two types are compatible if they appear as a function
6969 // argument, one of the types is a transparent union type and the other
6970 // type is compatible with a union member
6971 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6972 Unqualified);
6973 if (!lmerge.isNull())
6974 return lmerge;
6975
6976 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6977 Unqualified);
6978 if (!rmerge.isNull())
6979 return rmerge;
6980
6981 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6982}
6983
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006984QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006985 bool OfBlockPointer,
6986 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006987 const FunctionType *lbase = lhs->getAs<FunctionType>();
6988 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006989 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6990 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006991 bool allLTypes = true;
6992 bool allRTypes = true;
6993
6994 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006995 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006996 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006997 QualType RHS = rbase->getReturnType();
6998 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006999 bool UnqualifiedResult = Unqualified;
7000 if (!UnqualifiedResult)
7001 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007002 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007003 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007004 else
Alp Toker314cc812014-01-25 16:55:45 +00007005 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007006 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007007 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007008
7009 if (Unqualified)
7010 retType = retType.getUnqualifiedType();
7011
Alp Toker314cc812014-01-25 16:55:45 +00007012 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7013 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007014 if (Unqualified) {
7015 LRetType = LRetType.getUnqualifiedType();
7016 RRetType = RRetType.getUnqualifiedType();
7017 }
7018
7019 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007020 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007021 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007022 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007023
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007024 // FIXME: double check this
7025 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7026 // rbase->getRegParmAttr() != 0 &&
7027 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007028 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7029 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007030
Douglas Gregor8c940862010-01-18 17:14:39 +00007031 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007032 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007033 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007034
John McCall8c6b56f2010-12-15 01:06:38 +00007035 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007036 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7037 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007038 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7039 return QualType();
7040
John McCall31168b02011-06-15 23:02:42 +00007041 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7042 return QualType();
7043
John McCall8c6b56f2010-12-15 01:06:38 +00007044 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7045 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007046
Rafael Espindola8778c282012-11-29 16:09:03 +00007047 if (lbaseInfo.getNoReturn() != NoReturn)
7048 allLTypes = false;
7049 if (rbaseInfo.getNoReturn() != NoReturn)
7050 allRTypes = false;
7051
John McCall31168b02011-06-15 23:02:42 +00007052 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007053
Eli Friedman47f77112008-08-22 00:56:42 +00007054 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007055 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7056 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007057 // Compatible functions must have the same number of parameters
7058 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007059 return QualType();
7060
7061 // Variadic and non-variadic functions aren't compatible
7062 if (lproto->isVariadic() != rproto->isVariadic())
7063 return QualType();
7064
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007065 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7066 return QualType();
7067
Fariborz Jahanian97676972011-09-28 21:52:05 +00007068 if (LangOpts.ObjCAutoRefCount &&
7069 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7070 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007071
7072 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007073 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007074 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7075 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7076 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7077 QualType paramType = mergeFunctionParameterTypes(
7078 lParamType, rParamType, OfBlockPointer, Unqualified);
7079 if (paramType.isNull())
7080 return QualType();
7081
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007082 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007083 paramType = paramType.getUnqualifiedType();
7084
7085 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007086 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007087 lParamType = lParamType.getUnqualifiedType();
7088 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007089 }
Alp Toker601b22c2014-01-21 23:35:24 +00007090
7091 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007092 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007093 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007094 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007095 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007096
Eli Friedman47f77112008-08-22 00:56:42 +00007097 if (allLTypes) return lhs;
7098 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007099
7100 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7101 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007102 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007103 }
7104
7105 if (lproto) allRTypes = false;
7106 if (rproto) allLTypes = false;
7107
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007108 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007109 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007110 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007111 if (proto->isVariadic()) return QualType();
7112 // Check that the types are compatible with the types that
7113 // would result from default argument promotions (C99 6.7.5.3p15).
7114 // The only types actually affected are promotable integer
7115 // types and floats, which would be passed as a different
7116 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007117 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7118 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007119
Eli Friedman448ce402012-08-30 00:44:15 +00007120 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007121 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007122 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7123 paramTy = Enum->getDecl()->getIntegerType();
7124 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007125 return QualType();
7126 }
Alp Toker601b22c2014-01-21 23:35:24 +00007127
7128 if (paramTy->isPromotableIntegerType() ||
7129 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007130 return QualType();
7131 }
7132
7133 if (allLTypes) return lhs;
7134 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007135
7136 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7137 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007138 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007139 }
7140
7141 if (allLTypes) return lhs;
7142 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007143 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007144}
7145
John McCall433c2e62013-03-21 00:10:07 +00007146/// Given that we have an enum type and a non-enum type, try to merge them.
7147static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7148 QualType other, bool isBlockReturnType) {
7149 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7150 // a signed integer type, or an unsigned integer type.
7151 // Compatibility is based on the underlying type, not the promotion
7152 // type.
7153 QualType underlyingType = ET->getDecl()->getIntegerType();
7154 if (underlyingType.isNull()) return QualType();
7155 if (Context.hasSameType(underlyingType, other))
7156 return other;
7157
7158 // In block return types, we're more permissive and accept any
7159 // integral type of the same size.
7160 if (isBlockReturnType && other->isIntegerType() &&
7161 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7162 return other;
7163
7164 return QualType();
7165}
7166
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007167QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007168 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007169 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007170 // C++ [expr]: If an expression initially has the type "reference to T", the
7171 // type is adjusted to "T" prior to any further analysis, the expression
7172 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007173 // expression is an lvalue unless the reference is an rvalue reference and
7174 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007175 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7176 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007177
7178 if (Unqualified) {
7179 LHS = LHS.getUnqualifiedType();
7180 RHS = RHS.getUnqualifiedType();
7181 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007182
Eli Friedman47f77112008-08-22 00:56:42 +00007183 QualType LHSCan = getCanonicalType(LHS),
7184 RHSCan = getCanonicalType(RHS);
7185
7186 // If two types are identical, they are compatible.
7187 if (LHSCan == RHSCan)
7188 return LHS;
7189
John McCall8ccfcb52009-09-24 19:53:00 +00007190 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007191 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7192 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007193 if (LQuals != RQuals) {
7194 // If any of these qualifiers are different, we have a type
7195 // mismatch.
7196 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007197 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7198 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007199 return QualType();
7200
7201 // Exactly one GC qualifier difference is allowed: __strong is
7202 // okay if the other type has no GC qualifier but is an Objective
7203 // C object pointer (i.e. implicitly strong by default). We fix
7204 // this by pretending that the unqualified type was actually
7205 // qualified __strong.
7206 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7207 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7208 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7209
7210 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7211 return QualType();
7212
7213 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7214 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7215 }
7216 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7217 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7218 }
Eli Friedman47f77112008-08-22 00:56:42 +00007219 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007220 }
7221
7222 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007223
Eli Friedmandcca6332009-06-01 01:22:52 +00007224 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7225 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007226
Chris Lattnerfd652912008-01-14 05:45:46 +00007227 // We want to consider the two function types to be the same for these
7228 // comparisons, just force one to the other.
7229 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7230 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007231
7232 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007233 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7234 LHSClass = Type::ConstantArray;
7235 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7236 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007237
John McCall8b07ec22010-05-15 11:32:37 +00007238 // ObjCInterfaces are just specialized ObjCObjects.
7239 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7240 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7241
Nate Begemance4d7fc2008-04-18 23:10:10 +00007242 // Canonicalize ExtVector -> Vector.
7243 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7244 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007245
Chris Lattner95554662008-04-07 05:43:21 +00007246 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007247 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007248 // Note that we only have special rules for turning block enum
7249 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007250 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007251 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007252 }
John McCall9dd450b2009-09-21 23:43:11 +00007253 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007254 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007255 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007256 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007257 if (OfBlockPointer && !BlockReturnType) {
7258 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7259 return LHS;
7260 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7261 return RHS;
7262 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007263
Eli Friedman47f77112008-08-22 00:56:42 +00007264 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007265 }
Eli Friedman47f77112008-08-22 00:56:42 +00007266
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007267 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007268 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007269#define TYPE(Class, Base)
7270#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007271#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007272#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7273#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7274#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007275 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007276
Richard Smith27d807c2013-04-30 13:56:41 +00007277 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007278 case Type::LValueReference:
7279 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007280 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007281 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007282
John McCall8b07ec22010-05-15 11:32:37 +00007283 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007284 case Type::IncompleteArray:
7285 case Type::VariableArray:
7286 case Type::FunctionProto:
7287 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007288 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007289
Chris Lattnerfd652912008-01-14 05:45:46 +00007290 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007291 {
7292 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007293 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7294 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007295 if (Unqualified) {
7296 LHSPointee = LHSPointee.getUnqualifiedType();
7297 RHSPointee = RHSPointee.getUnqualifiedType();
7298 }
7299 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7300 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007301 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007302 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007303 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007304 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007305 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007306 return getPointerType(ResultType);
7307 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007308 case Type::BlockPointer:
7309 {
7310 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007311 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7312 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007313 if (Unqualified) {
7314 LHSPointee = LHSPointee.getUnqualifiedType();
7315 RHSPointee = RHSPointee.getUnqualifiedType();
7316 }
7317 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7318 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007319 if (ResultType.isNull()) return QualType();
7320 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7321 return LHS;
7322 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7323 return RHS;
7324 return getBlockPointerType(ResultType);
7325 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007326 case Type::Atomic:
7327 {
7328 // Merge two pointer types, while trying to preserve typedef info
7329 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7330 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7331 if (Unqualified) {
7332 LHSValue = LHSValue.getUnqualifiedType();
7333 RHSValue = RHSValue.getUnqualifiedType();
7334 }
7335 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7336 Unqualified);
7337 if (ResultType.isNull()) return QualType();
7338 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7339 return LHS;
7340 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7341 return RHS;
7342 return getAtomicType(ResultType);
7343 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007344 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007345 {
7346 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7347 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7348 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7349 return QualType();
7350
7351 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7352 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007353 if (Unqualified) {
7354 LHSElem = LHSElem.getUnqualifiedType();
7355 RHSElem = RHSElem.getUnqualifiedType();
7356 }
7357
7358 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007359 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007360 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7361 return LHS;
7362 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7363 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007364 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7365 ArrayType::ArraySizeModifier(), 0);
7366 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7367 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007368 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7369 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007370 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7371 return LHS;
7372 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7373 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007374 if (LVAT) {
7375 // FIXME: This isn't correct! But tricky to implement because
7376 // the array's size has to be the size of LHS, but the type
7377 // has to be different.
7378 return LHS;
7379 }
7380 if (RVAT) {
7381 // FIXME: This isn't correct! But tricky to implement because
7382 // the array's size has to be the size of RHS, but the type
7383 // has to be different.
7384 return RHS;
7385 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007386 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7387 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007388 return getIncompleteArrayType(ResultType,
7389 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007390 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007391 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007392 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007393 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007394 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007395 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007396 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007397 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007398 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007399 case Type::Complex:
7400 // Distinct complex types are incompatible.
7401 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007402 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007403 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007404 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7405 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007406 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007407 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007408 case Type::ObjCObject: {
7409 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007410 // FIXME: This should be type compatibility, e.g. whether
7411 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007412 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7413 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7414 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007415 return LHS;
7416
Eli Friedman47f77112008-08-22 00:56:42 +00007417 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007418 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007419 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007420 if (OfBlockPointer) {
7421 if (canAssignObjCInterfacesInBlockPointer(
7422 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007423 RHS->getAs<ObjCObjectPointerType>(),
7424 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007425 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007426 return QualType();
7427 }
John McCall9dd450b2009-09-21 23:43:11 +00007428 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7429 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007430 return LHS;
7431
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007432 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007433 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007434 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007435
David Blaikie8a40f702012-01-17 06:56:22 +00007436 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007437}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007438
Fariborz Jahanian97676972011-09-28 21:52:05 +00007439bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7440 const FunctionProtoType *FromFunctionType,
7441 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007442 if (FromFunctionType->hasAnyConsumedParams() !=
7443 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007444 return false;
7445 FunctionProtoType::ExtProtoInfo FromEPI =
7446 FromFunctionType->getExtProtoInfo();
7447 FunctionProtoType::ExtProtoInfo ToEPI =
7448 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007449 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007450 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7451 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007452 return false;
7453 }
7454 return true;
7455}
7456
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007457/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7458/// 'RHS' attributes and returns the merged version; including for function
7459/// return types.
7460QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7461 QualType LHSCan = getCanonicalType(LHS),
7462 RHSCan = getCanonicalType(RHS);
7463 // If two types are identical, they are compatible.
7464 if (LHSCan == RHSCan)
7465 return LHS;
7466 if (RHSCan->isFunctionType()) {
7467 if (!LHSCan->isFunctionType())
7468 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007469 QualType OldReturnType =
7470 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007471 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007472 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007473 QualType ResReturnType =
7474 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7475 if (ResReturnType.isNull())
7476 return QualType();
7477 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7478 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7479 // In either case, use OldReturnType to build the new function type.
7480 const FunctionType *F = LHS->getAs<FunctionType>();
7481 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007482 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7483 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007484 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007485 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007486 return ResultType;
7487 }
7488 }
7489 return QualType();
7490 }
7491
7492 // If the qualifiers are different, the types can still be merged.
7493 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7494 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7495 if (LQuals != RQuals) {
7496 // If any of these qualifiers are different, we have a type mismatch.
7497 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7498 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7499 return QualType();
7500
7501 // Exactly one GC qualifier difference is allowed: __strong is
7502 // okay if the other type has no GC qualifier but is an Objective
7503 // C object pointer (i.e. implicitly strong by default). We fix
7504 // this by pretending that the unqualified type was actually
7505 // qualified __strong.
7506 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7507 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7508 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7509
7510 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7511 return QualType();
7512
7513 if (GC_L == Qualifiers::Strong)
7514 return LHS;
7515 if (GC_R == Qualifiers::Strong)
7516 return RHS;
7517 return QualType();
7518 }
7519
7520 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7521 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7522 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7523 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7524 if (ResQT == LHSBaseQT)
7525 return LHS;
7526 if (ResQT == RHSBaseQT)
7527 return RHS;
7528 }
7529 return QualType();
7530}
7531
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007532//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007533// Integer Predicates
7534//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007535
Jay Foad39c79802011-01-12 09:06:06 +00007536unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007537 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007538 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007539 if (T->isBooleanType())
7540 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007541 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007542 return (unsigned)getTypeSize(T);
7543}
7544
Abramo Bagnara13640492012-09-09 10:21:24 +00007545QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007546 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007547
7548 // Turn <4 x signed int> -> <4 x unsigned int>
7549 if (const VectorType *VTy = T->getAs<VectorType>())
7550 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007551 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007552
7553 // For enums, we return the unsigned version of the base type.
7554 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007555 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007556
7557 const BuiltinType *BTy = T->getAs<BuiltinType>();
7558 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007559 switch (BTy->getKind()) {
7560 case BuiltinType::Char_S:
7561 case BuiltinType::SChar:
7562 return UnsignedCharTy;
7563 case BuiltinType::Short:
7564 return UnsignedShortTy;
7565 case BuiltinType::Int:
7566 return UnsignedIntTy;
7567 case BuiltinType::Long:
7568 return UnsignedLongTy;
7569 case BuiltinType::LongLong:
7570 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007571 case BuiltinType::Int128:
7572 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007573 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007574 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007575 }
7576}
7577
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007578ASTMutationListener::~ASTMutationListener() { }
7579
Richard Smith1fa5d642013-05-11 05:45:24 +00007580void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7581 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007582
7583//===----------------------------------------------------------------------===//
7584// Builtin Type Computation
7585//===----------------------------------------------------------------------===//
7586
7587/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007588/// pointer over the consumed characters. This returns the resultant type. If
7589/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7590/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7591/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007592///
7593/// RequiresICE is filled in on return to indicate whether the value is required
7594/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007595static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007596 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007597 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007598 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007599 // Modifiers.
7600 int HowLong = 0;
7601 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007602 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007603
Chris Lattnerdc226c22010-10-01 22:42:38 +00007604 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007605 bool Done = false;
7606 while (!Done) {
7607 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007608 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007609 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007610 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007611 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007612 case 'S':
7613 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7614 assert(!Signed && "Can't use 'S' modifier multiple times!");
7615 Signed = true;
7616 break;
7617 case 'U':
7618 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007619 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 Unsigned = true;
7621 break;
7622 case 'L':
7623 assert(HowLong <= 2 && "Can't have LLLL modifier");
7624 ++HowLong;
7625 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007626 case 'W':
7627 // This modifier represents int64 type.
7628 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7629 switch (Context.getTargetInfo().getInt64Type()) {
7630 default:
7631 llvm_unreachable("Unexpected integer type");
7632 case TargetInfo::SignedLong:
7633 HowLong = 1;
7634 break;
7635 case TargetInfo::SignedLongLong:
7636 HowLong = 2;
7637 break;
7638 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007639 }
7640 }
7641
7642 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007643
Chris Lattnerecd79c62009-06-14 00:45:47 +00007644 // Read the base type.
7645 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007646 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007647 case 'v':
7648 assert(HowLong == 0 && !Signed && !Unsigned &&
7649 "Bad modifiers used with 'v'!");
7650 Type = Context.VoidTy;
7651 break;
Jack Carter24bef982013-08-15 15:16:57 +00007652 case 'h':
7653 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007654 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007655 Type = Context.HalfTy;
7656 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007657 case 'f':
7658 assert(HowLong == 0 && !Signed && !Unsigned &&
7659 "Bad modifiers used with 'f'!");
7660 Type = Context.FloatTy;
7661 break;
7662 case 'd':
7663 assert(HowLong < 2 && !Signed && !Unsigned &&
7664 "Bad modifiers used with 'd'!");
7665 if (HowLong)
7666 Type = Context.LongDoubleTy;
7667 else
7668 Type = Context.DoubleTy;
7669 break;
7670 case 's':
7671 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7672 if (Unsigned)
7673 Type = Context.UnsignedShortTy;
7674 else
7675 Type = Context.ShortTy;
7676 break;
7677 case 'i':
7678 if (HowLong == 3)
7679 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7680 else if (HowLong == 2)
7681 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7682 else if (HowLong == 1)
7683 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7684 else
7685 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7686 break;
7687 case 'c':
7688 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7689 if (Signed)
7690 Type = Context.SignedCharTy;
7691 else if (Unsigned)
7692 Type = Context.UnsignedCharTy;
7693 else
7694 Type = Context.CharTy;
7695 break;
7696 case 'b': // boolean
7697 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7698 Type = Context.BoolTy;
7699 break;
7700 case 'z': // size_t.
7701 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7702 Type = Context.getSizeType();
7703 break;
7704 case 'F':
7705 Type = Context.getCFConstantStringType();
7706 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007707 case 'G':
7708 Type = Context.getObjCIdType();
7709 break;
7710 case 'H':
7711 Type = Context.getObjCSelType();
7712 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007713 case 'M':
7714 Type = Context.getObjCSuperType();
7715 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007716 case 'a':
7717 Type = Context.getBuiltinVaListType();
7718 assert(!Type.isNull() && "builtin va list type not initialized!");
7719 break;
7720 case 'A':
7721 // This is a "reference" to a va_list; however, what exactly
7722 // this means depends on how va_list is defined. There are two
7723 // different kinds of va_list: ones passed by value, and ones
7724 // passed by reference. An example of a by-value va_list is
7725 // x86, where va_list is a char*. An example of by-ref va_list
7726 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7727 // we want this argument to be a char*&; for x86-64, we want
7728 // it to be a __va_list_tag*.
7729 Type = Context.getBuiltinVaListType();
7730 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007731 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007732 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007733 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007734 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007735 break;
7736 case 'V': {
7737 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007738 unsigned NumElements = strtoul(Str, &End, 10);
7739 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007740 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007741
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007742 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7743 RequiresICE, false);
7744 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007745
7746 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007747 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007748 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007749 break;
7750 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007751 case 'E': {
7752 char *End;
7753
7754 unsigned NumElements = strtoul(Str, &End, 10);
7755 assert(End != Str && "Missing vector size");
7756
7757 Str = End;
7758
7759 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7760 false);
7761 Type = Context.getExtVectorType(ElementType, NumElements);
7762 break;
7763 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007764 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007765 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7766 false);
7767 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007768 Type = Context.getComplexType(ElementType);
7769 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007770 }
7771 case 'Y' : {
7772 Type = Context.getPointerDiffType();
7773 break;
7774 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007775 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007776 Type = Context.getFILEType();
7777 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007778 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007779 return QualType();
7780 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007781 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007782 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007783 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007784 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007785 else
7786 Type = Context.getjmp_bufType();
7787
Mike Stump2adb4da2009-07-28 23:47:15 +00007788 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007789 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007790 return QualType();
7791 }
7792 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007793 case 'K':
7794 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7795 Type = Context.getucontext_tType();
7796
7797 if (Type.isNull()) {
7798 Error = ASTContext::GE_Missing_ucontext;
7799 return QualType();
7800 }
7801 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007802 case 'p':
7803 Type = Context.getProcessIDType();
7804 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007805 }
Mike Stump11289f42009-09-09 15:08:12 +00007806
Chris Lattnerdc226c22010-10-01 22:42:38 +00007807 // If there are modifiers and if we're allowed to parse them, go for it.
7808 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007809 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007810 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007811 default: Done = true; --Str; break;
7812 case '*':
7813 case '&': {
7814 // Both pointers and references can have their pointee types
7815 // qualified with an address space.
7816 char *End;
7817 unsigned AddrSpace = strtoul(Str, &End, 10);
7818 if (End != Str && AddrSpace != 0) {
7819 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7820 Str = End;
7821 }
7822 if (c == '*')
7823 Type = Context.getPointerType(Type);
7824 else
7825 Type = Context.getLValueReferenceType(Type);
7826 break;
7827 }
7828 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7829 case 'C':
7830 Type = Type.withConst();
7831 break;
7832 case 'D':
7833 Type = Context.getVolatileType(Type);
7834 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007835 case 'R':
7836 Type = Type.withRestrict();
7837 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007838 }
7839 }
Chris Lattner84733392010-10-01 07:13:18 +00007840
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007841 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007842 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007843
Chris Lattnerecd79c62009-06-14 00:45:47 +00007844 return Type;
7845}
7846
7847/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007848QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007849 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007850 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007851 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007852
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007853 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007854
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007855 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007856 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007857 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7858 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007859 if (Error != GE_None)
7860 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007861
7862 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7863
Chris Lattnerecd79c62009-06-14 00:45:47 +00007864 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007865 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007866 if (Error != GE_None)
7867 return QualType();
7868
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007869 // If this argument is required to be an IntegerConstantExpression and the
7870 // caller cares, fill in the bitmask we return.
7871 if (RequiresICE && IntegerConstantArgs)
7872 *IntegerConstantArgs |= 1 << ArgTypes.size();
7873
Chris Lattnerecd79c62009-06-14 00:45:47 +00007874 // Do array -> pointer decay. The builtin should use the decayed type.
7875 if (Ty->isArrayType())
7876 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007877
Chris Lattnerecd79c62009-06-14 00:45:47 +00007878 ArgTypes.push_back(Ty);
7879 }
7880
David Majnemerba3e5ec2015-03-13 18:26:17 +00007881 if (Id == Builtin::BI__GetExceptionInfo)
7882 return QualType();
7883
Chris Lattnerecd79c62009-06-14 00:45:47 +00007884 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7885 "'.' should only occur at end of builtin type list!");
7886
Reid Kleckner78af0702013-08-27 23:08:25 +00007887 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007888 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7889
7890 bool Variadic = (TypeStr[0] == '.');
7891
7892 // We really shouldn't be making a no-proto type here, especially in C++.
7893 if (ArgTypes.empty() && Variadic)
7894 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007895
John McCalldb40c7f2010-12-14 08:05:40 +00007896 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007897 EPI.ExtInfo = EI;
7898 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007899
Jordan Rose5c382722013-03-08 21:51:21 +00007900 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007901}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007902
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007903static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7904 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007905 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007906 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007907
Rafael Espindola3ae00052013-05-13 00:12:11 +00007908 GVALinkage External = GVA_StrongExternal;
7909 switch (FD->getTemplateSpecializationKind()) {
7910 case TSK_Undeclared:
7911 case TSK_ExplicitSpecialization:
7912 External = GVA_StrongExternal;
7913 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007914
Rafael Espindola3ae00052013-05-13 00:12:11 +00007915 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007916 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007917
David Majnemerc3d07332014-05-15 06:25:57 +00007918 // C++11 [temp.explicit]p10:
7919 // [ Note: The intent is that an inline function that is the subject of
7920 // an explicit instantiation declaration will still be implicitly
7921 // instantiated when used so that the body can be considered for
7922 // inlining, but that no out-of-line copy of the inline function would be
7923 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007924 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007925 return GVA_AvailableExternally;
7926
Rafael Espindola3ae00052013-05-13 00:12:11 +00007927 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007928 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007929 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007930 }
7931
7932 if (!FD->isInlined())
7933 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007934
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007935 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7936 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007937 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007938 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7939
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007940 // GNU or C99 inline semantics. Determine whether this symbol should be
7941 // externally visible.
7942 if (FD->isInlineDefinitionExternallyVisible())
7943 return External;
7944
7945 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007946 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007947 }
7948
David Majnemer54e3ba52014-04-02 23:17:29 +00007949 // Functions specified with extern and inline in -fms-compatibility mode
7950 // forcibly get emitted. While the body of the function cannot be later
7951 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00007952 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00007953 return GVA_StrongODR;
7954
David Majnemer27d69db2014-04-28 22:17:59 +00007955 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007956}
7957
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007958static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7959 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7960 // dllexport/dllimport on inline functions.
7961 if (D->hasAttr<DLLImportAttr>()) {
7962 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7963 return GVA_AvailableExternally;
7964 } else if (D->hasAttr<DLLExportAttr>()) {
7965 if (L == GVA_DiscardableODR)
7966 return GVA_StrongODR;
7967 }
7968 return L;
7969}
7970
7971GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7972 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7973 FD);
7974}
7975
7976static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7977 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007978 if (!VD->isExternallyVisible())
7979 return GVA_Internal;
7980
David Majnemer27d69db2014-04-28 22:17:59 +00007981 if (VD->isStaticLocal()) {
7982 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7983 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7984 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7985 LexicalContext = LexicalContext->getLexicalParent();
7986
Richard Smith9e2341d2015-03-23 03:25:59 +00007987 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00007988 // enclosing function.
7989 if (LexicalContext)
7990 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007991 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007992
7993 // GVA_StrongODR function linkage is stronger than what we need,
7994 // downgrade to GVA_DiscardableODR.
7995 // This allows us to discard the variable if we never end up needing it.
7996 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7997 : StaticLocalLinkage;
7998 }
7999
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008000 // MSVC treats in-class initialized static data members as definitions.
8001 // By giving them non-strong linkage, out-of-line definitions won't
8002 // cause link errors.
8003 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8004 return GVA_DiscardableODR;
8005
Richard Smith8809a0c2013-09-27 20:14:12 +00008006 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008007 case TSK_Undeclared:
8008 case TSK_ExplicitSpecialization:
8009 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008010
Rafael Espindola3ae00052013-05-13 00:12:11 +00008011 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008012 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008013
David Majnemer27d69db2014-04-28 22:17:59 +00008014 case TSK_ExplicitInstantiationDeclaration:
8015 return GVA_AvailableExternally;
8016
Rafael Espindola3ae00052013-05-13 00:12:11 +00008017 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008018 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008019 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008020
8021 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008022}
8023
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008024GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8025 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8026 VD);
8027}
8028
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008029bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008030 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8031 if (!VD->isFileVarDecl())
8032 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008033 // Global named register variables (GNU extension) are never emitted.
8034 if (VD->getStorageClass() == SC_Register)
8035 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008036 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8037 // We never need to emit an uninstantiated function template.
8038 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8039 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008040 } else if (isa<OMPThreadPrivateDecl>(D))
8041 return true;
8042 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008043 return false;
8044
8045 // If this is a member of a class template, we do not need to emit it.
8046 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008047 return false;
8048
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008049 // Weak references don't produce any output by themselves.
8050 if (D->hasAttr<WeakRefAttr>())
8051 return false;
8052
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008053 // Aliases and used decls are required.
8054 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8055 return true;
8056
8057 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8058 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008059 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008060 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008061
8062 // Constructors and destructors are required.
8063 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8064 return true;
8065
John McCall6bd2a892013-01-25 22:31:03 +00008066 // The key function for a class is required. This rule only comes
8067 // into play when inline functions can be key functions, though.
8068 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8069 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8070 const CXXRecordDecl *RD = MD->getParent();
8071 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8072 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8073 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8074 return true;
8075 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008076 }
8077 }
8078
8079 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8080
8081 // static, static inline, always_inline, and extern inline functions can
8082 // always be deferred. Normal inline functions can be deferred in C99/C++.
8083 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008084 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8085 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008086 return false;
8087 return true;
8088 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008089
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008090 const VarDecl *VD = cast<VarDecl>(D);
8091 assert(VD->isFileVarDecl() && "Expected file scoped var");
8092
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008093 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8094 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008095 return false;
8096
Richard Smitha0e5e542012-11-12 21:38:00 +00008097 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008098 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008099 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8100 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008101 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008102
Richard Smitha0e5e542012-11-12 21:38:00 +00008103 // Variables that have destruction with side-effects are required.
8104 if (VD->getType().isDestructedType())
8105 return true;
8106
8107 // Variables that have initialization with side-effects are required.
8108 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8109 return true;
8110
8111 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008112}
Charles Davis53c59df2010-08-16 03:33:14 +00008113
Reid Kleckner78af0702013-08-27 23:08:25 +00008114CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8115 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008116 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008117 if (IsCXXMethod)
8118 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008119
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008120 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8121
8122 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008123}
8124
Jay Foad39c79802011-01-12 09:06:06 +00008125bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008126 // Pass through to the C++ ABI object
8127 return ABI->isNearlyEmpty(RD);
8128}
8129
Reid Kleckner96f8f932014-02-05 17:27:08 +00008130VTableContextBase *ASTContext::getVTableContext() {
8131 if (!VTContext.get()) {
8132 if (Target->getCXXABI().isMicrosoft())
8133 VTContext.reset(new MicrosoftVTableContext(*this));
8134 else
8135 VTContext.reset(new ItaniumVTableContext(*this));
8136 }
8137 return VTContext.get();
8138}
8139
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008140MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008141 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008142 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008143 case TargetCXXABI::GenericItanium:
8144 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008145 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008146 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008147 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008148 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008149 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008150 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008151 }
David Blaikie83d382b2011-09-23 05:06:16 +00008152 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008153}
8154
Charles Davis53c59df2010-08-16 03:33:14 +00008155CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008156
8157size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008158 return ASTRecordLayouts.getMemorySize() +
8159 llvm::capacity_in_bytes(ObjCLayouts) +
8160 llvm::capacity_in_bytes(KeyFunctions) +
8161 llvm::capacity_in_bytes(ObjCImpls) +
8162 llvm::capacity_in_bytes(BlockVarCopyInits) +
8163 llvm::capacity_in_bytes(DeclAttrs) +
8164 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8165 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8166 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8167 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8168 llvm::capacity_in_bytes(OverriddenMethods) +
8169 llvm::capacity_in_bytes(Types) +
8170 llvm::capacity_in_bytes(VariableArrayTypes) +
8171 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008172}
Ted Kremenek540017e2011-10-06 05:00:56 +00008173
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008174/// getIntTypeForBitwidth -
8175/// sets integer QualTy according to specified details:
8176/// bitwidth, signed/unsigned.
8177/// Returns empty type if there is no appropriate target types.
8178QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8179 unsigned Signed) const {
8180 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8181 CanQualType QualTy = getFromTargetType(Ty);
8182 if (!QualTy && DestWidth == 128)
8183 return Signed ? Int128Ty : UnsignedInt128Ty;
8184 return QualTy;
8185}
8186
8187/// getRealTypeForBitwidth -
8188/// sets floating point QualTy according to specified bitwidth.
8189/// Returns empty type if there is no appropriate target types.
8190QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8191 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8192 switch (Ty) {
8193 case TargetInfo::Float:
8194 return FloatTy;
8195 case TargetInfo::Double:
8196 return DoubleTy;
8197 case TargetInfo::LongDouble:
8198 return LongDoubleTy;
8199 case TargetInfo::NoFloat:
8200 return QualType();
8201 }
8202
8203 llvm_unreachable("Unhandled TargetInfo::RealType value");
8204}
8205
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008206void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8207 if (Number > 1)
8208 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008209}
8210
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008211unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8212 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8213 MangleNumbers.find(ND);
8214 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008215}
8216
David Majnemer2206bf52014-03-05 08:57:59 +00008217void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8218 if (Number > 1)
8219 StaticLocalNumbers[VD] = Number;
8220}
8221
8222unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8223 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8224 StaticLocalNumbers.find(VD);
8225 return I != StaticLocalNumbers.end() ? I->second : 1;
8226}
8227
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008228MangleNumberingContext &
8229ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008230 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8231 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8232 if (!MCtx)
8233 MCtx = createMangleNumberingContext();
8234 return *MCtx;
8235}
8236
8237MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8238 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008239}
8240
David Majnemere7a818f2015-03-06 18:53:55 +00008241const CXXConstructorDecl *
8242ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8243 return ABI->getCopyConstructorForExceptionObject(
8244 cast<CXXRecordDecl>(RD->getFirstDecl()));
8245}
8246
8247void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8248 CXXConstructorDecl *CD) {
8249 return ABI->addCopyConstructorForExceptionObject(
8250 cast<CXXRecordDecl>(RD->getFirstDecl()),
8251 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8252}
8253
David Majnemerdfa6d202015-03-11 18:36:39 +00008254void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8255 unsigned ParmIdx, Expr *DAE) {
8256 ABI->addDefaultArgExprForConstructor(
8257 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8258}
8259
8260Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8261 unsigned ParmIdx) {
8262 return ABI->getDefaultArgExprForConstructor(
8263 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8264}
8265
Ted Kremenek540017e2011-10-06 05:00:56 +00008266void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8267 ParamIndices[D] = index;
8268}
8269
8270unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8271 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8272 assert(I != ParamIndices.end() &&
8273 "ParmIndices lacks entry set by ParmVarDecl");
8274 return I->second;
8275}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008276
Richard Smithe6c01442013-06-05 00:46:14 +00008277APValue *
8278ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8279 bool MayCreate) {
8280 assert(E && E->getStorageDuration() == SD_Static &&
8281 "don't need to cache the computed value for this temporary");
8282 if (MayCreate)
8283 return &MaterializedTemporaryValues[E];
8284
8285 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8286 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008287 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008288}
8289
Fariborz Jahanian615de762013-05-28 17:37:39 +00008290bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8291 const llvm::Triple &T = getTargetInfo().getTriple();
8292 if (!T.isOSDarwin())
8293 return false;
8294
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008295 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8296 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8297 return false;
8298
Fariborz Jahanian615de762013-05-28 17:37:39 +00008299 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8300 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8301 uint64_t Size = sizeChars.getQuantity();
8302 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8303 unsigned Align = alignChars.getQuantity();
8304 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8305 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8306}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008307
8308namespace {
8309
8310 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8311 /// parents as defined by the \c RecursiveASTVisitor.
8312 ///
8313 /// Note that the relationship described here is purely in terms of AST
8314 /// traversal - there are other relationships (for example declaration context)
8315 /// in the AST that are better modeled by special matchers.
8316 ///
8317 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8318 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8319
8320 public:
8321 /// \brief Builds and returns the translation unit's parent map.
8322 ///
8323 /// The caller takes ownership of the returned \c ParentMap.
8324 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8325 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8326 Visitor.TraverseDecl(&TU);
8327 return Visitor.Parents;
8328 }
8329
8330 private:
8331 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8332
8333 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8334 }
8335
8336 bool shouldVisitTemplateInstantiations() const {
8337 return true;
8338 }
8339 bool shouldVisitImplicitCode() const {
8340 return true;
8341 }
8342 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8343 // are not triggered during data recursion.
8344 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8345 return false;
8346 }
8347
8348 template <typename T>
8349 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008350 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008351 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008352 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008353 // FIXME: Currently we add the same parent multiple times, but only
8354 // when no memoization data is available for the type.
8355 // For example when we visit all subexpressions of template
8356 // instantiations; this is suboptimal, but benign: the only way to
8357 // visit those is with hasAncestor / hasParent, and those do not create
8358 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008359 // The plan is to enable DynTypedNode to be storable in a map or hash
8360 // map. The main problem there is to implement hash functions /
8361 // comparison operators for all types that DynTypedNode supports that
8362 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008363 auto &NodeOrVector = (*Parents)[Node];
8364 if (NodeOrVector.isNull()) {
8365 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008366 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008367 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8368 auto *Node =
8369 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8370 auto *Vector = new ASTContext::ParentVector(1, *Node);
8371 NodeOrVector = Vector;
8372 delete Node;
8373 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008374 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008375
8376 auto *Vector =
8377 NodeOrVector.template get<ASTContext::ParentVector *>();
8378 // Skip duplicates for types that have memoization data.
8379 // We must check that the type has memoization data before calling
8380 // std::find() because DynTypedNode::operator== can't compare all
8381 // types.
8382 bool Found = ParentStack.back().getMemoizationData() &&
8383 std::find(Vector->begin(), Vector->end(),
8384 ParentStack.back()) != Vector->end();
8385 if (!Found)
8386 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008387 }
8388 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008389 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8390 bool Result = (this ->* traverse) (Node);
8391 ParentStack.pop_back();
8392 return Result;
8393 }
8394
8395 bool TraverseDecl(Decl *DeclNode) {
8396 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8397 }
8398
8399 bool TraverseStmt(Stmt *StmtNode) {
8400 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8401 }
8402
8403 ASTContext::ParentMap *Parents;
8404 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8405
8406 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8407 };
8408
8409} // end namespace
8410
Benjamin Kramer07935292014-10-04 17:01:26 +00008411ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008412ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8413 assert(Node.getMemoizationData() &&
8414 "Invariant broken: only nodes that support memoization may be "
8415 "used in the parent map.");
8416 if (!AllParents) {
8417 // We always need to run over the whole translation unit, as
8418 // hasAncestor can escape any subtree.
8419 AllParents.reset(
8420 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8421 }
8422 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8423 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008424 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008425 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008426 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8427 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008428 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008429 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008430}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008431
8432bool
8433ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8434 const ObjCMethodDecl *MethodImpl) {
8435 // No point trying to match an unavailable/deprecated mothod.
8436 if (MethodDecl->hasAttr<UnavailableAttr>()
8437 || MethodDecl->hasAttr<DeprecatedAttr>())
8438 return false;
8439 if (MethodDecl->getObjCDeclQualifier() !=
8440 MethodImpl->getObjCDeclQualifier())
8441 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008442 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008443 return false;
8444
8445 if (MethodDecl->param_size() != MethodImpl->param_size())
8446 return false;
8447
8448 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8449 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8450 EF = MethodDecl->param_end();
8451 IM != EM && IF != EF; ++IM, ++IF) {
8452 const ParmVarDecl *DeclVar = (*IF);
8453 const ParmVarDecl *ImplVar = (*IM);
8454 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8455 return false;
8456 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8457 return false;
8458 }
8459 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8460
8461}
Richard Smith053f6c62014-05-16 23:01:30 +00008462
8463// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8464// doesn't include ASTContext.h
8465template
8466clang::LazyGenerationalUpdatePtr<
8467 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8468clang::LazyGenerationalUpdatePtr<
8469 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8470 const clang::ASTContext &Ctx, Decl *Value);