blob: fc40f7e8e2387de6013c1433986946b198d3f491 [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),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000741 FirstLocalImport(), LastLocalImport(), SourceMgr(SM), LangOpts(LOpts),
742 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000743 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
744 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
745 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
746 Comments(SM), CommentsLoaded(false),
747 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000748 TUDecl = TranslationUnitDecl::Create(*this);
749}
750
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000751ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000752 ReleaseParentMapEntries();
753
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000757
Manuel Klimeka7328992013-06-03 13:51:33 +0000758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
763
Ted Kremenek076baeb2010-06-08 23:00:58 +0000764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771 R->Destroy(*this);
772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000779
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
782 A != AEnd; ++A)
783 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000784
Reid Kleckner588c9372014-02-19 23:44:52 +0000785 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000786}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000787
Manuel Klimek95403e62014-05-21 13:28:59 +0000788void ASTContext::ReleaseParentMapEntries() {
789 if (!AllParents) return;
790 for (const auto &Entry : *AllParents) {
791 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
792 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
793 } else {
794 assert(Entry.second.is<ParentVector *>());
795 delete Entry.second.get<ParentVector *>();
796 }
797 }
798}
799
Douglas Gregor1a809332010-05-23 18:26:36 +0000800void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000801 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000802}
803
Mike Stump11289f42009-09-09 15:08:12 +0000804void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000805ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
806 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000807}
808
Chris Lattner4eb445d2007-01-26 01:27:23 +0000809void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000810 llvm::errs() << "\n*** AST Context Stats:\n";
811 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000812
Douglas Gregora30d0462009-05-26 14:40:08 +0000813 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000814#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000815#define ABSTRACT_TYPE(Name, Parent)
816#include "clang/AST/TypeNodes.def"
817 0 // Extra
818 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000819
Chris Lattner4eb445d2007-01-26 01:27:23 +0000820 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
821 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000822 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000823 }
824
Douglas Gregora30d0462009-05-26 14:40:08 +0000825 unsigned Idx = 0;
826 unsigned TotalBytes = 0;
827#define TYPE(Name, Parent) \
828 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000829 llvm::errs() << " " << counts[Idx] << " " << #Name \
830 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000831 TotalBytes += counts[Idx] * sizeof(Name##Type); \
832 ++Idx;
833#define ABSTRACT_TYPE(Name, Parent)
834#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
837
Douglas Gregor7454c562010-07-02 20:37:36 +0000838 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000839 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
840 << NumImplicitDefaultConstructors
841 << " implicit default constructors created\n";
842 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
843 << NumImplicitCopyConstructors
844 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000845 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
847 << NumImplicitMoveConstructors
848 << " implicit move constructors created\n";
849 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
850 << NumImplicitCopyAssignmentOperators
851 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
854 << NumImplicitMoveAssignmentOperators
855 << " implicit move assignment operators created\n";
856 llvm::errs() << NumImplicitDestructorsDeclared << "/"
857 << NumImplicitDestructors
858 << " implicit destructors created\n";
859
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000860 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000861 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000862 ExternalSource->PrintStats();
863 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000864
Douglas Gregor5b11d492010-07-25 17:53:33 +0000865 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000866}
867
Alp Toker2dea15b2013-12-17 01:22:38 +0000868RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
869 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000870 SourceLocation Loc;
871 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000872 if (getLangOpts().CPlusPlus)
873 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
874 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000875 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000876 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
877 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000878 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000879 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
880 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000881 return NewDecl;
882}
883
884TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
885 StringRef Name) const {
886 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
887 TypedefDecl *NewDecl = TypedefDecl::Create(
888 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
889 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
890 NewDecl->setImplicit();
891 return NewDecl;
892}
893
Douglas Gregor801c99d2011-08-12 06:49:56 +0000894TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000895 if (!Int128Decl)
896 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000897 return Int128Decl;
898}
899
900TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000901 if (!UInt128Decl)
902 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000903 return UInt128Decl;
904}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000905
Nico Webere1687c52013-06-20 21:44:55 +0000906TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000907 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000908 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000909 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000910
Nico Webere1687c52013-06-20 21:44:55 +0000911 return Float128StubDecl;
912}
913
John McCall48f2d582009-10-23 23:03:21 +0000914void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000915 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000916 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000917 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000918}
919
Douglas Gregore8bbc122011-09-02 00:18:52 +0000920void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
921 assert((!this->Target || this->Target == &Target) &&
922 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000923 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000924
Douglas Gregore8bbc122011-09-02 00:18:52 +0000925 this->Target = &Target;
926
927 ABI.reset(createCXXABI(Target));
928 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000929 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000930
Chris Lattner970e54e2006-11-12 00:37:36 +0000931 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000932 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000933
Chris Lattner970e54e2006-11-12 00:37:36 +0000934 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000935 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000936 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000937 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000938 InitBuiltinType(CharTy, BuiltinType::Char_S);
939 else
940 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000941 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000942 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
943 InitBuiltinType(ShortTy, BuiltinType::Short);
944 InitBuiltinType(IntTy, BuiltinType::Int);
945 InitBuiltinType(LongTy, BuiltinType::Long);
946 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000947
Chris Lattner970e54e2006-11-12 00:37:36 +0000948 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000949 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
950 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
951 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
952 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
953 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000954
Chris Lattner970e54e2006-11-12 00:37:36 +0000955 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000956 InitBuiltinType(FloatTy, BuiltinType::Float);
957 InitBuiltinType(DoubleTy, BuiltinType::Double);
958 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000959
Chris Lattnerf122cef2009-04-30 02:43:43 +0000960 // GNU extension, 128-bit integers.
961 InitBuiltinType(Int128Ty, BuiltinType::Int128);
962 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
963
Hans Wennborg0d81e012013-05-10 10:08:40 +0000964 // C++ 3.9.1p5
965 if (TargetInfo::isTypeSigned(Target.getWCharType()))
966 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
967 else // -fshort-wchar makes wchar_t be unsigned.
968 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
969 if (LangOpts.CPlusPlus && LangOpts.WChar)
970 WideCharTy = WCharTy;
971 else {
972 // C99 (or C++ using -fno-wchar).
973 WideCharTy = getFromTargetType(Target.getWCharType());
974 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000975
James Molloy36365542012-05-04 10:55:22 +0000976 WIntTy = getFromTargetType(Target.getWIntType());
977
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000978 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
979 InitBuiltinType(Char16Ty, BuiltinType::Char16);
980 else // C99
981 Char16Ty = getFromTargetType(Target.getChar16Type());
982
983 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
984 InitBuiltinType(Char32Ty, BuiltinType::Char32);
985 else // C99
986 Char32Ty = getFromTargetType(Target.getChar32Type());
987
Douglas Gregor4619e432008-12-05 23:32:09 +0000988 // Placeholder type for type-dependent expressions whose type is
989 // completely unknown. No code should ever check a type against
990 // DependentTy and users should never see it; however, it is here to
991 // help diagnose failures to properly check for type-dependent
992 // expressions.
993 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000994
John McCall36e7fe32010-10-12 00:20:44 +0000995 // Placeholder type for functions.
996 InitBuiltinType(OverloadTy, BuiltinType::Overload);
997
John McCall0009fcc2011-04-26 20:42:42 +0000998 // Placeholder type for bound members.
999 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1000
John McCall526ab472011-10-25 17:37:35 +00001001 // Placeholder type for pseudo-objects.
1002 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1003
John McCall31996342011-04-07 08:22:57 +00001004 // "any" type; useful for debugger-like clients.
1005 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1006
John McCall8a6b59a2011-10-17 18:09:15 +00001007 // Placeholder type for unbridged ARC casts.
1008 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1009
Eli Friedman34866c72012-08-31 00:14:07 +00001010 // Placeholder type for builtin functions.
1011 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1012
Chris Lattner970e54e2006-11-12 00:37:36 +00001013 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001014 FloatComplexTy = getComplexType(FloatTy);
1015 DoubleComplexTy = getComplexType(DoubleTy);
1016 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001018 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001019 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1020 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001021 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001022
1023 if (LangOpts.OpenCL) {
1024 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1025 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1026 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1027 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1028 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1029 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001030
Guy Benyei61054192013-02-07 10:55:47 +00001031 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001032 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001033 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001034
1035 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001036 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1037 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001038
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001039 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001040
1041 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001042
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001043 // void * type
1044 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001045
1046 // nullptr type (C++0x 2.14.7)
1047 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001048
1049 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1050 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001051
1052 // Builtin type used to help define __builtin_va_list.
1053 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001054}
1055
David Blaikie9c902b52011-09-25 23:23:43 +00001056DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001057 return SourceMgr.getDiagnostics();
1058}
1059
Douglas Gregor561eceb2010-08-30 16:49:28 +00001060AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1061 AttrVec *&Result = DeclAttrs[D];
1062 if (!Result) {
1063 void *Mem = Allocate(sizeof(AttrVec));
1064 Result = new (Mem) AttrVec;
1065 }
1066
1067 return *Result;
1068}
1069
1070/// \brief Erase the attributes corresponding to the given declaration.
1071void ASTContext::eraseDeclAttrs(const Decl *D) {
1072 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1073 if (Pos != DeclAttrs.end()) {
1074 Pos->second->~AttrVec();
1075 DeclAttrs.erase(Pos);
1076 }
1077}
1078
Larisse Voufo39a1e502013-08-06 01:03:05 +00001079// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001080MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001081ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001082 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001083 return getTemplateOrSpecializationInfo(Var)
1084 .dyn_cast<MemberSpecializationInfo *>();
1085}
1086
1087ASTContext::TemplateOrSpecializationInfo
1088ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1089 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1090 TemplateOrInstantiation.find(Var);
1091 if (Pos == TemplateOrInstantiation.end())
1092 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001093
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001094 return Pos->second;
1095}
1096
Mike Stump11289f42009-09-09 15:08:12 +00001097void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001098ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001099 TemplateSpecializationKind TSK,
1100 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001101 assert(Inst->isStaticDataMember() && "Not a static data member");
1102 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001103 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1104 Tmpl, TSK, PointOfInstantiation));
1105}
1106
1107void
1108ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1109 TemplateOrSpecializationInfo TSI) {
1110 assert(!TemplateOrInstantiation[Inst] &&
1111 "Already noted what the variable was instantiated from");
1112 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001113}
1114
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001115FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1116 const FunctionDecl *FD){
1117 assert(FD && "Specialization is 0");
1118 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001119 = ClassScopeSpecializationPattern.find(FD);
1120 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001121 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001122
1123 return Pos->second;
1124}
1125
1126void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1127 FunctionDecl *Pattern) {
1128 assert(FD && "Specialization is 0");
1129 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001130 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001131}
1132
John McCalle61f2ba2009-11-18 02:36:19 +00001133NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001134ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001135 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001136 = InstantiatedFromUsingDecl.find(UUD);
1137 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001138 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001139
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001140 return Pos->second;
1141}
1142
1143void
John McCallb96ec562009-12-04 22:46:56 +00001144ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1145 assert((isa<UsingDecl>(Pattern) ||
1146 isa<UnresolvedUsingValueDecl>(Pattern) ||
1147 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1148 "pattern decl is not a using decl");
1149 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1150 InstantiatedFromUsingDecl[Inst] = Pattern;
1151}
1152
1153UsingShadowDecl *
1154ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1155 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1156 = InstantiatedFromUsingShadowDecl.find(Inst);
1157 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001158 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001159
1160 return Pos->second;
1161}
1162
1163void
1164ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1165 UsingShadowDecl *Pattern) {
1166 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1167 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001168}
1169
Anders Carlsson5da84842009-09-01 04:26:58 +00001170FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1171 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1172 = InstantiatedFromUnnamedFieldDecl.find(Field);
1173 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001174 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001175
Anders Carlsson5da84842009-09-01 04:26:58 +00001176 return Pos->second;
1177}
1178
1179void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1180 FieldDecl *Tmpl) {
1181 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1182 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1183 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1184 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001185
Anders Carlsson5da84842009-09-01 04:26:58 +00001186 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1187}
1188
Douglas Gregor832940b2010-03-02 23:58:15 +00001189ASTContext::overridden_cxx_method_iterator
1190ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1191 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001192 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001193 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001194 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001195
1196 return Pos->second.begin();
1197}
1198
1199ASTContext::overridden_cxx_method_iterator
1200ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1201 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001202 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001203 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001204 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001205
1206 return Pos->second.end();
1207}
1208
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001209unsigned
1210ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1211 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001212 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001213 if (Pos == OverriddenMethods.end())
1214 return 0;
1215
1216 return Pos->second.size();
1217}
1218
Douglas Gregor832940b2010-03-02 23:58:15 +00001219void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1220 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001221 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001222 OverriddenMethods[Method].push_back(Overridden);
1223}
1224
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001225void ASTContext::getOverriddenMethods(
1226 const NamedDecl *D,
1227 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001228 assert(D);
1229
1230 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001231 Overridden.append(overridden_methods_begin(CXXMethod),
1232 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001233 return;
1234 }
1235
1236 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1237 if (!Method)
1238 return;
1239
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001240 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1241 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001242 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001243}
1244
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001245void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1246 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1247 assert(!Import->isFromASTFile() && "Non-local import declaration");
1248 if (!FirstLocalImport) {
1249 FirstLocalImport = Import;
1250 LastLocalImport = Import;
1251 return;
1252 }
1253
1254 LastLocalImport->NextLocalImport = Import;
1255 LastLocalImport = Import;
1256}
1257
Chris Lattner53cfe802007-07-18 17:52:12 +00001258//===----------------------------------------------------------------------===//
1259// Type Sizing and Analysis
1260//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001261
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001262/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1263/// scalar floating point type.
1264const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001265 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001266 assert(BT && "Not a floating point type!");
1267 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001268 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001269 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001270 case BuiltinType::Float: return Target->getFloatFormat();
1271 case BuiltinType::Double: return Target->getDoubleFormat();
1272 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001273 }
1274}
1275
Rafael Espindola71eccb32013-08-08 19:53:46 +00001276CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001277 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001278
John McCall94268702010-10-08 18:24:19 +00001279 bool UseAlignAttrOnly = false;
1280 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1281 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001282
John McCall94268702010-10-08 18:24:19 +00001283 // __attribute__((aligned)) can increase or decrease alignment
1284 // *except* on a struct or struct member, where it only increases
1285 // alignment unless 'packed' is also specified.
1286 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001287 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001288 // ignore that possibility; Sema should diagnose it.
1289 if (isa<FieldDecl>(D)) {
1290 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1291 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1292 } else {
1293 UseAlignAttrOnly = true;
1294 }
1295 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001296 else if (isa<FieldDecl>(D))
1297 UseAlignAttrOnly =
1298 D->hasAttr<PackedAttr>() ||
1299 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001300
John McCall4e819612011-01-20 07:57:12 +00001301 // If we're using the align attribute only, just ignore everything
1302 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001303 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001304 // do nothing
1305
John McCall94268702010-10-08 18:24:19 +00001306 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001307 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001308 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001309 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001310 T = RT->getPointeeType();
1311 else
1312 T = getPointerType(RT->getPointeeType());
1313 }
Richard Smithf6d70302014-06-10 23:34:28 +00001314 QualType BaseT = getBaseElementType(T);
1315 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001316 // Adjust alignments of declarations with array type by the
1317 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001318 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001319 unsigned MinWidth = Target->getLargeArrayMinWidth();
1320 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001321 if (isa<VariableArrayType>(arrayType))
1322 Align = std::max(Align, Target->getLargeArrayAlign());
1323 else if (isa<ConstantArrayType>(arrayType) &&
1324 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1325 Align = std::max(Align, Target->getLargeArrayAlign());
1326 }
John McCall33ddac02011-01-19 10:06:00 +00001327 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001328 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001329 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1330 if (VD->hasGlobalStorage())
1331 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1332 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001333 }
John McCall4e819612011-01-20 07:57:12 +00001334
1335 // Fields can be subject to extra alignment constraints, like if
1336 // the field is packed, the struct is packed, or the struct has a
1337 // a max-field-alignment constraint (#pragma pack). So calculate
1338 // the actual alignment of the field within the struct, and then
1339 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001340 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1341 const RecordDecl *Parent = Field->getParent();
1342 // We can only produce a sensible answer if the record is valid.
1343 if (!Parent->isInvalidDecl()) {
1344 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001345
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001346 // Start with the record's overall alignment.
1347 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001348
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001349 // Use the GCD of that and the offset within the record.
1350 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1351 if (Offset > 0) {
1352 // Alignment is always a power of 2, so the GCD will be a power of 2,
1353 // which means we get to do this crazy thing instead of Euclid's.
1354 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1355 if (LowBitOfOffset < FieldAlign)
1356 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1357 }
1358
1359 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001360 }
Charles Davis3fc51072010-02-23 04:52:00 +00001361 }
Chris Lattner68061312009-01-24 21:53:27 +00001362 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001363
Ken Dyckcc56c542011-01-15 18:38:59 +00001364 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001365}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001366
John McCallf1249922012-08-21 04:10:00 +00001367// getTypeInfoDataSizeInChars - Return the size of a type, in
1368// chars. If the type is a record, its data size is returned. This is
1369// the size of the memcpy that's performed when assigning this type
1370// using a trivial copy/move assignment operator.
1371std::pair<CharUnits, CharUnits>
1372ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1373 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1374
1375 // In C++, objects can sometimes be allocated into the tail padding
1376 // of a base-class subobject. We decide whether that's possible
1377 // during class layout, so here we can just trust the layout results.
1378 if (getLangOpts().CPlusPlus) {
1379 if (const RecordType *RT = T->getAs<RecordType>()) {
1380 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1381 sizeAndAlign.first = layout.getDataSize();
1382 }
1383 }
1384
1385 return sizeAndAlign;
1386}
1387
Richard Trieu04d2d942013-05-14 21:59:17 +00001388/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1389/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1390std::pair<CharUnits, CharUnits>
1391static getConstantArrayInfoInChars(const ASTContext &Context,
1392 const ConstantArrayType *CAT) {
1393 std::pair<CharUnits, CharUnits> EltInfo =
1394 Context.getTypeInfoInChars(CAT->getElementType());
1395 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001396 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1397 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001398 "Overflow in array type char size evaluation");
1399 uint64_t Width = EltInfo.first.getQuantity() * Size;
1400 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001401 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1402 Context.getTargetInfo().getPointerWidth(0) == 64)
1403 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001404 return std::make_pair(CharUnits::fromQuantity(Width),
1405 CharUnits::fromQuantity(Align));
1406}
1407
John McCall87fe5d52010-05-20 01:18:31 +00001408std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001409ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001410 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1411 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001412 TypeInfo Info = getTypeInfo(T);
1413 return std::make_pair(toCharUnitsFromBits(Info.Width),
1414 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001415}
1416
1417std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001418ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001419 return getTypeInfoInChars(T.getTypePtr());
1420}
1421
David Majnemer34b57492014-07-30 01:30:47 +00001422bool ASTContext::isAlignmentRequired(const Type *T) const {
1423 return getTypeInfo(T).AlignIsRequired;
1424}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001425
David Majnemer34b57492014-07-30 01:30:47 +00001426bool ASTContext::isAlignmentRequired(QualType T) const {
1427 return isAlignmentRequired(T.getTypePtr());
1428}
1429
1430TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001431 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1432 if (I != MemoizedTypeInfo.end())
1433 return I->second;
1434
1435 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1436 TypeInfo TI = getTypeInfoImpl(T);
1437 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001438 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001439}
1440
1441/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1442/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001443///
1444/// FIXME: Pointers into different addr spaces could have different sizes and
1445/// alignment requirements: getPointerInfo should take an AddrSpace, this
1446/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001447TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1448 uint64_t Width = 0;
1449 unsigned Align = 8;
1450 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001451 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001452#define TYPE(Class, Base)
1453#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001454#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001455#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001456#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1457 case Type::Class: \
1458 assert(!T->isDependentType() && "should not see dependent types here"); \
1459 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001460#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001461 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001462
Chris Lattner355332d2007-07-13 22:27:08 +00001463 case Type::FunctionNoProto:
1464 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001465 // GCC extension: alignof(function) = 32 bits
1466 Width = 0;
1467 Align = 32;
1468 break;
1469
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001470 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001471 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001472 Width = 0;
1473 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1474 break;
1475
Steve Naroff5c131802007-08-30 01:06:46 +00001476 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001477 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001478
David Majnemer34b57492014-07-30 01:30:47 +00001479 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001480 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001481 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001482 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001483 Width = EltInfo.Width * Size;
1484 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001485 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1486 getTargetInfo().getPointerWidth(0) == 64)
1487 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001488 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001489 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001490 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001491 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001492 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001493 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1494 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001495 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001496 // If the alignment is not a power of 2, round up to the next power of 2.
1497 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001498 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001499 Align = llvm::NextPowerOf2(Align);
1500 Width = llvm::RoundUpToAlignment(Width, Align);
1501 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001502 // Adjust the alignment based on the target max.
1503 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1504 if (TargetVectorAlign && TargetVectorAlign < Align)
1505 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001506 break;
1507 }
Chris Lattner647fb222007-07-18 18:26:58 +00001508
Chris Lattner7570e9c2008-03-08 08:52:55 +00001509 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001510 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001511 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001512 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001513 // GCC extension: alignof(void) = 8 bits.
1514 Width = 0;
1515 Align = 8;
1516 break;
1517
Chris Lattner6a4f7452007-12-19 19:23:28 +00001518 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001519 Width = Target->getBoolWidth();
1520 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001521 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001522 case BuiltinType::Char_S:
1523 case BuiltinType::Char_U:
1524 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001525 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001526 Width = Target->getCharWidth();
1527 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001528 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001529 case BuiltinType::WChar_S:
1530 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001531 Width = Target->getWCharWidth();
1532 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001533 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001534 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001535 Width = Target->getChar16Width();
1536 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001537 break;
1538 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 Width = Target->getChar32Width();
1540 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001541 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001542 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001543 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001544 Width = Target->getShortWidth();
1545 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001546 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001547 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001548 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001549 Width = Target->getIntWidth();
1550 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001552 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001553 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001554 Width = Target->getLongWidth();
1555 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001556 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001557 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001559 Width = Target->getLongLongWidth();
1560 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001561 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001562 case BuiltinType::Int128:
1563 case BuiltinType::UInt128:
1564 Width = 128;
1565 Align = 128; // int128_t is 128-bit aligned on all targets.
1566 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001567 case BuiltinType::Half:
1568 Width = Target->getHalfWidth();
1569 Align = Target->getHalfAlign();
1570 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001571 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001572 Width = Target->getFloatWidth();
1573 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001574 break;
1575 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001576 Width = Target->getDoubleWidth();
1577 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001578 break;
1579 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001580 Width = Target->getLongDoubleWidth();
1581 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001582 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001583 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001584 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1585 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001586 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001587 case BuiltinType::ObjCId:
1588 case BuiltinType::ObjCClass:
1589 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001590 Width = Target->getPointerWidth(0);
1591 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001592 break;
Guy Benyei61054192013-02-07 10:55:47 +00001593 case BuiltinType::OCLSampler:
1594 // Samplers are modeled as integers.
1595 Width = Target->getIntWidth();
1596 Align = Target->getIntAlign();
1597 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001598 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001599 case BuiltinType::OCLImage1d:
1600 case BuiltinType::OCLImage1dArray:
1601 case BuiltinType::OCLImage1dBuffer:
1602 case BuiltinType::OCLImage2d:
1603 case BuiltinType::OCLImage2dArray:
1604 case BuiltinType::OCLImage3d:
1605 // Currently these types are pointers to opaque types.
1606 Width = Target->getPointerWidth(0);
1607 Align = Target->getPointerAlign(0);
1608 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001609 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001610 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001611 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001612 Width = Target->getPointerWidth(0);
1613 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001614 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001615 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001616 unsigned AS = getTargetAddressSpace(
1617 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001618 Width = Target->getPointerWidth(AS);
1619 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001620 break;
1621 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001622 case Type::LValueReference:
1623 case Type::RValueReference: {
1624 // alignof and sizeof should never enter this code path here, so we go
1625 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001626 unsigned AS = getTargetAddressSpace(
1627 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001628 Width = Target->getPointerWidth(AS);
1629 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001630 break;
1631 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001632 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001633 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001634 Width = Target->getPointerWidth(AS);
1635 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001636 break;
1637 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001638 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001639 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001640 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001641 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001642 }
Chris Lattner647fb222007-07-18 18:26:58 +00001643 case Type::Complex: {
1644 // Complex types have the same alignment as their elements, but twice the
1645 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001646 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1647 Width = EltInfo.Width * 2;
1648 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001649 break;
1650 }
John McCall8b07ec22010-05-15 11:32:37 +00001651 case Type::ObjCObject:
1652 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001653 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001654 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001655 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001656 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001657 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001658 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001659 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001660 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001661 break;
1662 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001663 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001664 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001665 const TagType *TT = cast<TagType>(T);
1666
1667 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001668 Width = 8;
1669 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001670 break;
1671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
David Majnemer475b25e2015-01-21 10:54:38 +00001673 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1674 const EnumDecl *ED = ET->getDecl();
1675 TypeInfo Info =
1676 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1677 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1678 Info.Align = AttrAlign;
1679 Info.AlignIsRequired = true;
1680 }
1681 return Info;
1682 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001683
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001684 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001685 const RecordDecl *RD = RT->getDecl();
1686 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001687 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001688 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001689 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001690 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001691 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001692
Chris Lattner63d2b362009-10-22 05:17:15 +00001693 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001694 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1695 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001696
Richard Smith30482bc2011-02-20 03:19:35 +00001697 case Type::Auto: {
1698 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001699 assert(!A->getDeducedType().isNull() &&
1700 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001701 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001702 }
1703
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001704 case Type::Paren:
1705 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1706
Douglas Gregoref462e62009-04-30 17:32:17 +00001707 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001708 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001709 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001710 // If the typedef has an aligned attribute on it, it overrides any computed
1711 // alignment we have. This violates the GCC documentation (which says that
1712 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001713 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001714 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001715 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001716 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001717 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001718 AlignIsRequired = Info.AlignIsRequired;
1719 }
David Majnemer34b57492014-07-30 01:30:47 +00001720 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001721 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001722 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001723
Abramo Bagnara6150c882010-05-11 21:36:43 +00001724 case Type::Elaborated:
1725 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001726
John McCall81904512011-01-06 01:58:22 +00001727 case Type::Attributed:
1728 return getTypeInfo(
1729 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1730
Eli Friedman0dfb8892011-10-06 23:00:33 +00001731 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001732 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001733 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1734 Width = Info.Width;
1735 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001736
1737 // If the size of the type doesn't exceed the platform's max
1738 // atomic promotion width, make the size and alignment more
1739 // favorable to atomic operations:
1740 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1741 // Round the size up to a power of 2.
1742 if (!llvm::isPowerOf2_64(Width))
1743 Width = llvm::NextPowerOf2(Width);
1744
1745 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001746 Align = static_cast<unsigned>(Width);
1747 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001748 }
1749
Douglas Gregoref462e62009-04-30 17:32:17 +00001750 }
Mike Stump11289f42009-09-09 15:08:12 +00001751
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001752 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001753 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001754}
1755
Ken Dyckcc56c542011-01-15 18:38:59 +00001756/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1757CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1758 return CharUnits::fromQuantity(BitSize / getCharWidth());
1759}
1760
Ken Dyckb0fcc592011-02-11 01:54:29 +00001761/// toBits - Convert a size in characters to a size in characters.
1762int64_t ASTContext::toBits(CharUnits CharSize) const {
1763 return CharSize.getQuantity() * getCharWidth();
1764}
1765
Ken Dyck8c89d592009-12-22 14:23:30 +00001766/// getTypeSizeInChars - Return the size of the specified type, in characters.
1767/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001768CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001769 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001770}
Jay Foad39c79802011-01-12 09:06:06 +00001771CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001772 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001773}
1774
Ken Dycka6046ab2010-01-26 17:25:18 +00001775/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001776/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001777CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001778 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001779}
Jay Foad39c79802011-01-12 09:06:06 +00001780CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001781 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001782}
1783
Chris Lattnera3402cd2009-01-27 18:08:34 +00001784/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1785/// type for the current target in bits. This can be different than the ABI
1786/// alignment in cases where it is beneficial for performance to overalign
1787/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001788unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001789 TypeInfo TI = getTypeInfo(T);
1790 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001791
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001792 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1793 return ABIAlign; // Never overalign on XCore.
1794
Eli Friedman7ab09572009-05-25 21:27:19 +00001795 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001796 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001797 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001798 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001799 if (const EnumType *ET = T->getAs<EnumType>())
1800 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001801 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001802 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1803 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001804 // Don't increase the alignment if an alignment attribute was specified on a
1805 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001806 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001807 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001808
Chris Lattnera3402cd2009-01-27 18:08:34 +00001809 return ABIAlign;
1810}
1811
Ulrich Weigandfa806422013-05-06 16:23:57 +00001812/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1813/// to a global variable of the specified type.
1814unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1815 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1816}
1817
1818/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1819/// should be given to a global variable of the specified type.
1820CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1821 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1822}
1823
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001824/// DeepCollectObjCIvars -
1825/// This routine first collects all declared, but not synthesized, ivars in
1826/// super class and then collects all ivars, including those synthesized for
1827/// current class. This routine is used for implementation of current class
1828/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001829///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001830void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1831 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001832 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001833 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1834 DeepCollectObjCIvars(SuperClass, false, Ivars);
1835 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001836 for (const auto *I : OI->ivars())
1837 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001838 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001839 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001840 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001841 Iv= Iv->getNextIvar())
1842 Ivars.push_back(Iv);
1843 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001844}
1845
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001846/// CollectInheritedProtocols - Collect all protocols in current class and
1847/// those inherited by it.
1848void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001849 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001850 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001851 // We can use protocol_iterator here instead of
1852 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001853 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001854 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001855 for (auto *P : Proto->protocols()) {
1856 Protocols.insert(P->getCanonicalDecl());
1857 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001858 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001859 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001860
1861 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001862 for (const auto *Cat : OI->visible_categories())
1863 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001864
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001865 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1866 while (SD) {
1867 CollectInheritedProtocols(SD, Protocols);
1868 SD = SD->getSuperClass();
1869 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001870 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001871 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001872 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001873 for (const auto *P : Proto->protocols())
1874 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001875 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001876 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001877 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001878 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001879 for (const auto *P : Proto->protocols())
1880 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001881 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001882 }
1883}
1884
Jay Foad39c79802011-01-12 09:06:06 +00001885unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001886 unsigned count = 0;
1887 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001888 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001889 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001890
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001891 // Count ivar defined in this class's implementation. This
1892 // includes synthesized ivars.
1893 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001894 count += ImplDecl->ivar_size();
1895
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001896 return count;
1897}
1898
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001899bool ASTContext::isSentinelNullExpr(const Expr *E) {
1900 if (!E)
1901 return false;
1902
1903 // nullptr_t is always treated as null.
1904 if (E->getType()->isNullPtrType()) return true;
1905
1906 if (E->getType()->isAnyPointerType() &&
1907 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1908 Expr::NPC_ValueDependentIsNull))
1909 return true;
1910
1911 // Unfortunately, __null has type 'int'.
1912 if (isa<GNUNullExpr>(E)) return true;
1913
1914 return false;
1915}
1916
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001917/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1918ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1919 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1920 I = ObjCImpls.find(D);
1921 if (I != ObjCImpls.end())
1922 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001923 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001924}
1925/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1926ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1927 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1928 I = ObjCImpls.find(D);
1929 if (I != ObjCImpls.end())
1930 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001931 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001932}
1933
1934/// \brief Set the implementation of ObjCInterfaceDecl.
1935void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1936 ObjCImplementationDecl *ImplD) {
1937 assert(IFaceD && ImplD && "Passed null params");
1938 ObjCImpls[IFaceD] = ImplD;
1939}
1940/// \brief Set the implementation of ObjCCategoryDecl.
1941void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1942 ObjCCategoryImplDecl *ImplD) {
1943 assert(CatD && ImplD && "Passed null params");
1944 ObjCImpls[CatD] = ImplD;
1945}
1946
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001947const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1948 const NamedDecl *ND) const {
1949 if (const ObjCInterfaceDecl *ID =
1950 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001951 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001952 if (const ObjCCategoryDecl *CD =
1953 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001954 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001955 if (const ObjCImplDecl *IMD =
1956 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001957 return IMD->getClassInterface();
1958
Craig Topper36250ad2014-05-12 05:36:57 +00001959 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001960}
1961
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001962/// \brief Get the copy initialization expression of VarDecl,or NULL if
1963/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001964Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001965 assert(VD && "Passed null params");
1966 assert(VD->hasAttr<BlocksAttr>() &&
1967 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001968 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001969 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001970 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001971}
1972
1973/// \brief Set the copy inialization expression of a block var decl.
1974void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1975 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001976 assert(VD->hasAttr<BlocksAttr>() &&
1977 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001978 BlockVarCopyInits[VD] = Init;
1979}
1980
John McCallbcd03502009-12-07 02:54:59 +00001981TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001982 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001983 if (!DataSize)
1984 DataSize = TypeLoc::getFullDataSizeForType(T);
1985 else
1986 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001987 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001988
John McCallbcd03502009-12-07 02:54:59 +00001989 TypeSourceInfo *TInfo =
1990 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1991 new (TInfo) TypeSourceInfo(T);
1992 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001993}
1994
John McCallbcd03502009-12-07 02:54:59 +00001995TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001996 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001997 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001998 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001999 return DI;
2000}
2001
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002002const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002003ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002004 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002005}
2006
2007const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002008ASTContext::getASTObjCImplementationLayout(
2009 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002010 return getObjCLayout(D->getClassInterface(), D);
2011}
2012
Chris Lattner983a8bb2007-07-13 22:13:22 +00002013//===----------------------------------------------------------------------===//
2014// Type creation/memoization methods
2015//===----------------------------------------------------------------------===//
2016
Jay Foad39c79802011-01-12 09:06:06 +00002017QualType
John McCall33ddac02011-01-19 10:06:00 +00002018ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2019 unsigned fastQuals = quals.getFastQualifiers();
2020 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002021
2022 // Check if we've already instantiated this type.
2023 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002024 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002025 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002026 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2027 assert(eq->getQualifiers() == quals);
2028 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002029 }
2030
John McCall33ddac02011-01-19 10:06:00 +00002031 // If the base type is not canonical, make the appropriate canonical type.
2032 QualType canon;
2033 if (!baseType->isCanonicalUnqualified()) {
2034 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002035 canonSplit.Quals.addConsistentQualifiers(quals);
2036 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002037
2038 // Re-find the insert position.
2039 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2040 }
2041
2042 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2043 ExtQualNodes.InsertNode(eq, insertPos);
2044 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002045}
2046
Jay Foad39c79802011-01-12 09:06:06 +00002047QualType
2048ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002049 QualType CanT = getCanonicalType(T);
2050 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002051 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002052
John McCall8ccfcb52009-09-24 19:53:00 +00002053 // If we are composing extended qualifiers together, merge together
2054 // into one ExtQuals node.
2055 QualifierCollector Quals;
2056 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002057
John McCall8ccfcb52009-09-24 19:53:00 +00002058 // If this type already has an address space specified, it cannot get
2059 // another one.
2060 assert(!Quals.hasAddressSpace() &&
2061 "Type cannot be in multiple addr spaces!");
2062 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002063
John McCall8ccfcb52009-09-24 19:53:00 +00002064 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002065}
2066
Chris Lattnerd60183d2009-02-18 22:53:11 +00002067QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002068 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002069 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002070 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002071 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCall53fa7142010-12-24 02:08:15 +00002073 if (const PointerType *ptr = T->getAs<PointerType>()) {
2074 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002075 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002076 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2077 return getPointerType(ResultType);
2078 }
2079 }
Mike Stump11289f42009-09-09 15:08:12 +00002080
John McCall8ccfcb52009-09-24 19:53:00 +00002081 // If we are composing extended qualifiers together, merge together
2082 // into one ExtQuals node.
2083 QualifierCollector Quals;
2084 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002085
John McCall8ccfcb52009-09-24 19:53:00 +00002086 // If this type already has an ObjCGC specified, it cannot get
2087 // another one.
2088 assert(!Quals.hasObjCGCAttr() &&
2089 "Type cannot have multiple ObjCGCs!");
2090 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002091
John McCall8ccfcb52009-09-24 19:53:00 +00002092 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002093}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002094
John McCall4f5019e2010-12-19 02:44:49 +00002095const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2096 FunctionType::ExtInfo Info) {
2097 if (T->getExtInfo() == Info)
2098 return T;
2099
2100 QualType Result;
2101 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002102 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002103 } else {
2104 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2105 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2106 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002107 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002108 }
2109
2110 return cast<FunctionType>(Result.getTypePtr());
2111}
2112
Richard Smith2a7d4812013-05-04 07:00:32 +00002113void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2114 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002115 FD = FD->getMostRecentDecl();
2116 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002117 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2118 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002119 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002120 if (FunctionDecl *Next = FD->getPreviousDecl())
2121 FD = Next;
2122 else
2123 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002124 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002125 if (ASTMutationListener *L = getASTMutationListener())
2126 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002127}
2128
Richard Smith0b3a4622014-11-13 20:01:57 +00002129/// Get a function type and produce the equivalent function type with the
2130/// specified exception specification. Type sugar that can be present on a
2131/// declaration of a function with an exception specification is permitted
2132/// and preserved. Other type sugar (for instance, typedefs) is not.
2133static QualType getFunctionTypeWithExceptionSpec(
2134 ASTContext &Context, QualType Orig,
2135 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2136 // Might have some parens.
2137 if (auto *PT = dyn_cast<ParenType>(Orig))
2138 return Context.getParenType(
2139 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2140
2141 // Might have a calling-convention attribute.
2142 if (auto *AT = dyn_cast<AttributedType>(Orig))
2143 return Context.getAttributedType(
2144 AT->getAttrKind(),
2145 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2146 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2147 ESI));
2148
2149 // Anything else must be a function type. Rebuild it with the new exception
2150 // specification.
2151 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2152 return Context.getFunctionType(
2153 Proto->getReturnType(), Proto->getParamTypes(),
2154 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2155}
2156
2157void ASTContext::adjustExceptionSpec(
2158 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2159 bool AsWritten) {
2160 // Update the type.
2161 QualType Updated =
2162 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2163 FD->setType(Updated);
2164
2165 if (!AsWritten)
2166 return;
2167
2168 // Update the type in the type source information too.
2169 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2170 // If the type and the type-as-written differ, we may need to update
2171 // the type-as-written too.
2172 if (TSInfo->getType() != FD->getType())
2173 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2174
2175 // FIXME: When we get proper type location information for exceptions,
2176 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2177 // up the TypeSourceInfo;
2178 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2179 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2180 "TypeLoc size mismatch from updating exception specification");
2181 TSInfo->overrideType(Updated);
2182 }
2183}
2184
Chris Lattnerc6395932007-06-22 20:56:16 +00002185/// getComplexType - Return the uniqued reference to the type for a complex
2186/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002187QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002188 // Unique pointers, to guarantee there is only one pointer of a particular
2189 // structure.
2190 llvm::FoldingSetNodeID ID;
2191 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002192
Craig Topper36250ad2014-05-12 05:36:57 +00002193 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002194 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2195 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattnerc6395932007-06-22 20:56:16 +00002197 // If the pointee type isn't canonical, this won't be a canonical type either,
2198 // so fill in the canonical type field.
2199 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002200 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002201 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattnerc6395932007-06-22 20:56:16 +00002203 // Get the new insert position for the node we care about.
2204 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002205 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002206 }
John McCall90d1c2d2009-09-24 23:30:46 +00002207 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002208 Types.push_back(New);
2209 ComplexTypes.InsertNode(New, InsertPos);
2210 return QualType(New, 0);
2211}
2212
Chris Lattner970e54e2006-11-12 00:37:36 +00002213/// getPointerType - Return the uniqued reference to the type for a pointer to
2214/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002215QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002216 // Unique pointers, to guarantee there is only one pointer of a particular
2217 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002218 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002219 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002220
Craig Topper36250ad2014-05-12 05:36:57 +00002221 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002222 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002223 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002224
Chris Lattner7ccecb92006-11-12 08:50:50 +00002225 // If the pointee type isn't canonical, this won't be a canonical type either,
2226 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002227 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002228 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002229 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002230
Bob Wilsonc8541f22013-03-15 17:12:43 +00002231 // Get the new insert position for the node we care about.
2232 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002233 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002234 }
John McCall90d1c2d2009-09-24 23:30:46 +00002235 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002236 Types.push_back(New);
2237 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002238 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002239}
2240
Reid Kleckner0503a872013-12-05 01:23:43 +00002241QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2242 llvm::FoldingSetNodeID ID;
2243 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002244 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002245 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2246 if (AT)
2247 return QualType(AT, 0);
2248
2249 QualType Canonical = getCanonicalType(New);
2250
2251 // Get the new insert position for the node we care about.
2252 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002253 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002254
2255 AT = new (*this, TypeAlignment)
2256 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2257 Types.push_back(AT);
2258 AdjustedTypes.InsertNode(AT, InsertPos);
2259 return QualType(AT, 0);
2260}
2261
Reid Kleckner8a365022013-06-24 17:51:48 +00002262QualType ASTContext::getDecayedType(QualType T) const {
2263 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2264
Reid Kleckner8a365022013-06-24 17:51:48 +00002265 QualType Decayed;
2266
2267 // C99 6.7.5.3p7:
2268 // A declaration of a parameter as "array of type" shall be
2269 // adjusted to "qualified pointer to type", where the type
2270 // qualifiers (if any) are those specified within the [ and ] of
2271 // the array type derivation.
2272 if (T->isArrayType())
2273 Decayed = getArrayDecayedType(T);
2274
2275 // C99 6.7.5.3p8:
2276 // A declaration of a parameter as "function returning type"
2277 // shall be adjusted to "pointer to function returning type", as
2278 // in 6.3.2.1.
2279 if (T->isFunctionType())
2280 Decayed = getPointerType(T);
2281
Reid Kleckner0503a872013-12-05 01:23:43 +00002282 llvm::FoldingSetNodeID ID;
2283 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002284 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002285 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2286 if (AT)
2287 return QualType(AT, 0);
2288
Reid Kleckner8a365022013-06-24 17:51:48 +00002289 QualType Canonical = getCanonicalType(Decayed);
2290
2291 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002292 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002293 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002294
Reid Kleckner0503a872013-12-05 01:23:43 +00002295 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2296 Types.push_back(AT);
2297 AdjustedTypes.InsertNode(AT, InsertPos);
2298 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002299}
2300
Mike Stump11289f42009-09-09 15:08:12 +00002301/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002302/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002303QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002304 assert(T->isFunctionType() && "block of function types only");
2305 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002306 // structure.
2307 llvm::FoldingSetNodeID ID;
2308 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002309
Craig Topper36250ad2014-05-12 05:36:57 +00002310 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002311 if (BlockPointerType *PT =
2312 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2313 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002314
2315 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002316 // type either so fill in the canonical type field.
2317 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002318 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002319 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002320
Steve Naroffec33ed92008-08-27 16:04:49 +00002321 // Get the new insert position for the node we care about.
2322 BlockPointerType *NewIP =
2323 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002324 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002325 }
John McCall90d1c2d2009-09-24 23:30:46 +00002326 BlockPointerType *New
2327 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002328 Types.push_back(New);
2329 BlockPointerTypes.InsertNode(New, InsertPos);
2330 return QualType(New, 0);
2331}
2332
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002333/// getLValueReferenceType - Return the uniqued reference to the type for an
2334/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002335QualType
2336ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002337 assert(getCanonicalType(T) != OverloadTy &&
2338 "Unresolved overloaded function type");
2339
Bill Wendling3708c182007-05-27 10:15:43 +00002340 // Unique pointers, to guarantee there is only one pointer of a particular
2341 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002342 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002343 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002344
Craig Topper36250ad2014-05-12 05:36:57 +00002345 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002346 if (LValueReferenceType *RT =
2347 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002348 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002349
John McCallfc93cf92009-10-22 22:37:11 +00002350 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2351
Bill Wendling3708c182007-05-27 10:15:43 +00002352 // If the referencee type isn't canonical, this won't be a canonical type
2353 // either, so fill in the canonical type field.
2354 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002355 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2356 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2357 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002358
Bill Wendling3708c182007-05-27 10:15:43 +00002359 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002360 LValueReferenceType *NewIP =
2361 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002362 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002363 }
2364
John McCall90d1c2d2009-09-24 23:30:46 +00002365 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002366 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2367 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002368 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002369 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002370
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002371 return QualType(New, 0);
2372}
2373
2374/// getRValueReferenceType - Return the uniqued reference to the type for an
2375/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002376QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002377 // Unique pointers, to guarantee there is only one pointer of a particular
2378 // structure.
2379 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002380 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002381
Craig Topper36250ad2014-05-12 05:36:57 +00002382 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002383 if (RValueReferenceType *RT =
2384 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2385 return QualType(RT, 0);
2386
John McCallfc93cf92009-10-22 22:37:11 +00002387 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2388
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002389 // If the referencee type isn't canonical, this won't be a canonical type
2390 // either, so fill in the canonical type field.
2391 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002392 if (InnerRef || !T.isCanonical()) {
2393 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2394 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002395
2396 // Get the new insert position for the node we care about.
2397 RValueReferenceType *NewIP =
2398 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002399 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002400 }
2401
John McCall90d1c2d2009-09-24 23:30:46 +00002402 RValueReferenceType *New
2403 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002404 Types.push_back(New);
2405 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002406 return QualType(New, 0);
2407}
2408
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002409/// getMemberPointerType - Return the uniqued reference to the type for a
2410/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002411QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002412 // Unique pointers, to guarantee there is only one pointer of a particular
2413 // structure.
2414 llvm::FoldingSetNodeID ID;
2415 MemberPointerType::Profile(ID, T, Cls);
2416
Craig Topper36250ad2014-05-12 05:36:57 +00002417 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002418 if (MemberPointerType *PT =
2419 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2420 return QualType(PT, 0);
2421
2422 // If the pointee or class type isn't canonical, this won't be a canonical
2423 // type either, so fill in the canonical type field.
2424 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002425 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002426 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2427
2428 // Get the new insert position for the node we care about.
2429 MemberPointerType *NewIP =
2430 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002431 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002432 }
John McCall90d1c2d2009-09-24 23:30:46 +00002433 MemberPointerType *New
2434 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002435 Types.push_back(New);
2436 MemberPointerTypes.InsertNode(New, InsertPos);
2437 return QualType(New, 0);
2438}
2439
Mike Stump11289f42009-09-09 15:08:12 +00002440/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002441/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002442QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002443 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002444 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002445 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002446 assert((EltTy->isDependentType() ||
2447 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002448 "Constant array of VLAs is illegal!");
2449
Chris Lattnere2df3f92009-05-13 04:12:56 +00002450 // Convert the array size into a canonical width matching the pointer size for
2451 // the target.
2452 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002453 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002454 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattner23b7eb62007-06-15 23:05:46 +00002456 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002457 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002458
Craig Topper36250ad2014-05-12 05:36:57 +00002459 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002460 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002461 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002462 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002463
John McCall33ddac02011-01-19 10:06:00 +00002464 // If the element type isn't canonical or has qualifiers, this won't
2465 // be a canonical type either, so fill in the canonical type field.
2466 QualType Canon;
2467 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2468 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002469 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002470 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002471 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002472
Chris Lattner36f8e652007-01-27 08:31:04 +00002473 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002474 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002475 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002476 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002477 }
Mike Stump11289f42009-09-09 15:08:12 +00002478
John McCall90d1c2d2009-09-24 23:30:46 +00002479 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002480 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002481 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002482 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002483 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002484}
2485
John McCall06549462011-01-18 08:40:38 +00002486/// getVariableArrayDecayedType - Turns the given type, which may be
2487/// variably-modified, into the corresponding type with all the known
2488/// sizes replaced with [*].
2489QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2490 // Vastly most common case.
2491 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002492
John McCall06549462011-01-18 08:40:38 +00002493 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002494
John McCall06549462011-01-18 08:40:38 +00002495 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002496 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002497 switch (ty->getTypeClass()) {
2498#define TYPE(Class, Base)
2499#define ABSTRACT_TYPE(Class, Base)
2500#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2501#include "clang/AST/TypeNodes.def"
2502 llvm_unreachable("didn't desugar past all non-canonical types?");
2503
2504 // These types should never be variably-modified.
2505 case Type::Builtin:
2506 case Type::Complex:
2507 case Type::Vector:
2508 case Type::ExtVector:
2509 case Type::DependentSizedExtVector:
2510 case Type::ObjCObject:
2511 case Type::ObjCInterface:
2512 case Type::ObjCObjectPointer:
2513 case Type::Record:
2514 case Type::Enum:
2515 case Type::UnresolvedUsing:
2516 case Type::TypeOfExpr:
2517 case Type::TypeOf:
2518 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002519 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002520 case Type::DependentName:
2521 case Type::InjectedClassName:
2522 case Type::TemplateSpecialization:
2523 case Type::DependentTemplateSpecialization:
2524 case Type::TemplateTypeParm:
2525 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002526 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002527 case Type::PackExpansion:
2528 llvm_unreachable("type should never be variably-modified");
2529
2530 // These types can be variably-modified but should never need to
2531 // further decay.
2532 case Type::FunctionNoProto:
2533 case Type::FunctionProto:
2534 case Type::BlockPointer:
2535 case Type::MemberPointer:
2536 return type;
2537
2538 // These types can be variably-modified. All these modifications
2539 // preserve structure except as noted by comments.
2540 // TODO: if we ever care about optimizing VLAs, there are no-op
2541 // optimizations available here.
2542 case Type::Pointer:
2543 result = getPointerType(getVariableArrayDecayedType(
2544 cast<PointerType>(ty)->getPointeeType()));
2545 break;
2546
2547 case Type::LValueReference: {
2548 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2549 result = getLValueReferenceType(
2550 getVariableArrayDecayedType(lv->getPointeeType()),
2551 lv->isSpelledAsLValue());
2552 break;
2553 }
2554
2555 case Type::RValueReference: {
2556 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2557 result = getRValueReferenceType(
2558 getVariableArrayDecayedType(lv->getPointeeType()));
2559 break;
2560 }
2561
Eli Friedman0dfb8892011-10-06 23:00:33 +00002562 case Type::Atomic: {
2563 const AtomicType *at = cast<AtomicType>(ty);
2564 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2565 break;
2566 }
2567
John McCall06549462011-01-18 08:40:38 +00002568 case Type::ConstantArray: {
2569 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2570 result = getConstantArrayType(
2571 getVariableArrayDecayedType(cat->getElementType()),
2572 cat->getSize(),
2573 cat->getSizeModifier(),
2574 cat->getIndexTypeCVRQualifiers());
2575 break;
2576 }
2577
2578 case Type::DependentSizedArray: {
2579 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2580 result = getDependentSizedArrayType(
2581 getVariableArrayDecayedType(dat->getElementType()),
2582 dat->getSizeExpr(),
2583 dat->getSizeModifier(),
2584 dat->getIndexTypeCVRQualifiers(),
2585 dat->getBracketsRange());
2586 break;
2587 }
2588
2589 // Turn incomplete types into [*] types.
2590 case Type::IncompleteArray: {
2591 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2592 result = getVariableArrayType(
2593 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002594 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002595 ArrayType::Normal,
2596 iat->getIndexTypeCVRQualifiers(),
2597 SourceRange());
2598 break;
2599 }
2600
2601 // Turn VLA types into [*] types.
2602 case Type::VariableArray: {
2603 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2604 result = getVariableArrayType(
2605 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002606 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002607 ArrayType::Star,
2608 vat->getIndexTypeCVRQualifiers(),
2609 vat->getBracketsRange());
2610 break;
2611 }
2612 }
2613
2614 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002615 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002616}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002617
Steve Naroffcadebd02007-08-30 18:14:25 +00002618/// getVariableArrayType - Returns a non-unique reference to the type for a
2619/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002620QualType ASTContext::getVariableArrayType(QualType EltTy,
2621 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002622 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002623 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002624 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002625 // Since we don't unique expressions, it isn't possible to unique VLA's
2626 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002627 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002628
John McCall33ddac02011-01-19 10:06:00 +00002629 // Be sure to pull qualifiers off the element type.
2630 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2631 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002632 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002633 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002634 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002635 }
2636
John McCall90d1c2d2009-09-24 23:30:46 +00002637 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002638 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002639
2640 VariableArrayTypes.push_back(New);
2641 Types.push_back(New);
2642 return QualType(New, 0);
2643}
2644
Douglas Gregor4619e432008-12-05 23:32:09 +00002645/// getDependentSizedArrayType - Returns a non-unique reference to
2646/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002647/// type.
John McCall33ddac02011-01-19 10:06:00 +00002648QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2649 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002650 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002651 unsigned elementTypeQuals,
2652 SourceRange brackets) const {
2653 assert((!numElements || numElements->isTypeDependent() ||
2654 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002655 "Size must be type- or value-dependent!");
2656
John McCall33ddac02011-01-19 10:06:00 +00002657 // Dependently-sized array types that do not have a specified number
2658 // of elements will have their sizes deduced from a dependent
2659 // initializer. We do no canonicalization here at all, which is okay
2660 // because they can't be used in most locations.
2661 if (!numElements) {
2662 DependentSizedArrayType *newType
2663 = new (*this, TypeAlignment)
2664 DependentSizedArrayType(*this, elementType, QualType(),
2665 numElements, ASM, elementTypeQuals,
2666 brackets);
2667 Types.push_back(newType);
2668 return QualType(newType, 0);
2669 }
2670
2671 // Otherwise, we actually build a new type every time, but we
2672 // also build a canonical type.
2673
2674 SplitQualType canonElementType = getCanonicalType(elementType).split();
2675
Craig Topper36250ad2014-05-12 05:36:57 +00002676 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002677 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002678 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002679 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002680 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002681
John McCall33ddac02011-01-19 10:06:00 +00002682 // Look for an existing type with these properties.
2683 DependentSizedArrayType *canonTy =
2684 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002685
John McCall33ddac02011-01-19 10:06:00 +00002686 // If we don't have one, build one.
2687 if (!canonTy) {
2688 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002689 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002690 QualType(), numElements, ASM, elementTypeQuals,
2691 brackets);
2692 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2693 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002694 }
2695
John McCall33ddac02011-01-19 10:06:00 +00002696 // Apply qualifiers from the element type to the array.
2697 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002698 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002699
John McCall33ddac02011-01-19 10:06:00 +00002700 // If we didn't need extra canonicalization for the element type,
2701 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002702 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002703 return canon;
2704
2705 // Otherwise, we need to build a type which follows the spelling
2706 // of the element type.
2707 DependentSizedArrayType *sugaredType
2708 = new (*this, TypeAlignment)
2709 DependentSizedArrayType(*this, elementType, canon, numElements,
2710 ASM, elementTypeQuals, brackets);
2711 Types.push_back(sugaredType);
2712 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002713}
2714
John McCall33ddac02011-01-19 10:06:00 +00002715QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002716 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002717 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002718 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002719 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002720
Craig Topper36250ad2014-05-12 05:36:57 +00002721 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002722 if (IncompleteArrayType *iat =
2723 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2724 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002725
2726 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002727 // either, so fill in the canonical type field. We also have to pull
2728 // qualifiers off the element type.
2729 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002730
John McCall33ddac02011-01-19 10:06:00 +00002731 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2732 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002733 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002734 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002735 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002736
2737 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002738 IncompleteArrayType *existing =
2739 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2740 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002741 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002742
John McCall33ddac02011-01-19 10:06:00 +00002743 IncompleteArrayType *newType = new (*this, TypeAlignment)
2744 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002745
John McCall33ddac02011-01-19 10:06:00 +00002746 IncompleteArrayTypes.InsertNode(newType, insertPos);
2747 Types.push_back(newType);
2748 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002749}
2750
Steve Naroff91fcddb2007-07-18 18:00:27 +00002751/// getVectorType - Return the unique reference to a vector type of
2752/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002753QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002754 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002755 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002756
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002757 // Check if we've already instantiated a vector of this type.
2758 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002759 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002760
Craig Topper36250ad2014-05-12 05:36:57 +00002761 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002762 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2763 return QualType(VTP, 0);
2764
2765 // If the element type isn't canonical, this won't be a canonical type either,
2766 // so fill in the canonical type field.
2767 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002768 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002769 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002770
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002771 // Get the new insert position for the node we care about.
2772 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002773 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002774 }
John McCall90d1c2d2009-09-24 23:30:46 +00002775 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002776 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002777 VectorTypes.InsertNode(New, InsertPos);
2778 Types.push_back(New);
2779 return QualType(New, 0);
2780}
2781
Nate Begemance4d7fc2008-04-18 23:10:10 +00002782/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002783/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002784QualType
2785ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002786 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002787
Steve Naroff91fcddb2007-07-18 18:00:27 +00002788 // Check if we've already instantiated a vector of this type.
2789 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002790 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002791 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002792 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002793 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2794 return QualType(VTP, 0);
2795
2796 // If the element type isn't canonical, this won't be a canonical type either,
2797 // so fill in the canonical type field.
2798 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002799 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002800 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002801
Steve Naroff91fcddb2007-07-18 18:00:27 +00002802 // Get the new insert position for the node we care about.
2803 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002804 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002805 }
John McCall90d1c2d2009-09-24 23:30:46 +00002806 ExtVectorType *New = new (*this, TypeAlignment)
2807 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002808 VectorTypes.InsertNode(New, InsertPos);
2809 Types.push_back(New);
2810 return QualType(New, 0);
2811}
2812
Jay Foad39c79802011-01-12 09:06:06 +00002813QualType
2814ASTContext::getDependentSizedExtVectorType(QualType vecType,
2815 Expr *SizeExpr,
2816 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002817 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002818 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002819 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002820
Craig Topper36250ad2014-05-12 05:36:57 +00002821 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002822 DependentSizedExtVectorType *Canon
2823 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2824 DependentSizedExtVectorType *New;
2825 if (Canon) {
2826 // We already have a canonical version of this array type; use it as
2827 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002828 New = new (*this, TypeAlignment)
2829 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2830 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002831 } else {
2832 QualType CanonVecTy = getCanonicalType(vecType);
2833 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002834 New = new (*this, TypeAlignment)
2835 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2836 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002837
2838 DependentSizedExtVectorType *CanonCheck
2839 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2840 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2841 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002842 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2843 } else {
2844 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2845 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002846 New = new (*this, TypeAlignment)
2847 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002848 }
2849 }
Mike Stump11289f42009-09-09 15:08:12 +00002850
Douglas Gregor758a8692009-06-17 21:51:59 +00002851 Types.push_back(New);
2852 return QualType(New, 0);
2853}
2854
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002855/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002856///
Jay Foad39c79802011-01-12 09:06:06 +00002857QualType
2858ASTContext::getFunctionNoProtoType(QualType ResultTy,
2859 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002860 const CallingConv CallConv = Info.getCC();
2861
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002862 // Unique functions, to guarantee there is only one function of a particular
2863 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002864 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002865 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Craig Topper36250ad2014-05-12 05:36:57 +00002867 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002868 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002869 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002870 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002871
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002872 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002873 if (!ResultTy.isCanonical()) {
2874 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002875
Chris Lattner47955de2007-01-27 08:37:20 +00002876 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002877 FunctionNoProtoType *NewIP =
2878 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002879 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002880 }
Mike Stump11289f42009-09-09 15:08:12 +00002881
Roman Divacky65b88cd2011-03-01 17:40:53 +00002882 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002883 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002884 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002885 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002886 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002887 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002888}
2889
Douglas Gregorcd780372013-01-17 23:36:45 +00002890/// \brief Determine whether \p T is canonical as the result type of a function.
2891static bool isCanonicalResultType(QualType T) {
2892 return T.isCanonical() &&
2893 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2894 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2895}
2896
Jay Foad39c79802011-01-12 09:06:06 +00002897QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002898ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002899 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002900 size_t NumArgs = ArgArray.size();
2901
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002902 // Unique functions, to guarantee there is only one function of a particular
2903 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002904 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002905 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2906 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002907
Craig Topper36250ad2014-05-12 05:36:57 +00002908 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002909 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002910 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002911 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002912
2913 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002914 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002915 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002916 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002917 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002918 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002919 isCanonical = false;
2920
2921 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002922 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002923 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002924 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002925 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002926 CanonicalArgs.reserve(NumArgs);
2927 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002928 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002929
John McCalldb40c7f2010-12-14 08:05:40 +00002930 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002931 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002932 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002933
Douglas Gregorcd780372013-01-17 23:36:45 +00002934 // Result types do not have ARC lifetime qualifiers.
2935 QualType CanResultTy = getCanonicalType(ResultTy);
2936 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2937 Qualifiers Qs = CanResultTy.getQualifiers();
2938 Qs.removeObjCLifetime();
2939 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2940 }
2941
Jordan Rose5c382722013-03-08 21:51:21 +00002942 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002943
Chris Lattnerfd4de792007-01-27 01:15:32 +00002944 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002945 FunctionProtoType *NewIP =
2946 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002947 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002948 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002949
John McCall31168b02011-06-15 23:02:42 +00002950 // FunctionProtoType objects are allocated with extra bytes after
2951 // them for three variable size arrays at the end:
2952 // - parameter types
2953 // - exception types
2954 // - consumed-arguments flags
2955 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002956 // expression, or information used to resolve the exception
2957 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002958 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002959 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002960 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2961 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2962 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002963 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002964 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002965 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002966 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002967 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002968 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002969 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002970 Size += NumArgs * sizeof(bool);
2971
John McCalldb40c7f2010-12-14 08:05:40 +00002972 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002973 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002974 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002975 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002976 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002977 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002978}
Chris Lattneref51c202006-11-10 07:17:23 +00002979
John McCalle78aac42010-03-10 03:28:59 +00002980#ifndef NDEBUG
2981static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2982 if (!isa<CXXRecordDecl>(D)) return false;
2983 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2984 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2985 return true;
2986 if (RD->getDescribedClassTemplate() &&
2987 !isa<ClassTemplateSpecializationDecl>(RD))
2988 return true;
2989 return false;
2990}
2991#endif
2992
2993/// getInjectedClassNameType - Return the unique reference to the
2994/// injected class name type for the specified templated declaration.
2995QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002996 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002997 assert(NeedsInjectedClassNameType(Decl));
2998 if (Decl->TypeForDecl) {
2999 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003000 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003001 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3002 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3003 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3004 } else {
John McCall424cec92011-01-19 06:33:43 +00003005 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003006 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003007 Decl->TypeForDecl = newType;
3008 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003009 }
3010 return QualType(Decl->TypeForDecl, 0);
3011}
3012
Douglas Gregor83a586e2008-04-13 21:07:44 +00003013/// getTypeDeclType - Return the unique reference to the type for the
3014/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003015QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003016 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003017 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003018
Richard Smithdda56e42011-04-15 14:24:37 +00003019 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003020 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003021
John McCall96f0b5f2010-03-10 06:48:02 +00003022 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3023 "Template type parameter types are always available.");
3024
John McCall81e38502010-02-16 03:57:14 +00003025 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003026 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003027 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003028 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003029 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003030 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003031 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003032 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003033 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003034 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3035 Decl->TypeForDecl = newType;
3036 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003037 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003038 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003039
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003040 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003041}
3042
Chris Lattner32d920b2007-01-26 02:01:53 +00003043/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003044/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003045QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003046ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3047 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003048 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003049
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003050 if (Canonical.isNull())
3051 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003052 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003053 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003054 Decl->TypeForDecl = newType;
3055 Types.push_back(newType);
3056 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003057}
3058
Jay Foad39c79802011-01-12 09:06:06 +00003059QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003060 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3061
Douglas Gregorec9fd132012-01-14 16:38:05 +00003062 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003063 if (PrevDecl->TypeForDecl)
3064 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3065
John McCall424cec92011-01-19 06:33:43 +00003066 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3067 Decl->TypeForDecl = newType;
3068 Types.push_back(newType);
3069 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003070}
3071
Jay Foad39c79802011-01-12 09:06:06 +00003072QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003073 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3074
Douglas Gregorec9fd132012-01-14 16:38:05 +00003075 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003076 if (PrevDecl->TypeForDecl)
3077 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3078
John McCall424cec92011-01-19 06:33:43 +00003079 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3080 Decl->TypeForDecl = newType;
3081 Types.push_back(newType);
3082 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003083}
3084
John McCall81904512011-01-06 01:58:22 +00003085QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3086 QualType modifiedType,
3087 QualType equivalentType) {
3088 llvm::FoldingSetNodeID id;
3089 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3090
Craig Topper36250ad2014-05-12 05:36:57 +00003091 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003092 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3093 if (type) return QualType(type, 0);
3094
3095 QualType canon = getCanonicalType(equivalentType);
3096 type = new (*this, TypeAlignment)
3097 AttributedType(canon, attrKind, modifiedType, equivalentType);
3098
3099 Types.push_back(type);
3100 AttributedTypes.InsertNode(type, insertPos);
3101
3102 return QualType(type, 0);
3103}
3104
3105
John McCallcebee162009-10-18 09:09:24 +00003106/// \brief Retrieve a substitution-result type.
3107QualType
3108ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003109 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003110 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003111 && "replacement types must always be canonical");
3112
3113 llvm::FoldingSetNodeID ID;
3114 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003115 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003116 SubstTemplateTypeParmType *SubstParm
3117 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3118
3119 if (!SubstParm) {
3120 SubstParm = new (*this, TypeAlignment)
3121 SubstTemplateTypeParmType(Parm, Replacement);
3122 Types.push_back(SubstParm);
3123 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3124 }
3125
3126 return QualType(SubstParm, 0);
3127}
3128
Douglas Gregorada4b792011-01-14 02:55:32 +00003129/// \brief Retrieve a
3130QualType ASTContext::getSubstTemplateTypeParmPackType(
3131 const TemplateTypeParmType *Parm,
3132 const TemplateArgument &ArgPack) {
3133#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003134 for (const auto &P : ArgPack.pack_elements()) {
3135 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3136 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003137 }
3138#endif
3139
3140 llvm::FoldingSetNodeID ID;
3141 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003142 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003143 if (SubstTemplateTypeParmPackType *SubstParm
3144 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3145 return QualType(SubstParm, 0);
3146
3147 QualType Canon;
3148 if (!Parm->isCanonicalUnqualified()) {
3149 Canon = getCanonicalType(QualType(Parm, 0));
3150 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3151 ArgPack);
3152 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3153 }
3154
3155 SubstTemplateTypeParmPackType *SubstParm
3156 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3157 ArgPack);
3158 Types.push_back(SubstParm);
3159 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3160 return QualType(SubstParm, 0);
3161}
3162
Douglas Gregoreff93e02009-02-05 23:33:38 +00003163/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003164/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003165/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003166QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003167 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003168 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003169 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003170 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003171 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003172 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003173 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3174
3175 if (TypeParm)
3176 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003177
Chandler Carruth08836322011-05-01 00:51:33 +00003178 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003179 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003180 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003181
3182 TemplateTypeParmType *TypeCheck
3183 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3184 assert(!TypeCheck && "Template type parameter canonical type broken");
3185 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003186 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003187 TypeParm = new (*this, TypeAlignment)
3188 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003189
3190 Types.push_back(TypeParm);
3191 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3192
3193 return QualType(TypeParm, 0);
3194}
3195
John McCalle78aac42010-03-10 03:28:59 +00003196TypeSourceInfo *
3197ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3198 SourceLocation NameLoc,
3199 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003200 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003201 assert(!Name.getAsDependentTemplateName() &&
3202 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003203 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003204
3205 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003206 TemplateSpecializationTypeLoc TL =
3207 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003208 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003209 TL.setTemplateNameLoc(NameLoc);
3210 TL.setLAngleLoc(Args.getLAngleLoc());
3211 TL.setRAngleLoc(Args.getRAngleLoc());
3212 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3213 TL.setArgLocInfo(i, Args[i].getLocInfo());
3214 return DI;
3215}
3216
Mike Stump11289f42009-09-09 15:08:12 +00003217QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003218ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003219 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003220 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003221 assert(!Template.getAsDependentTemplateName() &&
3222 "No dependent template names here!");
3223
John McCall6b51f282009-11-23 01:53:49 +00003224 unsigned NumArgs = Args.size();
3225
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003226 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003227 ArgVec.reserve(NumArgs);
3228 for (unsigned i = 0; i != NumArgs; ++i)
3229 ArgVec.push_back(Args[i].getArgument());
3230
John McCall2408e322010-04-27 00:57:59 +00003231 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003232 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003233}
3234
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003235#ifndef NDEBUG
3236static bool hasAnyPackExpansions(const TemplateArgument *Args,
3237 unsigned NumArgs) {
3238 for (unsigned I = 0; I != NumArgs; ++I)
3239 if (Args[I].isPackExpansion())
3240 return true;
3241
3242 return true;
3243}
3244#endif
3245
John McCall0ad16662009-10-29 08:12:44 +00003246QualType
3247ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003248 const TemplateArgument *Args,
3249 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003250 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003251 assert(!Template.getAsDependentTemplateName() &&
3252 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003253 // Look through qualified template names.
3254 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3255 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003256
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003257 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003258 Template.getAsTemplateDecl() &&
3259 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003260 QualType CanonType;
3261 if (!Underlying.isNull())
3262 CanonType = getCanonicalType(Underlying);
3263 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003264 // We can get here with an alias template when the specialization contains
3265 // a pack expansion that does not match up with a parameter pack.
3266 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3267 "Caller must compute aliased type");
3268 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003269 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3270 NumArgs);
3271 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003272
Douglas Gregora8e02e72009-07-28 23:00:59 +00003273 // Allocate the (non-canonical) template specialization type, but don't
3274 // try to unique it: these types typically have location information that
3275 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003276 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3277 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003278 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003279 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003280 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003281 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3282 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003283
Douglas Gregor8bf42052009-02-09 18:46:07 +00003284 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003285 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003286}
3287
Mike Stump11289f42009-09-09 15:08:12 +00003288QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003289ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3290 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003291 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003292 assert(!Template.getAsDependentTemplateName() &&
3293 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003294
Douglas Gregore29139c2011-03-03 17:04:51 +00003295 // Look through qualified template names.
3296 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3297 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003298
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003299 // Build the canonical template specialization type.
3300 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003301 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003302 CanonArgs.reserve(NumArgs);
3303 for (unsigned I = 0; I != NumArgs; ++I)
3304 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3305
3306 // Determine whether this canonical template specialization type already
3307 // exists.
3308 llvm::FoldingSetNodeID ID;
3309 TemplateSpecializationType::Profile(ID, CanonTemplate,
3310 CanonArgs.data(), NumArgs, *this);
3311
Craig Topper36250ad2014-05-12 05:36:57 +00003312 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003313 TemplateSpecializationType *Spec
3314 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3315
3316 if (!Spec) {
3317 // Allocate a new canonical template specialization type.
3318 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3319 sizeof(TemplateArgument) * NumArgs),
3320 TypeAlignment);
3321 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3322 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003323 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003324 Types.push_back(Spec);
3325 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3326 }
3327
3328 assert(Spec->isDependentType() &&
3329 "Non-dependent template-id type must have a canonical type");
3330 return QualType(Spec, 0);
3331}
3332
3333QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003334ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3335 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003336 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003337 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003338 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003339
Craig Topper36250ad2014-05-12 05:36:57 +00003340 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003341 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003342 if (T)
3343 return QualType(T, 0);
3344
Douglas Gregorc42075a2010-02-04 18:10:26 +00003345 QualType Canon = NamedType;
3346 if (!Canon.isCanonical()) {
3347 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003348 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3349 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003350 (void)CheckT;
3351 }
3352
Abramo Bagnara6150c882010-05-11 21:36:43 +00003353 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003354 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003355 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003356 return QualType(T, 0);
3357}
3358
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003359QualType
Jay Foad39c79802011-01-12 09:06:06 +00003360ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003361 llvm::FoldingSetNodeID ID;
3362 ParenType::Profile(ID, InnerType);
3363
Craig Topper36250ad2014-05-12 05:36:57 +00003364 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003365 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3366 if (T)
3367 return QualType(T, 0);
3368
3369 QualType Canon = InnerType;
3370 if (!Canon.isCanonical()) {
3371 Canon = getCanonicalType(InnerType);
3372 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3373 assert(!CheckT && "Paren canonical type broken");
3374 (void)CheckT;
3375 }
3376
3377 T = new (*this) ParenType(InnerType, Canon);
3378 Types.push_back(T);
3379 ParenTypes.InsertNode(T, InsertPos);
3380 return QualType(T, 0);
3381}
3382
Douglas Gregor02085352010-03-31 20:19:30 +00003383QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3384 NestedNameSpecifier *NNS,
3385 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003386 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003387 if (Canon.isNull()) {
3388 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003389 ElaboratedTypeKeyword CanonKeyword = Keyword;
3390 if (Keyword == ETK_None)
3391 CanonKeyword = ETK_Typename;
3392
3393 if (CanonNNS != NNS || CanonKeyword != Keyword)
3394 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003395 }
3396
3397 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003398 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003399
Craig Topper36250ad2014-05-12 05:36:57 +00003400 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003401 DependentNameType *T
3402 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003403 if (T)
3404 return QualType(T, 0);
3405
Douglas Gregor02085352010-03-31 20:19:30 +00003406 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003407 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003408 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003409 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003410}
3411
Mike Stump11289f42009-09-09 15:08:12 +00003412QualType
John McCallc392f372010-06-11 00:33:02 +00003413ASTContext::getDependentTemplateSpecializationType(
3414 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003415 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003416 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003417 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003418 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003419 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003420 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3421 ArgCopy.push_back(Args[I].getArgument());
3422 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3423 ArgCopy.size(),
3424 ArgCopy.data());
3425}
3426
3427QualType
3428ASTContext::getDependentTemplateSpecializationType(
3429 ElaboratedTypeKeyword Keyword,
3430 NestedNameSpecifier *NNS,
3431 const IdentifierInfo *Name,
3432 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003433 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003434 assert((!NNS || NNS->isDependent()) &&
3435 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003436
Douglas Gregorc42075a2010-02-04 18:10:26 +00003437 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003438 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3439 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003440
Craig Topper36250ad2014-05-12 05:36:57 +00003441 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003442 DependentTemplateSpecializationType *T
3443 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003444 if (T)
3445 return QualType(T, 0);
3446
John McCallc392f372010-06-11 00:33:02 +00003447 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003448
John McCallc392f372010-06-11 00:33:02 +00003449 ElaboratedTypeKeyword CanonKeyword = Keyword;
3450 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3451
3452 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003453 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003454 for (unsigned I = 0; I != NumArgs; ++I) {
3455 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3456 if (!CanonArgs[I].structurallyEquals(Args[I]))
3457 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003458 }
3459
John McCallc392f372010-06-11 00:33:02 +00003460 QualType Canon;
3461 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3462 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3463 Name, NumArgs,
3464 CanonArgs.data());
3465
3466 // Find the insert position again.
3467 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3468 }
3469
3470 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3471 sizeof(TemplateArgument) * NumArgs),
3472 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003473 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003474 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003475 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003476 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003477 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003478}
3479
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003480QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003481 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003482 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003483 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003484
3485 assert(Pattern->containsUnexpandedParameterPack() &&
3486 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003487 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003488 PackExpansionType *T
3489 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3490 if (T)
3491 return QualType(T, 0);
3492
3493 QualType Canon;
3494 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003495 Canon = getCanonicalType(Pattern);
3496 // The canonical type might not contain an unexpanded parameter pack, if it
3497 // contains an alias template specialization which ignores one of its
3498 // parameters.
3499 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003500 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003501
Richard Smith68eea502012-07-16 00:20:35 +00003502 // Find the insert position again, in case we inserted an element into
3503 // PackExpansionTypes and invalidated our insert position.
3504 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3505 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003506 }
3507
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003508 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003509 Types.push_back(T);
3510 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003511 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003512}
3513
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003514/// CmpProtocolNames - Comparison predicate for sorting protocols
3515/// alphabetically.
3516static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3517 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003518 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003519}
3520
John McCall8b07ec22010-05-15 11:32:37 +00003521static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003522 unsigned NumProtocols) {
3523 if (NumProtocols == 0) return true;
3524
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003525 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3526 return false;
3527
John McCallfc93cf92009-10-22 22:37:11 +00003528 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003529 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3530 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003531 return false;
3532 return true;
3533}
3534
3535static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003536 unsigned &NumProtocols) {
3537 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003538
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003539 // Sort protocols, keyed by name.
3540 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3541
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003542 // Canonicalize.
3543 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3544 Protocols[I] = Protocols[I]->getCanonicalDecl();
3545
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003546 // Remove duplicates.
3547 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3548 NumProtocols = ProtocolsEnd-Protocols;
3549}
3550
John McCall8b07ec22010-05-15 11:32:37 +00003551QualType ASTContext::getObjCObjectType(QualType BaseType,
3552 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003553 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003554 // If the base type is an interface and there aren't any protocols
3555 // to add, then the interface type will do just fine.
3556 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3557 return BaseType;
3558
3559 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003560 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003561 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003562 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003563 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3564 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003565
John McCall8b07ec22010-05-15 11:32:37 +00003566 // Build the canonical type, which has the canonical base type and
3567 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003568 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003569 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3570 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3571 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003572 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003573 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003574 unsigned UniqueCount = NumProtocols;
3575
John McCallfc93cf92009-10-22 22:37:11 +00003576 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003577 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3578 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003579 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003580 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3581 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003582 }
3583
3584 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003585 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3586 }
3587
3588 unsigned Size = sizeof(ObjCObjectTypeImpl);
3589 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3590 void *Mem = Allocate(Size, TypeAlignment);
3591 ObjCObjectTypeImpl *T =
3592 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3593
3594 Types.push_back(T);
3595 ObjCObjectTypes.InsertNode(T, InsertPos);
3596 return QualType(T, 0);
3597}
3598
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003599/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3600/// protocol list adopt all protocols in QT's qualified-id protocol
3601/// list.
3602bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3603 ObjCInterfaceDecl *IC) {
3604 if (!QT->isObjCQualifiedIdType())
3605 return false;
3606
3607 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3608 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003609 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003610 if (!IC->ClassImplementsProtocol(Proto, false))
3611 return false;
3612 }
3613 return true;
3614 }
3615 return false;
3616}
3617
3618/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3619/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3620/// of protocols.
3621bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3622 ObjCInterfaceDecl *IDecl) {
3623 if (!QT->isObjCQualifiedIdType())
3624 return false;
3625 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3626 if (!OPT)
3627 return false;
3628 if (!IDecl->hasDefinition())
3629 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003630 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3631 CollectInheritedProtocols(IDecl, InheritedProtocols);
3632 if (InheritedProtocols.empty())
3633 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003634 // Check that if every protocol in list of id<plist> conforms to a protcol
3635 // of IDecl's, then bridge casting is ok.
3636 bool Conforms = false;
3637 for (auto *Proto : OPT->quals()) {
3638 Conforms = false;
3639 for (auto *PI : InheritedProtocols) {
3640 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3641 Conforms = true;
3642 break;
3643 }
3644 }
3645 if (!Conforms)
3646 break;
3647 }
3648 if (Conforms)
3649 return true;
3650
Aaron Ballman83731462014-03-17 16:14:00 +00003651 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003652 // If both the right and left sides have qualifiers.
3653 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003654 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003655 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003656 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003657 break;
3658 }
3659 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003660 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003661 }
3662 return true;
3663}
3664
John McCall8b07ec22010-05-15 11:32:37 +00003665/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3666/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003667QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003668 llvm::FoldingSetNodeID ID;
3669 ObjCObjectPointerType::Profile(ID, ObjectT);
3670
Craig Topper36250ad2014-05-12 05:36:57 +00003671 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003672 if (ObjCObjectPointerType *QT =
3673 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3674 return QualType(QT, 0);
3675
3676 // Find the canonical object type.
3677 QualType Canonical;
3678 if (!ObjectT.isCanonical()) {
3679 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3680
3681 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003682 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3683 }
3684
Douglas Gregorf85bee62010-02-08 22:59:26 +00003685 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003686 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3687 ObjCObjectPointerType *QType =
3688 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003689
Steve Narofffb4330f2009-06-17 22:40:22 +00003690 Types.push_back(QType);
3691 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003692 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003693}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003694
Douglas Gregor1c283312010-08-11 12:19:30 +00003695/// getObjCInterfaceType - Return the unique reference to the type for the
3696/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003697QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3698 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003699 if (Decl->TypeForDecl)
3700 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003702 if (PrevDecl) {
3703 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3704 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3705 return QualType(PrevDecl->TypeForDecl, 0);
3706 }
3707
Douglas Gregor7671e532011-12-16 16:34:57 +00003708 // Prefer the definition, if there is one.
3709 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3710 Decl = Def;
3711
Douglas Gregor1c283312010-08-11 12:19:30 +00003712 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3713 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3714 Decl->TypeForDecl = T;
3715 Types.push_back(T);
3716 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003717}
3718
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003719/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3720/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003721/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003722/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003723/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003724QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003725 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003726 if (tofExpr->isTypeDependent()) {
3727 llvm::FoldingSetNodeID ID;
3728 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003729
Craig Topper36250ad2014-05-12 05:36:57 +00003730 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003731 DependentTypeOfExprType *Canon
3732 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3733 if (Canon) {
3734 // We already have a "canonical" version of an identical, dependent
3735 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003736 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003737 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003738 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003739 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003740 Canon
3741 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003742 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3743 toe = Canon;
3744 }
3745 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003746 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003747 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003748 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003749 Types.push_back(toe);
3750 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003751}
3752
Steve Naroffa773cd52007-08-01 18:02:17 +00003753/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003754/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003755/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003756/// an issue. This doesn't affect the type checker, since it operates
3757/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003758QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003759 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003760 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003761 Types.push_back(tot);
3762 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003763}
3764
Anders Carlssonad6bd352009-06-24 21:24:56 +00003765
Richard Smith8eb1d322014-06-05 20:13:13 +00003766/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3767/// nodes. This would never be helpful, since each such type has its own
3768/// expression, and would not give a significant memory saving, since there
3769/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003770QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003771 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003772
3773 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003774 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003775 // unique dependent type. Two such decltype-specifiers refer to the same
3776 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003777 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003778 llvm::FoldingSetNodeID ID;
3779 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003780
Craig Topper36250ad2014-05-12 05:36:57 +00003781 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003782 DependentDecltypeType *Canon
3783 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003784 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003785 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003786 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003787 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003788 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003789 dt = new (*this, TypeAlignment)
3790 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003791 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003792 dt = new (*this, TypeAlignment)
3793 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003794 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003795 Types.push_back(dt);
3796 return QualType(dt, 0);
3797}
3798
Alexis Hunte852b102011-05-24 22:41:36 +00003799/// getUnaryTransformationType - We don't unique these, since the memory
3800/// savings are minimal and these are rare.
3801QualType ASTContext::getUnaryTransformType(QualType BaseType,
3802 QualType UnderlyingType,
3803 UnaryTransformType::UTTKind Kind)
3804 const {
3805 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003806 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3807 Kind,
3808 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003809 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003810 Types.push_back(Ty);
3811 return QualType(Ty, 0);
3812}
3813
Richard Smith2a7d4812013-05-04 07:00:32 +00003814/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3815/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3816/// canonical deduced-but-dependent 'auto' type.
3817QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003818 bool IsDependent) const {
3819 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003820 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003821
Richard Smith2a7d4812013-05-04 07:00:32 +00003822 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003823 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003824 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003825 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003826 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3827 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003828
Richard Smith74aeef52013-04-26 16:15:35 +00003829 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003830 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003831 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003832 Types.push_back(AT);
3833 if (InsertPos)
3834 AutoTypes.InsertNode(AT, InsertPos);
3835 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003836}
3837
Eli Friedman0dfb8892011-10-06 23:00:33 +00003838/// getAtomicType - Return the uniqued reference to the atomic type for
3839/// the given value type.
3840QualType ASTContext::getAtomicType(QualType T) const {
3841 // Unique pointers, to guarantee there is only one pointer of a particular
3842 // structure.
3843 llvm::FoldingSetNodeID ID;
3844 AtomicType::Profile(ID, T);
3845
Craig Topper36250ad2014-05-12 05:36:57 +00003846 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003847 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3848 return QualType(AT, 0);
3849
3850 // If the atomic value type isn't canonical, this won't be a canonical type
3851 // either, so fill in the canonical type field.
3852 QualType Canonical;
3853 if (!T.isCanonical()) {
3854 Canonical = getAtomicType(getCanonicalType(T));
3855
3856 // Get the new insert position for the node we care about.
3857 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003858 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003859 }
3860 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3861 Types.push_back(New);
3862 AtomicTypes.InsertNode(New, InsertPos);
3863 return QualType(New, 0);
3864}
3865
Richard Smith02e85f32011-04-14 22:09:26 +00003866/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3867QualType ASTContext::getAutoDeductType() const {
3868 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003869 AutoDeductTy = QualType(
3870 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003871 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003872 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003873 return AutoDeductTy;
3874}
3875
3876/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3877QualType ASTContext::getAutoRRefDeductType() const {
3878 if (AutoRRefDeductTy.isNull())
3879 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3880 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3881 return AutoRRefDeductTy;
3882}
3883
Chris Lattnerfb072462007-01-23 05:45:31 +00003884/// getTagDeclType - Return the unique reference to the type for the
3885/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003886QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003887 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003888 // FIXME: What is the design on getTagDeclType when it requires casting
3889 // away const? mutable?
3890 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003891}
3892
Mike Stump11289f42009-09-09 15:08:12 +00003893/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3894/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3895/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003896CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003897 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003898}
Chris Lattnerfb072462007-01-23 05:45:31 +00003899
Hans Wennborg27541db2011-10-27 08:29:09 +00003900/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3901CanQualType ASTContext::getIntMaxType() const {
3902 return getFromTargetType(Target->getIntMaxType());
3903}
3904
3905/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3906CanQualType ASTContext::getUIntMaxType() const {
3907 return getFromTargetType(Target->getUIntMaxType());
3908}
3909
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003910/// getSignedWCharType - Return the type of "signed wchar_t".
3911/// Used when in C++, as a GCC extension.
3912QualType ASTContext::getSignedWCharType() const {
3913 // FIXME: derive from "Target" ?
3914 return WCharTy;
3915}
3916
3917/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3918/// Used when in C++, as a GCC extension.
3919QualType ASTContext::getUnsignedWCharType() const {
3920 // FIXME: derive from "Target" ?
3921 return UnsignedIntTy;
3922}
3923
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003924QualType ASTContext::getIntPtrType() const {
3925 return getFromTargetType(Target->getIntPtrType());
3926}
3927
3928QualType ASTContext::getUIntPtrType() const {
3929 return getCorrespondingUnsignedType(getIntPtrType());
3930}
3931
Hans Wennborg27541db2011-10-27 08:29:09 +00003932/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003933/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3934QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003935 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003936}
3937
Eli Friedman4e91899e2012-11-27 02:58:24 +00003938/// \brief Return the unique type for "pid_t" defined in
3939/// <sys/types.h>. We need this to compute the correct type for vfork().
3940QualType ASTContext::getProcessIDType() const {
3941 return getFromTargetType(Target->getProcessIDType());
3942}
3943
Chris Lattnera21ad802008-04-02 05:18:44 +00003944//===----------------------------------------------------------------------===//
3945// Type Operators
3946//===----------------------------------------------------------------------===//
3947
Jay Foad39c79802011-01-12 09:06:06 +00003948CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003949 // Push qualifiers into arrays, and then discard any remaining
3950 // qualifiers.
3951 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003952 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003953 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003954 QualType Result;
3955 if (isa<ArrayType>(Ty)) {
3956 Result = getArrayDecayedType(QualType(Ty,0));
3957 } else if (isa<FunctionType>(Ty)) {
3958 Result = getPointerType(QualType(Ty, 0));
3959 } else {
3960 Result = QualType(Ty, 0);
3961 }
3962
3963 return CanQualType::CreateUnsafe(Result);
3964}
3965
John McCall6c9dd522011-01-18 07:41:22 +00003966QualType ASTContext::getUnqualifiedArrayType(QualType type,
3967 Qualifiers &quals) {
3968 SplitQualType splitType = type.getSplitUnqualifiedType();
3969
3970 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3971 // the unqualified desugared type and then drops it on the floor.
3972 // We then have to strip that sugar back off with
3973 // getUnqualifiedDesugaredType(), which is silly.
3974 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003975 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003976
3977 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003978 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003979 quals = splitType.Quals;
3980 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003981 }
3982
John McCall6c9dd522011-01-18 07:41:22 +00003983 // Otherwise, recurse on the array's element type.
3984 QualType elementType = AT->getElementType();
3985 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3986
3987 // If that didn't change the element type, AT has no qualifiers, so we
3988 // can just use the results in splitType.
3989 if (elementType == unqualElementType) {
3990 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003991 quals = splitType.Quals;
3992 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003993 }
3994
3995 // Otherwise, add in the qualifiers from the outermost type, then
3996 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003997 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003998
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003999 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004000 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004001 CAT->getSizeModifier(), 0);
4002 }
4003
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004004 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004005 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004006 }
4007
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004008 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004009 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004010 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004011 VAT->getSizeModifier(),
4012 VAT->getIndexTypeCVRQualifiers(),
4013 VAT->getBracketsRange());
4014 }
4015
4016 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004017 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004018 DSAT->getSizeModifier(), 0,
4019 SourceRange());
4020}
4021
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004022/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4023/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4024/// they point to and return true. If T1 and T2 aren't pointer types
4025/// or pointer-to-member types, or if they are not similar at this
4026/// level, returns false and leaves T1 and T2 unchanged. Top-level
4027/// qualifiers on T1 and T2 are ignored. This function will typically
4028/// be called in a loop that successively "unwraps" pointer and
4029/// pointer-to-member types to compare them at each level.
4030bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4031 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4032 *T2PtrType = T2->getAs<PointerType>();
4033 if (T1PtrType && T2PtrType) {
4034 T1 = T1PtrType->getPointeeType();
4035 T2 = T2PtrType->getPointeeType();
4036 return true;
4037 }
4038
4039 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4040 *T2MPType = T2->getAs<MemberPointerType>();
4041 if (T1MPType && T2MPType &&
4042 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4043 QualType(T2MPType->getClass(), 0))) {
4044 T1 = T1MPType->getPointeeType();
4045 T2 = T2MPType->getPointeeType();
4046 return true;
4047 }
4048
David Blaikiebbafb8a2012-03-11 07:00:24 +00004049 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004050 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4051 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4052 if (T1OPType && T2OPType) {
4053 T1 = T1OPType->getPointeeType();
4054 T2 = T2OPType->getPointeeType();
4055 return true;
4056 }
4057 }
4058
4059 // FIXME: Block pointers, too?
4060
4061 return false;
4062}
4063
Jay Foad39c79802011-01-12 09:06:06 +00004064DeclarationNameInfo
4065ASTContext::getNameForTemplate(TemplateName Name,
4066 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004067 switch (Name.getKind()) {
4068 case TemplateName::QualifiedTemplate:
4069 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004070 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004071 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4072 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004073
John McCalld9dfe3a2011-06-30 08:33:18 +00004074 case TemplateName::OverloadedTemplate: {
4075 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4076 // DNInfo work in progress: CHECKME: what about DNLoc?
4077 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4078 }
4079
4080 case TemplateName::DependentTemplate: {
4081 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004082 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004083 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004084 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4085 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004086 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004087 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4088 // DNInfo work in progress: FIXME: source locations?
4089 DeclarationNameLoc DNLoc;
4090 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4091 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4092 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004093 }
4094 }
4095
John McCalld9dfe3a2011-06-30 08:33:18 +00004096 case TemplateName::SubstTemplateTemplateParm: {
4097 SubstTemplateTemplateParmStorage *subst
4098 = Name.getAsSubstTemplateTemplateParm();
4099 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4100 NameLoc);
4101 }
4102
4103 case TemplateName::SubstTemplateTemplateParmPack: {
4104 SubstTemplateTemplateParmPackStorage *subst
4105 = Name.getAsSubstTemplateTemplateParmPack();
4106 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4107 NameLoc);
4108 }
4109 }
4110
4111 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004112}
4113
Jay Foad39c79802011-01-12 09:06:06 +00004114TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004115 switch (Name.getKind()) {
4116 case TemplateName::QualifiedTemplate:
4117 case TemplateName::Template: {
4118 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004119 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004120 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004121 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4122
4123 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004124 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004125 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004126
John McCalld9dfe3a2011-06-30 08:33:18 +00004127 case TemplateName::OverloadedTemplate:
4128 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004129
John McCalld9dfe3a2011-06-30 08:33:18 +00004130 case TemplateName::DependentTemplate: {
4131 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4132 assert(DTN && "Non-dependent template names must refer to template decls.");
4133 return DTN->CanonicalTemplateName;
4134 }
4135
4136 case TemplateName::SubstTemplateTemplateParm: {
4137 SubstTemplateTemplateParmStorage *subst
4138 = Name.getAsSubstTemplateTemplateParm();
4139 return getCanonicalTemplateName(subst->getReplacement());
4140 }
4141
4142 case TemplateName::SubstTemplateTemplateParmPack: {
4143 SubstTemplateTemplateParmPackStorage *subst
4144 = Name.getAsSubstTemplateTemplateParmPack();
4145 TemplateTemplateParmDecl *canonParameter
4146 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4147 TemplateArgument canonArgPack
4148 = getCanonicalTemplateArgument(subst->getArgumentPack());
4149 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4150 }
4151 }
4152
4153 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004154}
4155
Douglas Gregoradee3e32009-11-11 23:06:43 +00004156bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4157 X = getCanonicalTemplateName(X);
4158 Y = getCanonicalTemplateName(Y);
4159 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4160}
4161
Mike Stump11289f42009-09-09 15:08:12 +00004162TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004163ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004164 switch (Arg.getKind()) {
4165 case TemplateArgument::Null:
4166 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004167
Douglas Gregora8e02e72009-07-28 23:00:59 +00004168 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004169 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004170
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004171 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004172 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004173 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004174 }
Mike Stump11289f42009-09-09 15:08:12 +00004175
Eli Friedmanb826a002012-09-26 02:36:12 +00004176 case TemplateArgument::NullPtr:
4177 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4178 /*isNullPtr*/true);
4179
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004180 case TemplateArgument::Template:
4181 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004182
4183 case TemplateArgument::TemplateExpansion:
4184 return TemplateArgument(getCanonicalTemplateName(
4185 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004186 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004187
Douglas Gregora8e02e72009-07-28 23:00:59 +00004188 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004189 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004190
Douglas Gregora8e02e72009-07-28 23:00:59 +00004191 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004192 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004193
Douglas Gregora8e02e72009-07-28 23:00:59 +00004194 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004195 if (Arg.pack_size() == 0)
4196 return Arg;
4197
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004198 TemplateArgument *CanonArgs
4199 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004200 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004201 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004202 AEnd = Arg.pack_end();
4203 A != AEnd; (void)++A, ++Idx)
4204 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004205
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004206 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004207 }
4208 }
4209
4210 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004211 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004212}
4213
Douglas Gregor333489b2009-03-27 23:10:48 +00004214NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004215ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004216 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004217 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004218
4219 switch (NNS->getKind()) {
4220 case NestedNameSpecifier::Identifier:
4221 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004222 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004223 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4224 NNS->getAsIdentifier());
4225
4226 case NestedNameSpecifier::Namespace:
4227 // A namespace is canonical; build a nested-name-specifier with
4228 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004229 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004230 NNS->getAsNamespace()->getOriginalNamespace());
4231
4232 case NestedNameSpecifier::NamespaceAlias:
4233 // A namespace is canonical; build a nested-name-specifier with
4234 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004235 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004236 NNS->getAsNamespaceAlias()->getNamespace()
4237 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004238
4239 case NestedNameSpecifier::TypeSpec:
4240 case NestedNameSpecifier::TypeSpecWithTemplate: {
4241 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004242
4243 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4244 // break it apart into its prefix and identifier, then reconsititute those
4245 // as the canonical nested-name-specifier. This is required to canonicalize
4246 // a dependent nested-name-specifier involving typedefs of dependent-name
4247 // types, e.g.,
4248 // typedef typename T::type T1;
4249 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004250 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4251 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004252 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004253
Eli Friedman5358a0a2012-03-03 04:09:56 +00004254 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4255 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4256 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004257 return NestedNameSpecifier::Create(*this, nullptr, false,
4258 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004259 }
4260
4261 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004262 case NestedNameSpecifier::Super:
4263 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004264 return NNS;
4265 }
4266
David Blaikie8a40f702012-01-17 06:56:22 +00004267 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004268}
4269
Chris Lattner7adf0762008-08-04 07:31:14 +00004270
Jay Foad39c79802011-01-12 09:06:06 +00004271const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004272 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004273 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004274 // Handle the common positive case fast.
4275 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4276 return AT;
4277 }
Mike Stump11289f42009-09-09 15:08:12 +00004278
John McCall8ccfcb52009-09-24 19:53:00 +00004279 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004280 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004281 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004282
John McCall8ccfcb52009-09-24 19:53:00 +00004283 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004284 // implements C99 6.7.3p8: "If the specification of an array type includes
4285 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004286
Chris Lattner7adf0762008-08-04 07:31:14 +00004287 // If we get here, we either have type qualifiers on the type, or we have
4288 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004289 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004290
John McCall33ddac02011-01-19 10:06:00 +00004291 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004292 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004293
Chris Lattner7adf0762008-08-04 07:31:14 +00004294 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004295 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004296 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004297 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004298
Chris Lattner7adf0762008-08-04 07:31:14 +00004299 // Otherwise, we have an array and we have qualifiers on it. Push the
4300 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004301 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004302
Chris Lattner7adf0762008-08-04 07:31:14 +00004303 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4304 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4305 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004306 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004307 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4308 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4309 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004310 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004311
Mike Stump11289f42009-09-09 15:08:12 +00004312 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004313 = dyn_cast<DependentSizedArrayType>(ATy))
4314 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004315 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004316 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004317 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004318 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004319 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004320
Chris Lattner7adf0762008-08-04 07:31:14 +00004321 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004322 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004323 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004324 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004325 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004326 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004327}
4328
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004329QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004330 if (T->isArrayType() || T->isFunctionType())
4331 return getDecayedType(T);
4332 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004333}
4334
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004335QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004336 T = getVariableArrayDecayedType(T);
4337 T = getAdjustedParameterType(T);
4338 return T.getUnqualifiedType();
4339}
4340
David Majnemerd09a51c2015-03-03 01:50:05 +00004341QualType ASTContext::getExceptionObjectType(QualType T) const {
4342 // C++ [except.throw]p3:
4343 // A throw-expression initializes a temporary object, called the exception
4344 // object, the type of which is determined by removing any top-level
4345 // cv-qualifiers from the static type of the operand of throw and adjusting
4346 // the type from "array of T" or "function returning T" to "pointer to T"
4347 // or "pointer to function returning T", [...]
4348 T = getVariableArrayDecayedType(T);
4349 if (T->isArrayType() || T->isFunctionType())
4350 T = getDecayedType(T);
4351 return T.getUnqualifiedType();
4352}
4353
Chris Lattnera21ad802008-04-02 05:18:44 +00004354/// getArrayDecayedType - Return the properly qualified result of decaying the
4355/// specified array type to a pointer. This operation is non-trivial when
4356/// handling typedefs etc. The canonical type of "T" must be an array type,
4357/// this returns a pointer to a properly qualified element of the array.
4358///
4359/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004360QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004361 // Get the element type with 'getAsArrayType' so that we don't lose any
4362 // typedefs in the element type of the array. This also handles propagation
4363 // of type qualifiers from the array type into the element type if present
4364 // (C99 6.7.3p8).
4365 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4366 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004367
Chris Lattner7adf0762008-08-04 07:31:14 +00004368 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004369
4370 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004371 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004372}
4373
John McCall33ddac02011-01-19 10:06:00 +00004374QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4375 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004376}
4377
John McCall33ddac02011-01-19 10:06:00 +00004378QualType ASTContext::getBaseElementType(QualType type) const {
4379 Qualifiers qs;
4380 while (true) {
4381 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004382 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004383 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004384
John McCall33ddac02011-01-19 10:06:00 +00004385 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004386 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004387 }
Mike Stump11289f42009-09-09 15:08:12 +00004388
John McCall33ddac02011-01-19 10:06:00 +00004389 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004390}
4391
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004392/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004393uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004394ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4395 uint64_t ElementCount = 1;
4396 do {
4397 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004398 CA = dyn_cast_or_null<ConstantArrayType>(
4399 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004400 } while (CA);
4401 return ElementCount;
4402}
4403
Steve Naroff0af91202007-04-27 21:51:21 +00004404/// getFloatingRank - Return a relative rank for floating point types.
4405/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004406static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004407 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004408 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004409
John McCall9dd450b2009-09-21 23:43:11 +00004410 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4411 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004412 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004413 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004414 case BuiltinType::Float: return FloatRank;
4415 case BuiltinType::Double: return DoubleRank;
4416 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004417 }
4418}
4419
Mike Stump11289f42009-09-09 15:08:12 +00004420/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4421/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004422/// 'typeDomain' is a real floating point or complex type.
4423/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004424QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4425 QualType Domain) const {
4426 FloatingRank EltRank = getFloatingRank(Size);
4427 if (Domain->isComplexType()) {
4428 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004429 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004430 case FloatRank: return FloatComplexTy;
4431 case DoubleRank: return DoubleComplexTy;
4432 case LongDoubleRank: return LongDoubleComplexTy;
4433 }
Steve Naroff0af91202007-04-27 21:51:21 +00004434 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004435
4436 assert(Domain->isRealFloatingType() && "Unknown domain!");
4437 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004438 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004439 case FloatRank: return FloatTy;
4440 case DoubleRank: return DoubleTy;
4441 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004442 }
David Blaikief47fa302012-01-17 02:30:50 +00004443 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004444}
4445
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004446/// getFloatingTypeOrder - Compare the rank of the two specified floating
4447/// point types, ignoring the domain of the type (i.e. 'double' ==
4448/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004449/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004450int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004451 FloatingRank LHSR = getFloatingRank(LHS);
4452 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004453
Chris Lattnerb90739d2008-04-06 23:38:49 +00004454 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004455 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004456 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004457 return 1;
4458 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004459}
4460
Chris Lattner76a00cf2008-04-06 22:59:24 +00004461/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4462/// routine will assert if passed a built-in type that isn't an integer or enum,
4463/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004464unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004465 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004466
Chris Lattner76a00cf2008-04-06 22:59:24 +00004467 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004468 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004469 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004470 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004471 case BuiltinType::Char_S:
4472 case BuiltinType::Char_U:
4473 case BuiltinType::SChar:
4474 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004475 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004476 case BuiltinType::Short:
4477 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004478 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004479 case BuiltinType::Int:
4480 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004481 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004482 case BuiltinType::Long:
4483 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004484 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004485 case BuiltinType::LongLong:
4486 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004487 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004488 case BuiltinType::Int128:
4489 case BuiltinType::UInt128:
4490 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004491 }
4492}
4493
Eli Friedman629ffb92009-08-20 04:21:42 +00004494/// \brief Whether this is a promotable bitfield reference according
4495/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4496///
4497/// \returns the type this bit-field will promote to, or NULL if no
4498/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004499QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004500 if (E->isTypeDependent() || E->isValueDependent())
4501 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004502
4503 // FIXME: We should not do this unless E->refersToBitField() is true. This
4504 // matters in C where getSourceBitField() will find bit-fields for various
4505 // cases where the source expression is not a bit-field designator.
4506
John McCalld25db7e2013-05-06 21:39:12 +00004507 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004508 if (!Field)
4509 return QualType();
4510
4511 QualType FT = Field->getType();
4512
Richard Smithcaf33902011-10-10 18:28:20 +00004513 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004514 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004515 // C++ [conv.prom]p5:
4516 // A prvalue for an integral bit-field can be converted to a prvalue of type
4517 // int if int can represent all the values of the bit-field; otherwise, it
4518 // can be converted to unsigned int if unsigned int can represent all the
4519 // values of the bit-field. If the bit-field is larger yet, no integral
4520 // promotion applies to it.
4521 // C11 6.3.1.1/2:
4522 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4523 // If an int can represent all values of the original type (as restricted by
4524 // the width, for a bit-field), the value is converted to an int; otherwise,
4525 // it is converted to an unsigned int.
4526 //
4527 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4528 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004529 if (BitWidth < IntSize)
4530 return IntTy;
4531
4532 if (BitWidth == IntSize)
4533 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4534
4535 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004536 // like the base type. GCC has some weird bugs in this area that we
4537 // deliberately do not follow (GCC follows a pre-standard resolution to
4538 // C's DR315 which treats bit-width as being part of the type, and this leaks
4539 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004540 return QualType();
4541}
4542
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004543/// getPromotedIntegerType - Returns the type that Promotable will
4544/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4545/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004546QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004547 assert(!Promotable.isNull());
4548 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004549 if (const EnumType *ET = Promotable->getAs<EnumType>())
4550 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004551
4552 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4553 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4554 // (3.9.1) can be converted to a prvalue of the first of the following
4555 // types that can represent all the values of its underlying type:
4556 // int, unsigned int, long int, unsigned long int, long long int, or
4557 // unsigned long long int [...]
4558 // FIXME: Is there some better way to compute this?
4559 if (BT->getKind() == BuiltinType::WChar_S ||
4560 BT->getKind() == BuiltinType::WChar_U ||
4561 BT->getKind() == BuiltinType::Char16 ||
4562 BT->getKind() == BuiltinType::Char32) {
4563 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4564 uint64_t FromSize = getTypeSize(BT);
4565 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4566 LongLongTy, UnsignedLongLongTy };
4567 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4568 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4569 if (FromSize < ToSize ||
4570 (FromSize == ToSize &&
4571 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4572 return PromoteTypes[Idx];
4573 }
4574 llvm_unreachable("char type should fit into long long");
4575 }
4576 }
4577
4578 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004579 if (Promotable->isSignedIntegerType())
4580 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004581 uint64_t PromotableSize = getIntWidth(Promotable);
4582 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004583 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4584 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4585}
4586
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004587/// \brief Recurses in pointer/array types until it finds an objc retainable
4588/// type and returns its ownership.
4589Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4590 while (!T.isNull()) {
4591 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4592 return T.getObjCLifetime();
4593 if (T->isArrayType())
4594 T = getBaseElementType(T);
4595 else if (const PointerType *PT = T->getAs<PointerType>())
4596 T = PT->getPointeeType();
4597 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004598 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004599 else
4600 break;
4601 }
4602
4603 return Qualifiers::OCL_None;
4604}
4605
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004606static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4607 // Incomplete enum types are not treated as integer types.
4608 // FIXME: In C++, enum types are never integer types.
4609 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4610 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004611 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004612}
4613
Mike Stump11289f42009-09-09 15:08:12 +00004614/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004615/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004616/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004617int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004618 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4619 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004620
4621 // Unwrap enums to their underlying type.
4622 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4623 LHSC = getIntegerTypeForEnum(ET);
4624 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4625 RHSC = getIntegerTypeForEnum(ET);
4626
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004627 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004628
Chris Lattner76a00cf2008-04-06 22:59:24 +00004629 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4630 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004631
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004632 unsigned LHSRank = getIntegerRank(LHSC);
4633 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004634
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004635 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4636 if (LHSRank == RHSRank) return 0;
4637 return LHSRank > RHSRank ? 1 : -1;
4638 }
Mike Stump11289f42009-09-09 15:08:12 +00004639
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004640 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4641 if (LHSUnsigned) {
4642 // If the unsigned [LHS] type is larger, return it.
4643 if (LHSRank >= RHSRank)
4644 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004645
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004646 // If the signed type can represent all values of the unsigned type, it
4647 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004648 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004649 return -1;
4650 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004651
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004652 // If the unsigned [RHS] type is larger, return it.
4653 if (RHSRank >= LHSRank)
4654 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004655
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004656 // If the signed type can represent all values of the unsigned type, it
4657 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004658 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004659 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004660}
Anders Carlsson98f07902007-08-17 05:31:46 +00004661
Mike Stump11289f42009-09-09 15:08:12 +00004662// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004663QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004664 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004665 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004666 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004667
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004668 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004669
Anders Carlsson98f07902007-08-17 05:31:46 +00004670 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004671 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004672 // int flags;
4673 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004674 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004675 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004676 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004677 FieldTypes[3] = LongTy;
4678
Anders Carlsson98f07902007-08-17 05:31:46 +00004679 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004680 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004681 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004682 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004683 SourceLocation(), nullptr,
4684 FieldTypes[i], /*TInfo=*/nullptr,
4685 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004686 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004687 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004688 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004689 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004690 }
4691
Douglas Gregord5058122010-02-11 01:19:42 +00004692 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004693 }
Mike Stump11289f42009-09-09 15:08:12 +00004694
Anders Carlsson98f07902007-08-17 05:31:46 +00004695 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004696}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004697
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004698QualType ASTContext::getObjCSuperType() const {
4699 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004700 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004701 TUDecl->addDecl(ObjCSuperTypeDecl);
4702 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4703 }
4704 return ObjCSuperType;
4705}
4706
Douglas Gregor512b0772009-04-23 22:29:11 +00004707void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004708 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004709 assert(Rec && "Invalid CFConstantStringType");
4710 CFConstantStringTypeDecl = Rec->getDecl();
4711}
4712
Jay Foad39c79802011-01-12 09:06:06 +00004713QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004714 if (BlockDescriptorType)
4715 return getTagDeclType(BlockDescriptorType);
4716
Alp Toker2dea15b2013-12-17 01:22:38 +00004717 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004718 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004719 RD = buildImplicitRecord("__block_descriptor");
4720 RD->startDefinition();
4721
Mike Stumpd0153282009-10-20 02:12:22 +00004722 QualType FieldTypes[] = {
4723 UnsignedLongTy,
4724 UnsignedLongTy,
4725 };
4726
Craig Topperd6d31ac2013-07-15 08:24:27 +00004727 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004728 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004729 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004730 };
4731
4732 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004733 FieldDecl *Field = FieldDecl::Create(
4734 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004735 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4736 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004737 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004738 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004739 }
4740
Alp Toker2dea15b2013-12-17 01:22:38 +00004741 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004742
Alp Toker2dea15b2013-12-17 01:22:38 +00004743 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004744
4745 return getTagDeclType(BlockDescriptorType);
4746}
4747
Jay Foad39c79802011-01-12 09:06:06 +00004748QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004749 if (BlockDescriptorExtendedType)
4750 return getTagDeclType(BlockDescriptorExtendedType);
4751
Alp Toker2dea15b2013-12-17 01:22:38 +00004752 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004753 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004754 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4755 RD->startDefinition();
4756
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004757 QualType FieldTypes[] = {
4758 UnsignedLongTy,
4759 UnsignedLongTy,
4760 getPointerType(VoidPtrTy),
4761 getPointerType(VoidPtrTy)
4762 };
4763
Craig Topperd6d31ac2013-07-15 08:24:27 +00004764 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004765 "reserved",
4766 "Size",
4767 "CopyFuncPtr",
4768 "DestroyFuncPtr"
4769 };
4770
4771 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004772 FieldDecl *Field = FieldDecl::Create(
4773 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004774 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4775 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004776 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004777 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004778 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004779 }
4780
Alp Toker2dea15b2013-12-17 01:22:38 +00004781 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004782
Alp Toker2dea15b2013-12-17 01:22:38 +00004783 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004784 return getTagDeclType(BlockDescriptorExtendedType);
4785}
4786
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004787/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4788/// requires copy/dispose. Note that this must match the logic
4789/// in buildByrefHelpers.
4790bool ASTContext::BlockRequiresCopying(QualType Ty,
4791 const VarDecl *D) {
4792 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4793 const Expr *copyExpr = getBlockVarCopyInits(D);
4794 if (!copyExpr && record->hasTrivialDestructor()) return false;
4795
Mike Stump94967902009-10-21 18:16:27 +00004796 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004797 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004798
4799 if (!Ty->isObjCRetainableType()) return false;
4800
4801 Qualifiers qs = Ty.getQualifiers();
4802
4803 // If we have lifetime, that dominates.
4804 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4805 assert(getLangOpts().ObjCAutoRefCount);
4806
4807 switch (lifetime) {
4808 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4809
4810 // These are just bits as far as the runtime is concerned.
4811 case Qualifiers::OCL_ExplicitNone:
4812 case Qualifiers::OCL_Autoreleasing:
4813 return false;
4814
4815 // Tell the runtime that this is ARC __weak, called by the
4816 // byref routines.
4817 case Qualifiers::OCL_Weak:
4818 // ARC __strong __block variables need to be retained.
4819 case Qualifiers::OCL_Strong:
4820 return true;
4821 }
4822 llvm_unreachable("fell out of lifetime switch!");
4823 }
4824 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4825 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004826}
4827
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004828bool ASTContext::getByrefLifetime(QualType Ty,
4829 Qualifiers::ObjCLifetime &LifeTime,
4830 bool &HasByrefExtendedLayout) const {
4831
4832 if (!getLangOpts().ObjC1 ||
4833 getLangOpts().getGC() != LangOptions::NonGC)
4834 return false;
4835
4836 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004837 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004838 HasByrefExtendedLayout = true;
4839 LifeTime = Qualifiers::OCL_None;
4840 }
4841 else if (getLangOpts().ObjCAutoRefCount)
4842 LifeTime = Ty.getObjCLifetime();
4843 // MRR.
4844 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4845 LifeTime = Qualifiers::OCL_ExplicitNone;
4846 else
4847 LifeTime = Qualifiers::OCL_None;
4848 return true;
4849}
4850
Douglas Gregorbab8a962011-09-08 01:46:34 +00004851TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4852 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004853 ObjCInstanceTypeDecl =
4854 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004855 return ObjCInstanceTypeDecl;
4856}
4857
Anders Carlsson18acd442007-10-29 06:33:42 +00004858// This returns true if a type has been typedefed to BOOL:
4859// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004860static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004861 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004862 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4863 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004864
Anders Carlssond8499822007-10-29 05:01:08 +00004865 return false;
4866}
4867
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004868/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004869/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004870CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004871 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4872 return CharUnits::Zero();
4873
Ken Dyck40775002010-01-11 17:06:35 +00004874 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004875
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004876 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004877 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004878 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004879 // Treat arrays as pointers, since that's how they're passed in.
4880 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004881 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004882 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004883}
4884
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004885bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4886 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4887 VD->getType()->isIntegralOrEnumerationType() &&
4888 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4889}
4890
Ken Dyck40775002010-01-11 17:06:35 +00004891static inline
4892std::string charUnitsToString(const CharUnits &CU) {
4893 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004894}
4895
John McCall351762c2011-02-07 10:33:21 +00004896/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004897/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004898std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4899 std::string S;
4900
David Chisnall950a9512009-11-17 19:33:30 +00004901 const BlockDecl *Decl = Expr->getBlockDecl();
4902 QualType BlockTy =
4903 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4904 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004905 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004906 getObjCEncodingForMethodParameter(
4907 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4908 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004909 else
Alp Toker314cc812014-01-25 16:55:45 +00004910 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004911 // Compute size of all parameters.
4912 // Start with computing size of a pointer in number of bytes.
4913 // FIXME: There might(should) be a better way of doing this computation!
4914 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004915 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4916 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004917 for (auto PI : Decl->params()) {
4918 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004919 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004920 if (sz.isZero())
4921 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004922 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004923 ParmOffset += sz;
4924 }
4925 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004926 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004927 // Block pointer and offset.
4928 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004929
4930 // Argument types.
4931 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004932 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004933 QualType PType = PVDecl->getOriginalType();
4934 if (const ArrayType *AT =
4935 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4936 // Use array's original type only if it has known number of
4937 // elements.
4938 if (!isa<ConstantArrayType>(AT))
4939 PType = PVDecl->getType();
4940 } else if (PType->isFunctionType())
4941 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004942 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004943 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4944 S, true /*Extended*/);
4945 else
4946 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004947 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004948 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004949 }
John McCall351762c2011-02-07 10:33:21 +00004950
4951 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004952}
4953
Douglas Gregora9d84932011-05-27 01:19:52 +00004954bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004955 std::string& S) {
4956 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004957 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004958 CharUnits ParmOffset;
4959 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004960 for (auto PI : Decl->params()) {
4961 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004962 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004963 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004964 continue;
4965
David Chisnall50e4eba2010-12-30 14:05:53 +00004966 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004967 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004968 ParmOffset += sz;
4969 }
4970 S += charUnitsToString(ParmOffset);
4971 ParmOffset = CharUnits::Zero();
4972
4973 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004974 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004975 QualType PType = PVDecl->getOriginalType();
4976 if (const ArrayType *AT =
4977 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4978 // Use array's original type only if it has known number of
4979 // elements.
4980 if (!isa<ConstantArrayType>(AT))
4981 PType = PVDecl->getType();
4982 } else if (PType->isFunctionType())
4983 PType = PVDecl->getType();
4984 getObjCEncodingForType(PType, S);
4985 S += charUnitsToString(ParmOffset);
4986 ParmOffset += getObjCEncodingTypeSize(PType);
4987 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004988
4989 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004990}
4991
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004992/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4993/// method parameter or return type. If Extended, include class names and
4994/// block object types.
4995void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4996 QualType T, std::string& S,
4997 bool Extended) const {
4998 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4999 getObjCEncodingForTypeQualifier(QT, S);
5000 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005001 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005002 true /*OutermostType*/,
5003 false /*EncodingProperty*/,
5004 false /*StructField*/,
5005 Extended /*EncodeBlockParameters*/,
5006 Extended /*EncodeClassNames*/);
5007}
5008
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005009/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005010/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005011bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005012 std::string& S,
5013 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005014 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005015 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005016 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5017 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005018 // Compute size of all parameters.
5019 // Start with computing size of a pointer in number of bytes.
5020 // FIXME: There might(should) be a better way of doing this computation!
5021 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005022 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005023 // The first two arguments (self and _cmd) are pointers; account for
5024 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005025 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005026 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005027 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005028 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005029 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005030 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005031 continue;
5032
Ken Dyck40775002010-01-11 17:06:35 +00005033 assert (sz.isPositive() &&
5034 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005035 ParmOffset += sz;
5036 }
Ken Dyck40775002010-01-11 17:06:35 +00005037 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005038 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005039 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005040
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005041 // Argument types.
5042 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005043 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005044 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005045 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005046 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005047 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005048 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5049 // Use array's original type only if it has known number of
5050 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005051 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005052 PType = PVDecl->getType();
5053 } else if (PType->isFunctionType())
5054 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005055 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5056 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005057 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005058 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005059 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005060
5061 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005062}
5063
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005064ObjCPropertyImplDecl *
5065ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5066 const ObjCPropertyDecl *PD,
5067 const Decl *Container) const {
5068 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005069 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005070 if (const ObjCCategoryImplDecl *CID =
5071 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005072 for (auto *PID : CID->property_impls())
5073 if (PID->getPropertyDecl() == PD)
5074 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005075 } else {
5076 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5077 for (auto *PID : OID->property_impls())
5078 if (PID->getPropertyDecl() == PD)
5079 return PID;
5080 }
5081 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005082}
5083
Daniel Dunbar4932b362008-08-28 04:38:10 +00005084/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005085/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005086/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5087/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005088/// Property attributes are stored as a comma-delimited C string. The simple
5089/// attributes readonly and bycopy are encoded as single characters. The
5090/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5091/// encoded as single characters, followed by an identifier. Property types
5092/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005093/// these attributes are defined by the following enumeration:
5094/// @code
5095/// enum PropertyAttributes {
5096/// kPropertyReadOnly = 'R', // property is read-only.
5097/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5098/// kPropertyByref = '&', // property is a reference to the value last assigned
5099/// kPropertyDynamic = 'D', // property is dynamic
5100/// kPropertyGetter = 'G', // followed by getter selector name
5101/// kPropertySetter = 'S', // followed by setter selector name
5102/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005103/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005104/// kPropertyWeak = 'W' // 'weak' property
5105/// kPropertyStrong = 'P' // property GC'able
5106/// kPropertyNonAtomic = 'N' // property non-atomic
5107/// };
5108/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005109void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005110 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005111 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005112 // Collect information from the property implementation decl(s).
5113 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005114 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005115
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005116 if (ObjCPropertyImplDecl *PropertyImpDecl =
5117 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5118 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5119 Dynamic = true;
5120 else
5121 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005122 }
5123
5124 // FIXME: This is not very efficient.
5125 S = "T";
5126
5127 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005128 // GCC has some special rules regarding encoding of properties which
5129 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005130 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005131
5132 if (PD->isReadOnly()) {
5133 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005134 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5135 S += ",C";
5136 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5137 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005138 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5139 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005140 } else {
5141 switch (PD->getSetterKind()) {
5142 case ObjCPropertyDecl::Assign: break;
5143 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005144 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005145 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005146 }
5147 }
5148
5149 // It really isn't clear at all what this means, since properties
5150 // are "dynamic by default".
5151 if (Dynamic)
5152 S += ",D";
5153
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005154 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5155 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005156
Daniel Dunbar4932b362008-08-28 04:38:10 +00005157 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5158 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005159 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005160 }
5161
5162 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5163 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005164 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005165 }
5166
5167 if (SynthesizePID) {
5168 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5169 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005170 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005171 }
5172
5173 // FIXME: OBJCGC: weak & strong
5174}
5175
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005176/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005177/// Another legacy compatibility encoding: 32-bit longs are encoded as
5178/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005179/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5180///
5181void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005182 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005183 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005184 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005185 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005186 else
Jay Foad39c79802011-01-12 09:06:06 +00005187 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005188 PointeeTy = IntTy;
5189 }
5190 }
5191}
5192
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005193void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005194 const FieldDecl *Field,
5195 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005196 // We follow the behavior of gcc, expanding structures which are
5197 // directly pointed to, and expanding embedded structures. Note that
5198 // these rules are sufficient to prevent recursive encoding of the
5199 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005200 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005201 true /* outermost type */, false, false,
5202 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005203}
5204
Joe Groff98ac7d22014-07-07 22:25:15 +00005205void ASTContext::getObjCEncodingForPropertyType(QualType T,
5206 std::string& S) const {
5207 // Encode result type.
5208 // GCC has some special rules regarding encoding of properties which
5209 // closely resembles encoding of ivars.
5210 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5211 true /* outermost type */,
5212 true /* encoding property */);
5213}
5214
John McCall393a78d2012-12-20 02:45:14 +00005215static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5216 BuiltinType::Kind kind) {
5217 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005218 case BuiltinType::Void: return 'v';
5219 case BuiltinType::Bool: return 'B';
5220 case BuiltinType::Char_U:
5221 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005222 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005223 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005224 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005225 case BuiltinType::UInt: return 'I';
5226 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005227 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005228 case BuiltinType::UInt128: return 'T';
5229 case BuiltinType::ULongLong: return 'Q';
5230 case BuiltinType::Char_S:
5231 case BuiltinType::SChar: return 'c';
5232 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005233 case BuiltinType::WChar_S:
5234 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005235 case BuiltinType::Int: return 'i';
5236 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005237 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005238 case BuiltinType::LongLong: return 'q';
5239 case BuiltinType::Int128: return 't';
5240 case BuiltinType::Float: return 'f';
5241 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005242 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005243 case BuiltinType::NullPtr: return '*'; // like char*
5244
5245 case BuiltinType::Half:
5246 // FIXME: potentially need @encodes for these!
5247 return ' ';
5248
5249 case BuiltinType::ObjCId:
5250 case BuiltinType::ObjCClass:
5251 case BuiltinType::ObjCSel:
5252 llvm_unreachable("@encoding ObjC primitive type");
5253
5254 // OpenCL and placeholder types don't need @encodings.
5255 case BuiltinType::OCLImage1d:
5256 case BuiltinType::OCLImage1dArray:
5257 case BuiltinType::OCLImage1dBuffer:
5258 case BuiltinType::OCLImage2d:
5259 case BuiltinType::OCLImage2dArray:
5260 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005261 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005262 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005263 case BuiltinType::Dependent:
5264#define BUILTIN_TYPE(KIND, ID)
5265#define PLACEHOLDER_TYPE(KIND, ID) \
5266 case BuiltinType::KIND:
5267#include "clang/AST/BuiltinTypes.def"
5268 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005269 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005270 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005271}
5272
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005273static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5274 EnumDecl *Enum = ET->getDecl();
5275
5276 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5277 if (!Enum->isFixed())
5278 return 'i';
5279
5280 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005281 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5282 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005283}
5284
Jay Foad39c79802011-01-12 09:06:06 +00005285static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005286 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005287 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005288 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005289 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5290 // The GNU runtime requires more information; bitfields are encoded as b,
5291 // then the offset (in bits) of the first element, then the type of the
5292 // bitfield, then the size in bits. For example, in this structure:
5293 //
5294 // struct
5295 // {
5296 // int integer;
5297 // int flags:2;
5298 // };
5299 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5300 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5301 // information is not especially sensible, but we're stuck with it for
5302 // compatibility with GCC, although providing it breaks anything that
5303 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005304 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005305 const RecordDecl *RD = FD->getParent();
5306 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005307 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005308 if (const EnumType *ET = T->getAs<EnumType>())
5309 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005310 else {
5311 const BuiltinType *BT = T->castAs<BuiltinType>();
5312 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5313 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005314 }
Richard Smithcaf33902011-10-10 18:28:20 +00005315 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005316}
5317
Daniel Dunbar07d07852009-10-18 21:17:35 +00005318// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005319void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5320 bool ExpandPointedToStructures,
5321 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005322 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005323 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005324 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005325 bool StructField,
5326 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005327 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005328 bool EncodePointerToObjCTypedef,
5329 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005330 CanQualType CT = getCanonicalType(T);
5331 switch (CT->getTypeClass()) {
5332 case Type::Builtin:
5333 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005334 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005335 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005336 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5337 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5338 else
5339 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005340 return;
Mike Stump11289f42009-09-09 15:08:12 +00005341
John McCall393a78d2012-12-20 02:45:14 +00005342 case Type::Complex: {
5343 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005344 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005345 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005346 return;
5347 }
John McCall393a78d2012-12-20 02:45:14 +00005348
5349 case Type::Atomic: {
5350 const AtomicType *AT = T->castAs<AtomicType>();
5351 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005352 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005353 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005354 }
John McCall393a78d2012-12-20 02:45:14 +00005355
5356 // encoding for pointer or reference types.
5357 case Type::Pointer:
5358 case Type::LValueReference:
5359 case Type::RValueReference: {
5360 QualType PointeeTy;
5361 if (isa<PointerType>(CT)) {
5362 const PointerType *PT = T->castAs<PointerType>();
5363 if (PT->isObjCSelType()) {
5364 S += ':';
5365 return;
5366 }
5367 PointeeTy = PT->getPointeeType();
5368 } else {
5369 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5370 }
5371
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005372 bool isReadOnly = false;
5373 // For historical/compatibility reasons, the read-only qualifier of the
5374 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5375 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005376 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005377 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005378 if (OutermostType && T.isConstQualified()) {
5379 isReadOnly = true;
5380 S += 'r';
5381 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005382 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005383 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005384 while (P->getAs<PointerType>())
5385 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005386 if (P.isConstQualified()) {
5387 isReadOnly = true;
5388 S += 'r';
5389 }
5390 }
5391 if (isReadOnly) {
5392 // Another legacy compatibility encoding. Some ObjC qualifier and type
5393 // combinations need to be rearranged.
5394 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005395 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005396 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005397 }
Mike Stump11289f42009-09-09 15:08:12 +00005398
Anders Carlssond8499822007-10-29 05:01:08 +00005399 if (PointeeTy->isCharType()) {
5400 // char pointer types should be encoded as '*' unless it is a
5401 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005402 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005403 S += '*';
5404 return;
5405 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005406 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005407 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5408 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5409 S += '#';
5410 return;
5411 }
5412 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5413 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5414 S += '@';
5415 return;
5416 }
5417 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005418 }
Anders Carlssond8499822007-10-29 05:01:08 +00005419 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005420 getLegacyIntegralTypeEncoding(PointeeTy);
5421
Mike Stump11289f42009-09-09 15:08:12 +00005422 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005423 nullptr, false, false, false, false, false, false,
5424 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005425 return;
5426 }
John McCall393a78d2012-12-20 02:45:14 +00005427
5428 case Type::ConstantArray:
5429 case Type::IncompleteArray:
5430 case Type::VariableArray: {
5431 const ArrayType *AT = cast<ArrayType>(CT);
5432
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005433 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005434 // Incomplete arrays are encoded as a pointer to the array element.
5435 S += '^';
5436
Mike Stump11289f42009-09-09 15:08:12 +00005437 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005438 false, ExpandStructures, FD);
5439 } else {
5440 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005441
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005442 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5443 S += llvm::utostr(CAT->getSize().getZExtValue());
5444 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005445 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005446 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5447 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005448 S += '0';
5449 }
Mike Stump11289f42009-09-09 15:08:12 +00005450
5451 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005452 false, ExpandStructures, FD,
5453 false, false, false, false, false, false,
5454 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005455 S += ']';
5456 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005457 return;
5458 }
Mike Stump11289f42009-09-09 15:08:12 +00005459
John McCall393a78d2012-12-20 02:45:14 +00005460 case Type::FunctionNoProto:
5461 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005462 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005463 return;
Mike Stump11289f42009-09-09 15:08:12 +00005464
John McCall393a78d2012-12-20 02:45:14 +00005465 case Type::Record: {
5466 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005467 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005468 // Anonymous structures print as '?'
5469 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5470 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005471 if (ClassTemplateSpecializationDecl *Spec
5472 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5473 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005474 llvm::raw_string_ostream OS(S);
5475 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005476 TemplateArgs.data(),
5477 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005478 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005479 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005480 } else {
5481 S += '?';
5482 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005483 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005484 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005485 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005486 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005487 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005488 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005489 if (FD) {
5490 S += '"';
5491 S += Field->getNameAsString();
5492 S += '"';
5493 }
Mike Stump11289f42009-09-09 15:08:12 +00005494
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005495 // Special case bit-fields.
5496 if (Field->isBitField()) {
5497 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005498 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005499 } else {
5500 QualType qt = Field->getType();
5501 getLegacyIntegralTypeEncoding(qt);
5502 getObjCEncodingForTypeImpl(qt, S, false, true,
5503 FD, /*OutermostType*/false,
5504 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005505 /*StructField*/true,
5506 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005507 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005508 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005509 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005510 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005511 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005512 return;
5513 }
Mike Stump11289f42009-09-09 15:08:12 +00005514
John McCall393a78d2012-12-20 02:45:14 +00005515 case Type::BlockPointer: {
5516 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005517 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005518 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005519 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005520
5521 S += '<';
5522 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005523 getObjCEncodingForTypeImpl(
5524 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5525 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005526 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5527 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005528 // Block self
5529 S += "@?";
5530 // Block parameters
5531 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005532 for (const auto &I : FPT->param_types())
5533 getObjCEncodingForTypeImpl(
5534 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5535 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005536 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5537 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005538 }
5539 S += '>';
5540 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005541 return;
5542 }
Mike Stump11289f42009-09-09 15:08:12 +00005543
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005544 case Type::ObjCObject: {
5545 // hack to match legacy encoding of *id and *Class
5546 QualType Ty = getObjCObjectPointerType(CT);
5547 if (Ty->isObjCIdType()) {
5548 S += "{objc_object=}";
5549 return;
5550 }
5551 else if (Ty->isObjCClassType()) {
5552 S += "{objc_class=}";
5553 return;
5554 }
5555 }
5556
John McCall393a78d2012-12-20 02:45:14 +00005557 case Type::ObjCInterface: {
5558 // Ignore protocol qualifiers when mangling at this level.
5559 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005560
John McCall393a78d2012-12-20 02:45:14 +00005561 // The assumption seems to be that this assert will succeed
5562 // because nested levels will have filtered out 'id' and 'Class'.
5563 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005564 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005565 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005566 S += '{';
5567 const IdentifierInfo *II = OI->getIdentifier();
5568 S += II->getName();
5569 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005570 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005571 DeepCollectObjCIvars(OI, true, Ivars);
5572 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005573 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005574 if (Field->isBitField())
5575 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005576 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005577 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5578 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005579 EncodePointerToObjCTypedef,
5580 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005581 }
5582 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005583 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005584 }
Mike Stump11289f42009-09-09 15:08:12 +00005585
John McCall393a78d2012-12-20 02:45:14 +00005586 case Type::ObjCObjectPointer: {
5587 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005588 if (OPT->isObjCIdType()) {
5589 S += '@';
5590 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005591 }
Mike Stump11289f42009-09-09 15:08:12 +00005592
Steve Narofff0c86112009-10-28 22:03:49 +00005593 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5594 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5595 // Since this is a binary compatibility issue, need to consult with runtime
5596 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005597 S += '#';
5598 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005599 }
Mike Stump11289f42009-09-09 15:08:12 +00005600
Chris Lattnere7cabb92009-07-13 00:10:46 +00005601 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005602 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005603 ExpandPointedToStructures,
5604 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005605 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005606 // Note that we do extended encoding of protocol qualifer list
5607 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005608 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005609 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005610 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005611 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005612 S += '>';
5613 }
5614 S += '"';
5615 }
5616 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005617 }
Mike Stump11289f42009-09-09 15:08:12 +00005618
Chris Lattnere7cabb92009-07-13 00:10:46 +00005619 QualType PointeeTy = OPT->getPointeeType();
5620 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005621 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5622 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005623 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005624 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005625 // {...};
5626 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005627 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005628 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005629 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5630 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5631 DeepCollectObjCIvars(OI, true, Ivars);
5632 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5633 if (cast<FieldDecl>(Ivars[i]) == FD) {
5634 S += '{';
5635 S += OI->getIdentifier()->getName();
5636 S += '}';
5637 return;
5638 }
5639 }
5640 }
Mike Stump11289f42009-09-09 15:08:12 +00005641 getObjCEncodingForTypeImpl(PointeeTy, S,
5642 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005643 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005644 false, false, false, false, false,
5645 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005646 return;
5647 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005648
5649 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005650 if (OPT->getInterfaceDecl() &&
5651 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005652 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005653 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005654 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005655 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005656 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005657 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005658 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005659 S += '"';
5660 }
5661 return;
5662 }
Mike Stump11289f42009-09-09 15:08:12 +00005663
John McCalla9e6e8d2010-05-17 23:56:34 +00005664 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005665 // FIXME: we shoul do better than that. 'M' is available.
5666 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005667 // This matches gcc's encoding, even though technically it is insufficient.
5668 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005669 case Type::Vector:
5670 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005671 // Until we have a coherent encoding of these three types, issue warning.
5672 { if (NotEncodedT)
5673 *NotEncodedT = T;
5674 return;
5675 }
5676
5677 // We could see an undeduced auto type here during error recovery.
5678 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005679 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005680 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005681
Richard Smith27d807c2013-04-30 13:56:41 +00005682
John McCall393a78d2012-12-20 02:45:14 +00005683#define ABSTRACT_TYPE(KIND, BASE)
5684#define TYPE(KIND, BASE)
5685#define DEPENDENT_TYPE(KIND, BASE) \
5686 case Type::KIND:
5687#define NON_CANONICAL_TYPE(KIND, BASE) \
5688 case Type::KIND:
5689#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5690 case Type::KIND:
5691#include "clang/AST/TypeNodes.def"
5692 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005693 }
John McCall393a78d2012-12-20 02:45:14 +00005694 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005695}
5696
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005697void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5698 std::string &S,
5699 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005700 bool includeVBases,
5701 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005702 assert(RDecl && "Expected non-null RecordDecl");
5703 assert(!RDecl->isUnion() && "Should not be called for unions");
5704 if (!RDecl->getDefinition())
5705 return;
5706
5707 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5708 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5709 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5710
5711 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005712 for (const auto &BI : CXXRec->bases()) {
5713 if (!BI.isVirtual()) {
5714 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005715 if (base->isEmpty())
5716 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005717 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005718 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5719 std::make_pair(offs, base));
5720 }
5721 }
5722 }
5723
5724 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005725 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005726 uint64_t offs = layout.getFieldOffset(i);
5727 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005728 std::make_pair(offs, Field));
5729 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005730 }
5731
5732 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005733 for (const auto &BI : CXXRec->vbases()) {
5734 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005735 if (base->isEmpty())
5736 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005737 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005738 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5739 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005740 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5741 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005742 }
5743 }
5744
5745 CharUnits size;
5746 if (CXXRec) {
5747 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5748 } else {
5749 size = layout.getSize();
5750 }
5751
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005752#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005753 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005754#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005755 std::multimap<uint64_t, NamedDecl *>::iterator
5756 CurLayObj = FieldOrBaseOffsets.begin();
5757
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005758 if (CXXRec && CXXRec->isDynamicClass() &&
5759 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005760 if (FD) {
5761 S += "\"_vptr$";
5762 std::string recname = CXXRec->getNameAsString();
5763 if (recname.empty()) recname = "?";
5764 S += recname;
5765 S += '"';
5766 }
5767 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005768#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005769 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005770#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005771 }
5772
5773 if (!RDecl->hasFlexibleArrayMember()) {
5774 // Mark the end of the structure.
5775 uint64_t offs = toBits(size);
5776 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005777 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005778 }
5779
5780 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005781#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005782 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005783 if (CurOffs < CurLayObj->first) {
5784 uint64_t padding = CurLayObj->first - CurOffs;
5785 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5786 // packing/alignment of members is different that normal, in which case
5787 // the encoding will be out-of-sync with the real layout.
5788 // If the runtime switches to just consider the size of types without
5789 // taking into account alignment, we could make padding explicit in the
5790 // encoding (e.g. using arrays of chars). The encoding strings would be
5791 // longer then though.
5792 CurOffs += padding;
5793 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005794#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005795
5796 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005797 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005798 break; // reached end of structure.
5799
5800 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5801 // We expand the bases without their virtual bases since those are going
5802 // in the initial structure. Note that this differs from gcc which
5803 // expands virtual bases each time one is encountered in the hierarchy,
5804 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005805 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5806 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005807 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005808#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005809 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005810#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005811 } else {
5812 FieldDecl *field = cast<FieldDecl>(dcl);
5813 if (FD) {
5814 S += '"';
5815 S += field->getNameAsString();
5816 S += '"';
5817 }
5818
5819 if (field->isBitField()) {
5820 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005821#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005822 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005823#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005824 } else {
5825 QualType qt = field->getType();
5826 getLegacyIntegralTypeEncoding(qt);
5827 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5828 /*OutermostType*/false,
5829 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005830 /*StructField*/true,
5831 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005832#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005833 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005834#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005835 }
5836 }
5837 }
5838}
5839
Mike Stump11289f42009-09-09 15:08:12 +00005840void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005841 std::string& S) const {
5842 if (QT & Decl::OBJC_TQ_In)
5843 S += 'n';
5844 if (QT & Decl::OBJC_TQ_Inout)
5845 S += 'N';
5846 if (QT & Decl::OBJC_TQ_Out)
5847 S += 'o';
5848 if (QT & Decl::OBJC_TQ_Bycopy)
5849 S += 'O';
5850 if (QT & Decl::OBJC_TQ_Byref)
5851 S += 'R';
5852 if (QT & Decl::OBJC_TQ_Oneway)
5853 S += 'V';
5854}
5855
Douglas Gregor3ea72692011-08-12 05:46:01 +00005856TypedefDecl *ASTContext::getObjCIdDecl() const {
5857 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005858 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005859 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005860 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005861 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005862 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005863}
5864
Douglas Gregor52e02802011-08-12 06:17:30 +00005865TypedefDecl *ASTContext::getObjCSelDecl() const {
5866 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005867 QualType T = getPointerType(ObjCBuiltinSelTy);
5868 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005869 }
5870 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005871}
5872
Douglas Gregor0a586182011-08-12 05:59:41 +00005873TypedefDecl *ASTContext::getObjCClassDecl() const {
5874 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005875 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005876 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005877 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005878 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005879 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005880}
5881
Douglas Gregord53ae832012-01-17 18:09:05 +00005882ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5883 if (!ObjCProtocolClassDecl) {
5884 ObjCProtocolClassDecl
5885 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5886 SourceLocation(),
5887 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005888 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005889 SourceLocation(), true);
5890 }
5891
5892 return ObjCProtocolClassDecl;
5893}
5894
Meador Inge5d3fb222012-06-16 03:34:49 +00005895//===----------------------------------------------------------------------===//
5896// __builtin_va_list Construction Functions
5897//===----------------------------------------------------------------------===//
5898
5899static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5900 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005901 QualType T = Context->getPointerType(Context->CharTy);
5902 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005903}
5904
5905static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5906 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005907 QualType T = Context->getPointerType(Context->VoidTy);
5908 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005909}
5910
Tim Northover9bb857a2013-01-31 12:13:10 +00005911static TypedefDecl *
5912CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005913 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005914 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005915 if (Context->getLangOpts().CPlusPlus) {
5916 // namespace std { struct __va_list {
5917 NamespaceDecl *NS;
5918 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5919 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005920 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005921 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005922 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005923 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005924 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005925 }
5926
5927 VaListTagDecl->startDefinition();
5928
5929 const size_t NumFields = 5;
5930 QualType FieldTypes[NumFields];
5931 const char *FieldNames[NumFields];
5932
5933 // void *__stack;
5934 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5935 FieldNames[0] = "__stack";
5936
5937 // void *__gr_top;
5938 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5939 FieldNames[1] = "__gr_top";
5940
5941 // void *__vr_top;
5942 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5943 FieldNames[2] = "__vr_top";
5944
5945 // int __gr_offs;
5946 FieldTypes[3] = Context->IntTy;
5947 FieldNames[3] = "__gr_offs";
5948
5949 // int __vr_offs;
5950 FieldTypes[4] = Context->IntTy;
5951 FieldNames[4] = "__vr_offs";
5952
5953 // Create fields
5954 for (unsigned i = 0; i < NumFields; ++i) {
5955 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5956 VaListTagDecl,
5957 SourceLocation(),
5958 SourceLocation(),
5959 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005960 FieldTypes[i], /*TInfo=*/nullptr,
5961 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005962 /*Mutable=*/false,
5963 ICIS_NoInit);
5964 Field->setAccess(AS_public);
5965 VaListTagDecl->addDecl(Field);
5966 }
5967 VaListTagDecl->completeDefinition();
5968 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5969 Context->VaListTagTy = VaListTagType;
5970
5971 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005972 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005973}
5974
Meador Inge5d3fb222012-06-16 03:34:49 +00005975static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5976 // typedef struct __va_list_tag {
5977 RecordDecl *VaListTagDecl;
5978
Alp Toker2dea15b2013-12-17 01:22:38 +00005979 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005980 VaListTagDecl->startDefinition();
5981
5982 const size_t NumFields = 5;
5983 QualType FieldTypes[NumFields];
5984 const char *FieldNames[NumFields];
5985
5986 // unsigned char gpr;
5987 FieldTypes[0] = Context->UnsignedCharTy;
5988 FieldNames[0] = "gpr";
5989
5990 // unsigned char fpr;
5991 FieldTypes[1] = Context->UnsignedCharTy;
5992 FieldNames[1] = "fpr";
5993
5994 // unsigned short reserved;
5995 FieldTypes[2] = Context->UnsignedShortTy;
5996 FieldNames[2] = "reserved";
5997
5998 // void* overflow_arg_area;
5999 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6000 FieldNames[3] = "overflow_arg_area";
6001
6002 // void* reg_save_area;
6003 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6004 FieldNames[4] = "reg_save_area";
6005
6006 // Create fields
6007 for (unsigned i = 0; i < NumFields; ++i) {
6008 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6009 SourceLocation(),
6010 SourceLocation(),
6011 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006012 FieldTypes[i], /*TInfo=*/nullptr,
6013 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006014 /*Mutable=*/false,
6015 ICIS_NoInit);
6016 Field->setAccess(AS_public);
6017 VaListTagDecl->addDecl(Field);
6018 }
6019 VaListTagDecl->completeDefinition();
6020 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006021 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006022
6023 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006024 TypedefDecl *VaListTagTypedefDecl =
6025 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6026
Meador Inge5d3fb222012-06-16 03:34:49 +00006027 QualType VaListTagTypedefType =
6028 Context->getTypedefType(VaListTagTypedefDecl);
6029
6030 // typedef __va_list_tag __builtin_va_list[1];
6031 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6032 QualType VaListTagArrayType
6033 = Context->getConstantArrayType(VaListTagTypedefType,
6034 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006035 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006036}
6037
6038static TypedefDecl *
6039CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6040 // typedef struct __va_list_tag {
6041 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006042 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006043 VaListTagDecl->startDefinition();
6044
6045 const size_t NumFields = 4;
6046 QualType FieldTypes[NumFields];
6047 const char *FieldNames[NumFields];
6048
6049 // unsigned gp_offset;
6050 FieldTypes[0] = Context->UnsignedIntTy;
6051 FieldNames[0] = "gp_offset";
6052
6053 // unsigned fp_offset;
6054 FieldTypes[1] = Context->UnsignedIntTy;
6055 FieldNames[1] = "fp_offset";
6056
6057 // void* overflow_arg_area;
6058 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6059 FieldNames[2] = "overflow_arg_area";
6060
6061 // void* reg_save_area;
6062 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6063 FieldNames[3] = "reg_save_area";
6064
6065 // Create fields
6066 for (unsigned i = 0; i < NumFields; ++i) {
6067 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6068 VaListTagDecl,
6069 SourceLocation(),
6070 SourceLocation(),
6071 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006072 FieldTypes[i], /*TInfo=*/nullptr,
6073 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006074 /*Mutable=*/false,
6075 ICIS_NoInit);
6076 Field->setAccess(AS_public);
6077 VaListTagDecl->addDecl(Field);
6078 }
6079 VaListTagDecl->completeDefinition();
6080 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006081 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006082
6083 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006084 TypedefDecl *VaListTagTypedefDecl =
6085 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6086
Meador Inge5d3fb222012-06-16 03:34:49 +00006087 QualType VaListTagTypedefType =
6088 Context->getTypedefType(VaListTagTypedefDecl);
6089
6090 // typedef __va_list_tag __builtin_va_list[1];
6091 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6092 QualType VaListTagArrayType
6093 = Context->getConstantArrayType(VaListTagTypedefType,
6094 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006095 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006096}
6097
6098static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6099 // typedef int __builtin_va_list[4];
6100 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6101 QualType IntArrayType
6102 = Context->getConstantArrayType(Context->IntTy,
6103 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006104 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006105}
6106
Logan Chien57086ce2012-10-10 06:56:20 +00006107static TypedefDecl *
6108CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006109 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006110 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006111 if (Context->getLangOpts().CPlusPlus) {
6112 // namespace std { struct __va_list {
6113 NamespaceDecl *NS;
6114 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6115 Context->getTranslationUnitDecl(),
6116 /*Inline*/false, SourceLocation(),
6117 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006118 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006119 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006120 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006121 }
6122
6123 VaListDecl->startDefinition();
6124
6125 // void * __ap;
6126 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6127 VaListDecl,
6128 SourceLocation(),
6129 SourceLocation(),
6130 &Context->Idents.get("__ap"),
6131 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006132 /*TInfo=*/nullptr,
6133 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006134 /*Mutable=*/false,
6135 ICIS_NoInit);
6136 Field->setAccess(AS_public);
6137 VaListDecl->addDecl(Field);
6138
6139 // };
6140 VaListDecl->completeDefinition();
6141
6142 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006143 QualType T = Context->getRecordType(VaListDecl);
6144 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006145}
6146
Ulrich Weigand47445072013-05-06 16:26:41 +00006147static TypedefDecl *
6148CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6149 // typedef struct __va_list_tag {
6150 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006151 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006152 VaListTagDecl->startDefinition();
6153
6154 const size_t NumFields = 4;
6155 QualType FieldTypes[NumFields];
6156 const char *FieldNames[NumFields];
6157
6158 // long __gpr;
6159 FieldTypes[0] = Context->LongTy;
6160 FieldNames[0] = "__gpr";
6161
6162 // long __fpr;
6163 FieldTypes[1] = Context->LongTy;
6164 FieldNames[1] = "__fpr";
6165
6166 // void *__overflow_arg_area;
6167 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6168 FieldNames[2] = "__overflow_arg_area";
6169
6170 // void *__reg_save_area;
6171 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6172 FieldNames[3] = "__reg_save_area";
6173
6174 // Create fields
6175 for (unsigned i = 0; i < NumFields; ++i) {
6176 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6177 VaListTagDecl,
6178 SourceLocation(),
6179 SourceLocation(),
6180 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006181 FieldTypes[i], /*TInfo=*/nullptr,
6182 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006183 /*Mutable=*/false,
6184 ICIS_NoInit);
6185 Field->setAccess(AS_public);
6186 VaListTagDecl->addDecl(Field);
6187 }
6188 VaListTagDecl->completeDefinition();
6189 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6190 Context->VaListTagTy = VaListTagType;
6191
6192 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006193 TypedefDecl *VaListTagTypedefDecl =
6194 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006195 QualType VaListTagTypedefType =
6196 Context->getTypedefType(VaListTagTypedefDecl);
6197
6198 // typedef __va_list_tag __builtin_va_list[1];
6199 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6200 QualType VaListTagArrayType
6201 = Context->getConstantArrayType(VaListTagTypedefType,
6202 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006203
Alp Toker56b5cc92013-12-15 10:36:26 +00006204 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006205}
6206
Meador Inge5d3fb222012-06-16 03:34:49 +00006207static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6208 TargetInfo::BuiltinVaListKind Kind) {
6209 switch (Kind) {
6210 case TargetInfo::CharPtrBuiltinVaList:
6211 return CreateCharPtrBuiltinVaListDecl(Context);
6212 case TargetInfo::VoidPtrBuiltinVaList:
6213 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006214 case TargetInfo::AArch64ABIBuiltinVaList:
6215 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006216 case TargetInfo::PowerABIBuiltinVaList:
6217 return CreatePowerABIBuiltinVaListDecl(Context);
6218 case TargetInfo::X86_64ABIBuiltinVaList:
6219 return CreateX86_64ABIBuiltinVaListDecl(Context);
6220 case TargetInfo::PNaClABIBuiltinVaList:
6221 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006222 case TargetInfo::AAPCSABIBuiltinVaList:
6223 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006224 case TargetInfo::SystemZBuiltinVaList:
6225 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006226 }
6227
6228 llvm_unreachable("Unhandled __builtin_va_list type kind");
6229}
6230
6231TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006232 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006233 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006234 assert(BuiltinVaListDecl->isImplicit());
6235 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006236
6237 return BuiltinVaListDecl;
6238}
6239
Meador Ingecfb60902012-07-01 15:57:25 +00006240QualType ASTContext::getVaListTagType() const {
6241 // Force the creation of VaListTagTy by building the __builtin_va_list
6242 // declaration.
6243 if (VaListTagTy.isNull())
6244 (void) getBuiltinVaListDecl();
6245
6246 return VaListTagTy;
6247}
6248
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006249void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006250 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006251 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006252
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006253 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006254}
6255
John McCalld28ae272009-12-02 08:04:21 +00006256/// \brief Retrieve the template name that corresponds to a non-empty
6257/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006258TemplateName
6259ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6260 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006261 unsigned size = End - Begin;
6262 assert(size > 1 && "set is not overloaded!");
6263
6264 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6265 size * sizeof(FunctionTemplateDecl*));
6266 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6267
6268 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006269 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006270 NamedDecl *D = *I;
6271 assert(isa<FunctionTemplateDecl>(D) ||
6272 (isa<UsingShadowDecl>(D) &&
6273 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6274 *Storage++ = D;
6275 }
6276
6277 return TemplateName(OT);
6278}
6279
Douglas Gregordc572a32009-03-30 22:58:21 +00006280/// \brief Retrieve the template name that represents a qualified
6281/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006282TemplateName
6283ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6284 bool TemplateKeyword,
6285 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006286 assert(NNS && "Missing nested-name-specifier in qualified template name");
6287
Douglas Gregorc42075a2010-02-04 18:10:26 +00006288 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006289 llvm::FoldingSetNodeID ID;
6290 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6291
Craig Topper36250ad2014-05-12 05:36:57 +00006292 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006293 QualifiedTemplateName *QTN =
6294 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6295 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006296 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6297 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006298 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6299 }
6300
6301 return TemplateName(QTN);
6302}
6303
6304/// \brief Retrieve the template name that represents a dependent
6305/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006306TemplateName
6307ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6308 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006309 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006310 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006311
6312 llvm::FoldingSetNodeID ID;
6313 DependentTemplateName::Profile(ID, NNS, Name);
6314
Craig Topper36250ad2014-05-12 05:36:57 +00006315 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006316 DependentTemplateName *QTN =
6317 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6318
6319 if (QTN)
6320 return TemplateName(QTN);
6321
6322 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6323 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006324 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6325 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006326 } else {
6327 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006328 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6329 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006330 DependentTemplateName *CheckQTN =
6331 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6332 assert(!CheckQTN && "Dependent type name canonicalization broken");
6333 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006334 }
6335
6336 DependentTemplateNames.InsertNode(QTN, InsertPos);
6337 return TemplateName(QTN);
6338}
6339
Douglas Gregor71395fa2009-11-04 00:56:37 +00006340/// \brief Retrieve the template name that represents a dependent
6341/// template name such as \c MetaFun::template operator+.
6342TemplateName
6343ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006344 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006345 assert((!NNS || NNS->isDependent()) &&
6346 "Nested name specifier must be dependent");
6347
6348 llvm::FoldingSetNodeID ID;
6349 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006350
6351 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006352 DependentTemplateName *QTN
6353 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006354
6355 if (QTN)
6356 return TemplateName(QTN);
6357
6358 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6359 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006360 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6361 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006362 } else {
6363 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006364 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6365 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006366
6367 DependentTemplateName *CheckQTN
6368 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6369 assert(!CheckQTN && "Dependent template name canonicalization broken");
6370 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006371 }
6372
6373 DependentTemplateNames.InsertNode(QTN, InsertPos);
6374 return TemplateName(QTN);
6375}
6376
Douglas Gregor5590be02011-01-15 06:45:20 +00006377TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006378ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6379 TemplateName replacement) const {
6380 llvm::FoldingSetNodeID ID;
6381 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006382
6383 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006384 SubstTemplateTemplateParmStorage *subst
6385 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6386
6387 if (!subst) {
6388 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6389 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6390 }
6391
6392 return TemplateName(subst);
6393}
6394
6395TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006396ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6397 const TemplateArgument &ArgPack) const {
6398 ASTContext &Self = const_cast<ASTContext &>(*this);
6399 llvm::FoldingSetNodeID ID;
6400 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006401
6402 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006403 SubstTemplateTemplateParmPackStorage *Subst
6404 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6405
6406 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006407 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006408 ArgPack.pack_size(),
6409 ArgPack.pack_begin());
6410 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6411 }
6412
6413 return TemplateName(Subst);
6414}
6415
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006416/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006417/// TargetInfo, produce the corresponding type. The unsigned @p Type
6418/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006419CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006420 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006421 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006422 case TargetInfo::SignedChar: return SignedCharTy;
6423 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006424 case TargetInfo::SignedShort: return ShortTy;
6425 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6426 case TargetInfo::SignedInt: return IntTy;
6427 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6428 case TargetInfo::SignedLong: return LongTy;
6429 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6430 case TargetInfo::SignedLongLong: return LongLongTy;
6431 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6432 }
6433
David Blaikie83d382b2011-09-23 05:06:16 +00006434 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006435}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006436
6437//===----------------------------------------------------------------------===//
6438// Type Predicates.
6439//===----------------------------------------------------------------------===//
6440
Fariborz Jahanian96207692009-02-18 21:49:28 +00006441/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6442/// garbage collection attribute.
6443///
John McCall553d45a2011-01-12 00:34:59 +00006444Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006445 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006446 return Qualifiers::GCNone;
6447
David Blaikiebbafb8a2012-03-11 07:00:24 +00006448 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006449 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6450
6451 // Default behaviour under objective-C's gc is for ObjC pointers
6452 // (or pointers to them) be treated as though they were declared
6453 // as __strong.
6454 if (GCAttrs == Qualifiers::GCNone) {
6455 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6456 return Qualifiers::Strong;
6457 else if (Ty->isPointerType())
6458 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6459 } else {
6460 // It's not valid to set GC attributes on anything that isn't a
6461 // pointer.
6462#ifndef NDEBUG
6463 QualType CT = Ty->getCanonicalTypeInternal();
6464 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6465 CT = AT->getElementType();
6466 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6467#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006468 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006469 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006470}
6471
Chris Lattner49af6a42008-04-07 06:51:04 +00006472//===----------------------------------------------------------------------===//
6473// Type Compatibility Testing
6474//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006475
Mike Stump11289f42009-09-09 15:08:12 +00006476/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006477/// compatible.
6478static bool areCompatVectorTypes(const VectorType *LHS,
6479 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006480 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006481 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006482 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006483}
6484
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006485bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6486 QualType SecondVec) {
6487 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6488 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6489
6490 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6491 return true;
6492
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006493 // Treat Neon vector types and most AltiVec vector types as if they are the
6494 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006495 const VectorType *First = FirstVec->getAs<VectorType>();
6496 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006497 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006498 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006499 First->getVectorKind() != VectorType::AltiVecPixel &&
6500 First->getVectorKind() != VectorType::AltiVecBool &&
6501 Second->getVectorKind() != VectorType::AltiVecPixel &&
6502 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006503 return true;
6504
6505 return false;
6506}
6507
Steve Naroff8e6aee52009-07-23 01:01:38 +00006508//===----------------------------------------------------------------------===//
6509// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6510//===----------------------------------------------------------------------===//
6511
6512/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6513/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006514bool
6515ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6516 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006517 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006518 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006519 for (auto *PI : rProto->protocols())
6520 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006521 return true;
6522 return false;
6523}
6524
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006525/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6526/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006527bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6528 QualType rhs) {
6529 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6530 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6531 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6532
Aaron Ballman83731462014-03-17 16:14:00 +00006533 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006534 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006535 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006536 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6537 match = true;
6538 break;
6539 }
6540 }
6541 if (!match)
6542 return false;
6543 }
6544 return true;
6545}
6546
Steve Naroff8e6aee52009-07-23 01:01:38 +00006547/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6548/// ObjCQualifiedIDType.
6549bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6550 bool compare) {
6551 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006552 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006553 lhs->isObjCIdType() || lhs->isObjCClassType())
6554 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006555 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006556 rhs->isObjCIdType() || rhs->isObjCClassType())
6557 return true;
6558
6559 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006560 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006561
Steve Naroff8e6aee52009-07-23 01:01:38 +00006562 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006563
Steve Naroff8e6aee52009-07-23 01:01:38 +00006564 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006565 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006566 // make sure we check the class hierarchy.
6567 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006568 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006569 // when comparing an id<P> on lhs with a static type on rhs,
6570 // see if static class implements all of id's protocols, directly or
6571 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006572 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006573 return false;
6574 }
6575 }
6576 // If there are no qualifiers and no interface, we have an 'id'.
6577 return true;
6578 }
Mike Stump11289f42009-09-09 15:08:12 +00006579 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006580 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006581 bool match = false;
6582
6583 // when comparing an id<P> on lhs with a static type on rhs,
6584 // see if static class implements all of id's protocols, directly or
6585 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006586 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006587 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6588 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6589 match = true;
6590 break;
6591 }
6592 }
Mike Stump11289f42009-09-09 15:08:12 +00006593 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006594 // make sure we check the class hierarchy.
6595 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006596 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006597 // when comparing an id<P> on lhs with a static type on rhs,
6598 // see if static class implements all of id's protocols, directly or
6599 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006600 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006601 match = true;
6602 break;
6603 }
6604 }
6605 }
6606 if (!match)
6607 return false;
6608 }
Mike Stump11289f42009-09-09 15:08:12 +00006609
Steve Naroff8e6aee52009-07-23 01:01:38 +00006610 return true;
6611 }
Mike Stump11289f42009-09-09 15:08:12 +00006612
Steve Naroff8e6aee52009-07-23 01:01:38 +00006613 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6614 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6615
Mike Stump11289f42009-09-09 15:08:12 +00006616 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006617 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006618 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006619 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006620 bool match = false;
6621
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006622 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006623 // see if static class implements all of id's protocols, directly or
6624 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006625 // First, lhs protocols in the qualifier list must be found, direct
6626 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006627 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006628 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6629 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6630 match = true;
6631 break;
6632 }
6633 }
6634 if (!match)
6635 return false;
6636 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006637
6638 // Static class's protocols, or its super class or category protocols
6639 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6640 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6641 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6642 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6643 // This is rather dubious but matches gcc's behavior. If lhs has
6644 // no type qualifier and its class has no static protocol(s)
6645 // assume that it is mismatch.
6646 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6647 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006648 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006649 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006650 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006651 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6652 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6653 match = true;
6654 break;
6655 }
6656 }
6657 if (!match)
6658 return false;
6659 }
6660 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006661 return true;
6662 }
6663 return false;
6664}
6665
Eli Friedman47f77112008-08-22 00:56:42 +00006666/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006667/// compatible for assignment from RHS to LHS. This handles validation of any
6668/// protocol qualifiers on the LHS or RHS.
6669///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006670bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6671 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006672 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6673 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6674
Steve Naroff1329fa02009-07-15 18:40:39 +00006675 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006676 if (LHS->isObjCUnqualifiedIdOrClass() ||
6677 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006678 return true;
6679
John McCall8b07ec22010-05-15 11:32:37 +00006680 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006681 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6682 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006683 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006684
6685 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6686 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6687 QualType(RHSOPT,0));
6688
John McCall8b07ec22010-05-15 11:32:37 +00006689 // If we have 2 user-defined types, fall into that path.
6690 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006691 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006692
Steve Naroff8e6aee52009-07-23 01:01:38 +00006693 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006694}
6695
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006696/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006697/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006698/// arguments in block literals. When passed as arguments, passing 'A*' where
6699/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6700/// not OK. For the return type, the opposite is not OK.
6701bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6702 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006703 const ObjCObjectPointerType *RHSOPT,
6704 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006705 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006706 return true;
6707
6708 if (LHSOPT->isObjCBuiltinType()) {
6709 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6710 }
6711
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006712 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006713 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6714 QualType(RHSOPT,0),
6715 false);
6716
6717 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6718 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6719 if (LHS && RHS) { // We have 2 user-defined types.
6720 if (LHS != RHS) {
6721 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006722 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006723 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006724 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006725 }
6726 else
6727 return true;
6728 }
6729 return false;
6730}
6731
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006732/// getIntersectionOfProtocols - This routine finds the intersection of set
6733/// of protocols inherited from two distinct objective-c pointer objects.
6734/// It is used to build composite qualifier list of the composite type of
6735/// the conditional expression involving two objective-c pointer objects.
6736static
6737void getIntersectionOfProtocols(ASTContext &Context,
6738 const ObjCObjectPointerType *LHSOPT,
6739 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006740 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006741
John McCall8b07ec22010-05-15 11:32:37 +00006742 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6743 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6744 assert(LHS->getInterface() && "LHS must have an interface base");
6745 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006746
6747 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6748 unsigned LHSNumProtocols = LHS->getNumProtocols();
6749 if (LHSNumProtocols > 0)
6750 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6751 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006752 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006753 Context.CollectInheritedProtocols(LHS->getInterface(),
6754 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006755 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6756 LHSInheritedProtocols.end());
6757 }
6758
6759 unsigned RHSNumProtocols = RHS->getNumProtocols();
6760 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006761 ObjCProtocolDecl **RHSProtocols =
6762 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006763 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6764 if (InheritedProtocolSet.count(RHSProtocols[i]))
6765 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006766 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006767 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006768 Context.CollectInheritedProtocols(RHS->getInterface(),
6769 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006770 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6771 if (InheritedProtocolSet.count(ProtDecl))
6772 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006773 }
6774}
6775
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006776/// areCommonBaseCompatible - Returns common base class of the two classes if
6777/// one found. Note that this is O'2 algorithm. But it will be called as the
6778/// last type comparison in a ?-exp of ObjC pointer types before a
6779/// warning is issued. So, its invokation is extremely rare.
6780QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006781 const ObjCObjectPointerType *Lptr,
6782 const ObjCObjectPointerType *Rptr) {
6783 const ObjCObjectType *LHS = Lptr->getObjectType();
6784 const ObjCObjectType *RHS = Rptr->getObjectType();
6785 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6786 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006787 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006788 return QualType();
6789
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006790 do {
John McCall8b07ec22010-05-15 11:32:37 +00006791 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006792 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006793 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006794 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6795
6796 QualType Result = QualType(LHS, 0);
6797 if (!Protocols.empty())
6798 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6799 Result = getObjCObjectPointerType(Result);
6800 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006801 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006802 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006803
6804 return QualType();
6805}
6806
John McCall8b07ec22010-05-15 11:32:37 +00006807bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6808 const ObjCObjectType *RHS) {
6809 assert(LHS->getInterface() && "LHS is not an interface type");
6810 assert(RHS->getInterface() && "RHS is not an interface type");
6811
Chris Lattner49af6a42008-04-07 06:51:04 +00006812 // Verify that the base decls are compatible: the RHS must be a subclass of
6813 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006814 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006815 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006816
Chris Lattner49af6a42008-04-07 06:51:04 +00006817 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6818 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006819 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006820 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006821
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006822 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6823 // More detailed analysis is required.
6824 // OK, if LHS is same or a superclass of RHS *and*
6825 // this LHS, or as RHS's super class is assignment compatible with LHS.
6826 bool IsSuperClass =
6827 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6828 if (IsSuperClass) {
6829 // OK if conversion of LHS to SuperClass results in narrowing of types
6830 // ; i.e., SuperClass may implement at least one of the protocols
6831 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6832 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6833 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6834 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6835 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6836 // qualifiers.
6837 for (auto *RHSPI : RHS->quals())
6838 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6839 // If there is no protocols associated with RHS, it is not a match.
6840 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006841 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006842
6843 for (const auto *LHSProto : LHS->quals()) {
6844 bool SuperImplementsProtocol = false;
6845 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6846 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6847 SuperImplementsProtocol = true;
6848 break;
6849 }
6850 if (!SuperImplementsProtocol)
6851 return false;
6852 }
6853 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006854 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006855 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006856}
6857
Steve Naroffb7605152009-02-12 17:52:19 +00006858bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6859 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006860 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6861 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006862
Steve Naroff7cae42b2009-07-10 23:34:53 +00006863 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006864 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006865
6866 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6867 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006868}
6869
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006870bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6871 return canAssignObjCInterfaces(
6872 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6873 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6874}
6875
Mike Stump11289f42009-09-09 15:08:12 +00006876/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006877/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006878/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006879/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006880bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6881 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006882 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006883 return hasSameType(LHS, RHS);
6884
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006885 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006886}
6887
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006888bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006889 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006890}
6891
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006892bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6893 return !mergeTypes(LHS, RHS, true).isNull();
6894}
6895
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006896/// mergeTransparentUnionType - if T is a transparent union type and a member
6897/// of T is compatible with SubType, return the merged type, else return
6898/// QualType()
6899QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6900 bool OfBlockPointer,
6901 bool Unqualified) {
6902 if (const RecordType *UT = T->getAsUnionType()) {
6903 RecordDecl *UD = UT->getDecl();
6904 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006905 for (const auto *I : UD->fields()) {
6906 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006907 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6908 if (!MT.isNull())
6909 return MT;
6910 }
6911 }
6912 }
6913
6914 return QualType();
6915}
6916
Alp Toker9cacbab2014-01-20 20:26:09 +00006917/// mergeFunctionParameterTypes - merge two types which appear as function
6918/// parameter types
6919QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6920 bool OfBlockPointer,
6921 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006922 // GNU extension: two types are compatible if they appear as a function
6923 // argument, one of the types is a transparent union type and the other
6924 // type is compatible with a union member
6925 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6926 Unqualified);
6927 if (!lmerge.isNull())
6928 return lmerge;
6929
6930 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6931 Unqualified);
6932 if (!rmerge.isNull())
6933 return rmerge;
6934
6935 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6936}
6937
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006938QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006939 bool OfBlockPointer,
6940 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006941 const FunctionType *lbase = lhs->getAs<FunctionType>();
6942 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006943 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6944 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006945 bool allLTypes = true;
6946 bool allRTypes = true;
6947
6948 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006949 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006950 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006951 QualType RHS = rbase->getReturnType();
6952 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006953 bool UnqualifiedResult = Unqualified;
6954 if (!UnqualifiedResult)
6955 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006956 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006957 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006958 else
Alp Toker314cc812014-01-25 16:55:45 +00006959 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006960 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006961 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006962
6963 if (Unqualified)
6964 retType = retType.getUnqualifiedType();
6965
Alp Toker314cc812014-01-25 16:55:45 +00006966 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6967 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006968 if (Unqualified) {
6969 LRetType = LRetType.getUnqualifiedType();
6970 RRetType = RRetType.getUnqualifiedType();
6971 }
6972
6973 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006974 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006975 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006976 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006977
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006978 // FIXME: double check this
6979 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6980 // rbase->getRegParmAttr() != 0 &&
6981 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006982 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6983 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006984
Douglas Gregor8c940862010-01-18 17:14:39 +00006985 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006986 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006987 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006988
John McCall8c6b56f2010-12-15 01:06:38 +00006989 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006990 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6991 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006992 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6993 return QualType();
6994
John McCall31168b02011-06-15 23:02:42 +00006995 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6996 return QualType();
6997
John McCall8c6b56f2010-12-15 01:06:38 +00006998 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6999 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007000
Rafael Espindola8778c282012-11-29 16:09:03 +00007001 if (lbaseInfo.getNoReturn() != NoReturn)
7002 allLTypes = false;
7003 if (rbaseInfo.getNoReturn() != NoReturn)
7004 allRTypes = false;
7005
John McCall31168b02011-06-15 23:02:42 +00007006 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007007
Eli Friedman47f77112008-08-22 00:56:42 +00007008 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007009 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7010 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007011 // Compatible functions must have the same number of parameters
7012 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007013 return QualType();
7014
7015 // Variadic and non-variadic functions aren't compatible
7016 if (lproto->isVariadic() != rproto->isVariadic())
7017 return QualType();
7018
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007019 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7020 return QualType();
7021
Fariborz Jahanian97676972011-09-28 21:52:05 +00007022 if (LangOpts.ObjCAutoRefCount &&
7023 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7024 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007025
7026 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007027 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007028 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7029 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7030 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7031 QualType paramType = mergeFunctionParameterTypes(
7032 lParamType, rParamType, OfBlockPointer, Unqualified);
7033 if (paramType.isNull())
7034 return QualType();
7035
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007036 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007037 paramType = paramType.getUnqualifiedType();
7038
7039 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007040 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007041 lParamType = lParamType.getUnqualifiedType();
7042 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007043 }
Alp Toker601b22c2014-01-21 23:35:24 +00007044
7045 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007046 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007047 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007048 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007049 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007050
Eli Friedman47f77112008-08-22 00:56:42 +00007051 if (allLTypes) return lhs;
7052 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007053
7054 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7055 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007056 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007057 }
7058
7059 if (lproto) allRTypes = false;
7060 if (rproto) allLTypes = false;
7061
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007062 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007063 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007064 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007065 if (proto->isVariadic()) return QualType();
7066 // Check that the types are compatible with the types that
7067 // would result from default argument promotions (C99 6.7.5.3p15).
7068 // The only types actually affected are promotable integer
7069 // types and floats, which would be passed as a different
7070 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007071 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7072 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007073
Eli Friedman448ce402012-08-30 00:44:15 +00007074 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007075 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007076 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7077 paramTy = Enum->getDecl()->getIntegerType();
7078 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007079 return QualType();
7080 }
Alp Toker601b22c2014-01-21 23:35:24 +00007081
7082 if (paramTy->isPromotableIntegerType() ||
7083 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007084 return QualType();
7085 }
7086
7087 if (allLTypes) return lhs;
7088 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007089
7090 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7091 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007092 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007093 }
7094
7095 if (allLTypes) return lhs;
7096 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007097 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007098}
7099
John McCall433c2e62013-03-21 00:10:07 +00007100/// Given that we have an enum type and a non-enum type, try to merge them.
7101static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7102 QualType other, bool isBlockReturnType) {
7103 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7104 // a signed integer type, or an unsigned integer type.
7105 // Compatibility is based on the underlying type, not the promotion
7106 // type.
7107 QualType underlyingType = ET->getDecl()->getIntegerType();
7108 if (underlyingType.isNull()) return QualType();
7109 if (Context.hasSameType(underlyingType, other))
7110 return other;
7111
7112 // In block return types, we're more permissive and accept any
7113 // integral type of the same size.
7114 if (isBlockReturnType && other->isIntegerType() &&
7115 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7116 return other;
7117
7118 return QualType();
7119}
7120
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007121QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007122 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007123 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007124 // C++ [expr]: If an expression initially has the type "reference to T", the
7125 // type is adjusted to "T" prior to any further analysis, the expression
7126 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007127 // expression is an lvalue unless the reference is an rvalue reference and
7128 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007129 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7130 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007131
7132 if (Unqualified) {
7133 LHS = LHS.getUnqualifiedType();
7134 RHS = RHS.getUnqualifiedType();
7135 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007136
Eli Friedman47f77112008-08-22 00:56:42 +00007137 QualType LHSCan = getCanonicalType(LHS),
7138 RHSCan = getCanonicalType(RHS);
7139
7140 // If two types are identical, they are compatible.
7141 if (LHSCan == RHSCan)
7142 return LHS;
7143
John McCall8ccfcb52009-09-24 19:53:00 +00007144 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007145 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7146 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007147 if (LQuals != RQuals) {
7148 // If any of these qualifiers are different, we have a type
7149 // mismatch.
7150 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007151 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7152 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007153 return QualType();
7154
7155 // Exactly one GC qualifier difference is allowed: __strong is
7156 // okay if the other type has no GC qualifier but is an Objective
7157 // C object pointer (i.e. implicitly strong by default). We fix
7158 // this by pretending that the unqualified type was actually
7159 // qualified __strong.
7160 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7161 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7162 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7163
7164 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7165 return QualType();
7166
7167 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7168 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7169 }
7170 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7171 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7172 }
Eli Friedman47f77112008-08-22 00:56:42 +00007173 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007174 }
7175
7176 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007177
Eli Friedmandcca6332009-06-01 01:22:52 +00007178 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7179 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007180
Chris Lattnerfd652912008-01-14 05:45:46 +00007181 // We want to consider the two function types to be the same for these
7182 // comparisons, just force one to the other.
7183 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7184 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007185
7186 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007187 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7188 LHSClass = Type::ConstantArray;
7189 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7190 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007191
John McCall8b07ec22010-05-15 11:32:37 +00007192 // ObjCInterfaces are just specialized ObjCObjects.
7193 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7194 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7195
Nate Begemance4d7fc2008-04-18 23:10:10 +00007196 // Canonicalize ExtVector -> Vector.
7197 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7198 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007199
Chris Lattner95554662008-04-07 05:43:21 +00007200 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007201 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007202 // Note that we only have special rules for turning block enum
7203 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007204 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007205 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007206 }
John McCall9dd450b2009-09-21 23:43:11 +00007207 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007208 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007209 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007210 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007211 if (OfBlockPointer && !BlockReturnType) {
7212 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7213 return LHS;
7214 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7215 return RHS;
7216 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007217
Eli Friedman47f77112008-08-22 00:56:42 +00007218 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007219 }
Eli Friedman47f77112008-08-22 00:56:42 +00007220
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007221 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007222 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007223#define TYPE(Class, Base)
7224#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007225#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007226#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7227#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7228#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007229 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007230
Richard Smith27d807c2013-04-30 13:56:41 +00007231 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007232 case Type::LValueReference:
7233 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007234 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007235 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007236
John McCall8b07ec22010-05-15 11:32:37 +00007237 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007238 case Type::IncompleteArray:
7239 case Type::VariableArray:
7240 case Type::FunctionProto:
7241 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007242 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007243
Chris Lattnerfd652912008-01-14 05:45:46 +00007244 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007245 {
7246 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007247 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7248 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007249 if (Unqualified) {
7250 LHSPointee = LHSPointee.getUnqualifiedType();
7251 RHSPointee = RHSPointee.getUnqualifiedType();
7252 }
7253 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7254 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007255 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007256 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007257 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007258 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007259 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007260 return getPointerType(ResultType);
7261 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007262 case Type::BlockPointer:
7263 {
7264 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007265 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7266 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007267 if (Unqualified) {
7268 LHSPointee = LHSPointee.getUnqualifiedType();
7269 RHSPointee = RHSPointee.getUnqualifiedType();
7270 }
7271 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7272 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007273 if (ResultType.isNull()) return QualType();
7274 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7275 return LHS;
7276 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7277 return RHS;
7278 return getBlockPointerType(ResultType);
7279 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007280 case Type::Atomic:
7281 {
7282 // Merge two pointer types, while trying to preserve typedef info
7283 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7284 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7285 if (Unqualified) {
7286 LHSValue = LHSValue.getUnqualifiedType();
7287 RHSValue = RHSValue.getUnqualifiedType();
7288 }
7289 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7290 Unqualified);
7291 if (ResultType.isNull()) return QualType();
7292 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7293 return LHS;
7294 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7295 return RHS;
7296 return getAtomicType(ResultType);
7297 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007298 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007299 {
7300 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7301 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7302 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7303 return QualType();
7304
7305 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7306 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007307 if (Unqualified) {
7308 LHSElem = LHSElem.getUnqualifiedType();
7309 RHSElem = RHSElem.getUnqualifiedType();
7310 }
7311
7312 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007313 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007314 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7315 return LHS;
7316 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7317 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007318 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7319 ArrayType::ArraySizeModifier(), 0);
7320 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7321 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007322 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7323 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007324 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7325 return LHS;
7326 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7327 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007328 if (LVAT) {
7329 // FIXME: This isn't correct! But tricky to implement because
7330 // the array's size has to be the size of LHS, but the type
7331 // has to be different.
7332 return LHS;
7333 }
7334 if (RVAT) {
7335 // FIXME: This isn't correct! But tricky to implement because
7336 // the array's size has to be the size of RHS, but the type
7337 // has to be different.
7338 return RHS;
7339 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007340 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7341 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007342 return getIncompleteArrayType(ResultType,
7343 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007344 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007345 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007346 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007347 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007348 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007349 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007350 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007351 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007352 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007353 case Type::Complex:
7354 // Distinct complex types are incompatible.
7355 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007356 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007357 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007358 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7359 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007360 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007361 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007362 case Type::ObjCObject: {
7363 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007364 // FIXME: This should be type compatibility, e.g. whether
7365 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007366 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7367 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7368 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007369 return LHS;
7370
Eli Friedman47f77112008-08-22 00:56:42 +00007371 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007372 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007373 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007374 if (OfBlockPointer) {
7375 if (canAssignObjCInterfacesInBlockPointer(
7376 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007377 RHS->getAs<ObjCObjectPointerType>(),
7378 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007379 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007380 return QualType();
7381 }
John McCall9dd450b2009-09-21 23:43:11 +00007382 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7383 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007384 return LHS;
7385
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007386 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007387 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007388 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007389
David Blaikie8a40f702012-01-17 06:56:22 +00007390 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007391}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007392
Fariborz Jahanian97676972011-09-28 21:52:05 +00007393bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7394 const FunctionProtoType *FromFunctionType,
7395 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007396 if (FromFunctionType->hasAnyConsumedParams() !=
7397 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007398 return false;
7399 FunctionProtoType::ExtProtoInfo FromEPI =
7400 FromFunctionType->getExtProtoInfo();
7401 FunctionProtoType::ExtProtoInfo ToEPI =
7402 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007403 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007404 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7405 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007406 return false;
7407 }
7408 return true;
7409}
7410
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007411/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7412/// 'RHS' attributes and returns the merged version; including for function
7413/// return types.
7414QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7415 QualType LHSCan = getCanonicalType(LHS),
7416 RHSCan = getCanonicalType(RHS);
7417 // If two types are identical, they are compatible.
7418 if (LHSCan == RHSCan)
7419 return LHS;
7420 if (RHSCan->isFunctionType()) {
7421 if (!LHSCan->isFunctionType())
7422 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007423 QualType OldReturnType =
7424 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007425 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007426 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007427 QualType ResReturnType =
7428 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7429 if (ResReturnType.isNull())
7430 return QualType();
7431 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7432 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7433 // In either case, use OldReturnType to build the new function type.
7434 const FunctionType *F = LHS->getAs<FunctionType>();
7435 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007436 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7437 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007438 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007439 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007440 return ResultType;
7441 }
7442 }
7443 return QualType();
7444 }
7445
7446 // If the qualifiers are different, the types can still be merged.
7447 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7448 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7449 if (LQuals != RQuals) {
7450 // If any of these qualifiers are different, we have a type mismatch.
7451 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7452 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7453 return QualType();
7454
7455 // Exactly one GC qualifier difference is allowed: __strong is
7456 // okay if the other type has no GC qualifier but is an Objective
7457 // C object pointer (i.e. implicitly strong by default). We fix
7458 // this by pretending that the unqualified type was actually
7459 // qualified __strong.
7460 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7461 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7462 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7463
7464 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7465 return QualType();
7466
7467 if (GC_L == Qualifiers::Strong)
7468 return LHS;
7469 if (GC_R == Qualifiers::Strong)
7470 return RHS;
7471 return QualType();
7472 }
7473
7474 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7475 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7476 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7477 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7478 if (ResQT == LHSBaseQT)
7479 return LHS;
7480 if (ResQT == RHSBaseQT)
7481 return RHS;
7482 }
7483 return QualType();
7484}
7485
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007486//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007487// Integer Predicates
7488//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007489
Jay Foad39c79802011-01-12 09:06:06 +00007490unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007491 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007492 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007493 if (T->isBooleanType())
7494 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007495 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007496 return (unsigned)getTypeSize(T);
7497}
7498
Abramo Bagnara13640492012-09-09 10:21:24 +00007499QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007500 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007501
7502 // Turn <4 x signed int> -> <4 x unsigned int>
7503 if (const VectorType *VTy = T->getAs<VectorType>())
7504 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007505 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007506
7507 // For enums, we return the unsigned version of the base type.
7508 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007509 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007510
7511 const BuiltinType *BTy = T->getAs<BuiltinType>();
7512 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007513 switch (BTy->getKind()) {
7514 case BuiltinType::Char_S:
7515 case BuiltinType::SChar:
7516 return UnsignedCharTy;
7517 case BuiltinType::Short:
7518 return UnsignedShortTy;
7519 case BuiltinType::Int:
7520 return UnsignedIntTy;
7521 case BuiltinType::Long:
7522 return UnsignedLongTy;
7523 case BuiltinType::LongLong:
7524 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007525 case BuiltinType::Int128:
7526 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007527 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007528 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007529 }
7530}
7531
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007532ASTMutationListener::~ASTMutationListener() { }
7533
Richard Smith1fa5d642013-05-11 05:45:24 +00007534void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7535 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007536
7537//===----------------------------------------------------------------------===//
7538// Builtin Type Computation
7539//===----------------------------------------------------------------------===//
7540
7541/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007542/// pointer over the consumed characters. This returns the resultant type. If
7543/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7544/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7545/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007546///
7547/// RequiresICE is filled in on return to indicate whether the value is required
7548/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007549static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007550 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007551 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007552 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007553 // Modifiers.
7554 int HowLong = 0;
7555 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007556 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007557
Chris Lattnerdc226c22010-10-01 22:42:38 +00007558 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007559 bool Done = false;
7560 while (!Done) {
7561 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007562 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007563 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007564 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007565 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007566 case 'S':
7567 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7568 assert(!Signed && "Can't use 'S' modifier multiple times!");
7569 Signed = true;
7570 break;
7571 case 'U':
7572 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007573 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007574 Unsigned = true;
7575 break;
7576 case 'L':
7577 assert(HowLong <= 2 && "Can't have LLLL modifier");
7578 ++HowLong;
7579 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007580 case 'W':
7581 // This modifier represents int64 type.
7582 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7583 switch (Context.getTargetInfo().getInt64Type()) {
7584 default:
7585 llvm_unreachable("Unexpected integer type");
7586 case TargetInfo::SignedLong:
7587 HowLong = 1;
7588 break;
7589 case TargetInfo::SignedLongLong:
7590 HowLong = 2;
7591 break;
7592 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007593 }
7594 }
7595
7596 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007597
Chris Lattnerecd79c62009-06-14 00:45:47 +00007598 // Read the base type.
7599 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007600 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007601 case 'v':
7602 assert(HowLong == 0 && !Signed && !Unsigned &&
7603 "Bad modifiers used with 'v'!");
7604 Type = Context.VoidTy;
7605 break;
Jack Carter24bef982013-08-15 15:16:57 +00007606 case 'h':
7607 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007608 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007609 Type = Context.HalfTy;
7610 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007611 case 'f':
7612 assert(HowLong == 0 && !Signed && !Unsigned &&
7613 "Bad modifiers used with 'f'!");
7614 Type = Context.FloatTy;
7615 break;
7616 case 'd':
7617 assert(HowLong < 2 && !Signed && !Unsigned &&
7618 "Bad modifiers used with 'd'!");
7619 if (HowLong)
7620 Type = Context.LongDoubleTy;
7621 else
7622 Type = Context.DoubleTy;
7623 break;
7624 case 's':
7625 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7626 if (Unsigned)
7627 Type = Context.UnsignedShortTy;
7628 else
7629 Type = Context.ShortTy;
7630 break;
7631 case 'i':
7632 if (HowLong == 3)
7633 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7634 else if (HowLong == 2)
7635 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7636 else if (HowLong == 1)
7637 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7638 else
7639 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7640 break;
7641 case 'c':
7642 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7643 if (Signed)
7644 Type = Context.SignedCharTy;
7645 else if (Unsigned)
7646 Type = Context.UnsignedCharTy;
7647 else
7648 Type = Context.CharTy;
7649 break;
7650 case 'b': // boolean
7651 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7652 Type = Context.BoolTy;
7653 break;
7654 case 'z': // size_t.
7655 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7656 Type = Context.getSizeType();
7657 break;
7658 case 'F':
7659 Type = Context.getCFConstantStringType();
7660 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007661 case 'G':
7662 Type = Context.getObjCIdType();
7663 break;
7664 case 'H':
7665 Type = Context.getObjCSelType();
7666 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007667 case 'M':
7668 Type = Context.getObjCSuperType();
7669 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007670 case 'a':
7671 Type = Context.getBuiltinVaListType();
7672 assert(!Type.isNull() && "builtin va list type not initialized!");
7673 break;
7674 case 'A':
7675 // This is a "reference" to a va_list; however, what exactly
7676 // this means depends on how va_list is defined. There are two
7677 // different kinds of va_list: ones passed by value, and ones
7678 // passed by reference. An example of a by-value va_list is
7679 // x86, where va_list is a char*. An example of by-ref va_list
7680 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7681 // we want this argument to be a char*&; for x86-64, we want
7682 // it to be a __va_list_tag*.
7683 Type = Context.getBuiltinVaListType();
7684 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007685 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007686 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007687 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007688 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007689 break;
7690 case 'V': {
7691 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007692 unsigned NumElements = strtoul(Str, &End, 10);
7693 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007694 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007695
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007696 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7697 RequiresICE, false);
7698 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007699
7700 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007701 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007702 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007703 break;
7704 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007705 case 'E': {
7706 char *End;
7707
7708 unsigned NumElements = strtoul(Str, &End, 10);
7709 assert(End != Str && "Missing vector size");
7710
7711 Str = End;
7712
7713 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7714 false);
7715 Type = Context.getExtVectorType(ElementType, NumElements);
7716 break;
7717 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007718 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007719 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7720 false);
7721 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007722 Type = Context.getComplexType(ElementType);
7723 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007724 }
7725 case 'Y' : {
7726 Type = Context.getPointerDiffType();
7727 break;
7728 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007729 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007730 Type = Context.getFILEType();
7731 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007732 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007733 return QualType();
7734 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007735 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007736 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007737 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007738 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007739 else
7740 Type = Context.getjmp_bufType();
7741
Mike Stump2adb4da2009-07-28 23:47:15 +00007742 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007743 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007744 return QualType();
7745 }
7746 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007747 case 'K':
7748 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7749 Type = Context.getucontext_tType();
7750
7751 if (Type.isNull()) {
7752 Error = ASTContext::GE_Missing_ucontext;
7753 return QualType();
7754 }
7755 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007756 case 'p':
7757 Type = Context.getProcessIDType();
7758 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007759 }
Mike Stump11289f42009-09-09 15:08:12 +00007760
Chris Lattnerdc226c22010-10-01 22:42:38 +00007761 // If there are modifiers and if we're allowed to parse them, go for it.
7762 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007763 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007764 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007765 default: Done = true; --Str; break;
7766 case '*':
7767 case '&': {
7768 // Both pointers and references can have their pointee types
7769 // qualified with an address space.
7770 char *End;
7771 unsigned AddrSpace = strtoul(Str, &End, 10);
7772 if (End != Str && AddrSpace != 0) {
7773 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7774 Str = End;
7775 }
7776 if (c == '*')
7777 Type = Context.getPointerType(Type);
7778 else
7779 Type = Context.getLValueReferenceType(Type);
7780 break;
7781 }
7782 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7783 case 'C':
7784 Type = Type.withConst();
7785 break;
7786 case 'D':
7787 Type = Context.getVolatileType(Type);
7788 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007789 case 'R':
7790 Type = Type.withRestrict();
7791 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007792 }
7793 }
Chris Lattner84733392010-10-01 07:13:18 +00007794
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007795 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007796 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007797
Chris Lattnerecd79c62009-06-14 00:45:47 +00007798 return Type;
7799}
7800
7801/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007802QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007803 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007804 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007805 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007806
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007807 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007808
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007809 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007810 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007811 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7812 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007813 if (Error != GE_None)
7814 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007815
7816 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7817
Chris Lattnerecd79c62009-06-14 00:45:47 +00007818 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007819 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007820 if (Error != GE_None)
7821 return QualType();
7822
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007823 // If this argument is required to be an IntegerConstantExpression and the
7824 // caller cares, fill in the bitmask we return.
7825 if (RequiresICE && IntegerConstantArgs)
7826 *IntegerConstantArgs |= 1 << ArgTypes.size();
7827
Chris Lattnerecd79c62009-06-14 00:45:47 +00007828 // Do array -> pointer decay. The builtin should use the decayed type.
7829 if (Ty->isArrayType())
7830 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007831
Chris Lattnerecd79c62009-06-14 00:45:47 +00007832 ArgTypes.push_back(Ty);
7833 }
7834
7835 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7836 "'.' should only occur at end of builtin type list!");
7837
Reid Kleckner78af0702013-08-27 23:08:25 +00007838 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007839 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7840
7841 bool Variadic = (TypeStr[0] == '.');
7842
7843 // We really shouldn't be making a no-proto type here, especially in C++.
7844 if (ArgTypes.empty() && Variadic)
7845 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007846
John McCalldb40c7f2010-12-14 08:05:40 +00007847 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007848 EPI.ExtInfo = EI;
7849 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007850
Jordan Rose5c382722013-03-08 21:51:21 +00007851 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007852}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007853
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007854static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7855 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007856 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007857 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007858
Rafael Espindola3ae00052013-05-13 00:12:11 +00007859 GVALinkage External = GVA_StrongExternal;
7860 switch (FD->getTemplateSpecializationKind()) {
7861 case TSK_Undeclared:
7862 case TSK_ExplicitSpecialization:
7863 External = GVA_StrongExternal;
7864 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007865
Rafael Espindola3ae00052013-05-13 00:12:11 +00007866 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007867 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007868
David Majnemerc3d07332014-05-15 06:25:57 +00007869 // C++11 [temp.explicit]p10:
7870 // [ Note: The intent is that an inline function that is the subject of
7871 // an explicit instantiation declaration will still be implicitly
7872 // instantiated when used so that the body can be considered for
7873 // inlining, but that no out-of-line copy of the inline function would be
7874 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007875 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007876 return GVA_AvailableExternally;
7877
Rafael Espindola3ae00052013-05-13 00:12:11 +00007878 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007879 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007880 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007881 }
7882
7883 if (!FD->isInlined())
7884 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007885
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007886 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7887 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007888 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007889 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7890
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007891 // GNU or C99 inline semantics. Determine whether this symbol should be
7892 // externally visible.
7893 if (FD->isInlineDefinitionExternallyVisible())
7894 return External;
7895
7896 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007897 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007898 }
7899
David Majnemer54e3ba52014-04-02 23:17:29 +00007900 // Functions specified with extern and inline in -fms-compatibility mode
7901 // forcibly get emitted. While the body of the function cannot be later
7902 // replaced, the function definition cannot be discarded.
7903 if (FD->getMostRecentDecl()->isMSExternInline())
7904 return GVA_StrongODR;
7905
David Majnemer27d69db2014-04-28 22:17:59 +00007906 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007907}
7908
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007909static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7910 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7911 // dllexport/dllimport on inline functions.
7912 if (D->hasAttr<DLLImportAttr>()) {
7913 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7914 return GVA_AvailableExternally;
7915 } else if (D->hasAttr<DLLExportAttr>()) {
7916 if (L == GVA_DiscardableODR)
7917 return GVA_StrongODR;
7918 }
7919 return L;
7920}
7921
7922GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7923 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7924 FD);
7925}
7926
7927static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7928 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007929 if (!VD->isExternallyVisible())
7930 return GVA_Internal;
7931
David Majnemer27d69db2014-04-28 22:17:59 +00007932 if (VD->isStaticLocal()) {
7933 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7934 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7935 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7936 LexicalContext = LexicalContext->getLexicalParent();
7937
7938 // Let the static local variable inherit it's linkage from the nearest
7939 // enclosing function.
7940 if (LexicalContext)
7941 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007942 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007943
7944 // GVA_StrongODR function linkage is stronger than what we need,
7945 // downgrade to GVA_DiscardableODR.
7946 // This allows us to discard the variable if we never end up needing it.
7947 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7948 : StaticLocalLinkage;
7949 }
7950
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007951 // MSVC treats in-class initialized static data members as definitions.
7952 // By giving them non-strong linkage, out-of-line definitions won't
7953 // cause link errors.
7954 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7955 return GVA_DiscardableODR;
7956
Richard Smith8809a0c2013-09-27 20:14:12 +00007957 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007958 case TSK_Undeclared:
7959 case TSK_ExplicitSpecialization:
7960 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007961
Rafael Espindola3ae00052013-05-13 00:12:11 +00007962 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007963 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007964
David Majnemer27d69db2014-04-28 22:17:59 +00007965 case TSK_ExplicitInstantiationDeclaration:
7966 return GVA_AvailableExternally;
7967
Rafael Espindola3ae00052013-05-13 00:12:11 +00007968 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007969 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007970 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007971
7972 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007973}
7974
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007975GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7976 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7977 VD);
7978}
7979
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007980bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007981 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7982 if (!VD->isFileVarDecl())
7983 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007984 // Global named register variables (GNU extension) are never emitted.
7985 if (VD->getStorageClass() == SC_Register)
7986 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007987 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7988 // We never need to emit an uninstantiated function template.
7989 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7990 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00007991 } else if (isa<OMPThreadPrivateDecl>(D))
7992 return true;
7993 else
Richard Smith5205a8c2013-04-01 20:22:16 +00007994 return false;
7995
7996 // If this is a member of a class template, we do not need to emit it.
7997 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007998 return false;
7999
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008000 // Weak references don't produce any output by themselves.
8001 if (D->hasAttr<WeakRefAttr>())
8002 return false;
8003
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008004 // Aliases and used decls are required.
8005 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8006 return true;
8007
8008 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8009 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008010 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008011 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008012
8013 // Constructors and destructors are required.
8014 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8015 return true;
8016
John McCall6bd2a892013-01-25 22:31:03 +00008017 // The key function for a class is required. This rule only comes
8018 // into play when inline functions can be key functions, though.
8019 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8020 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8021 const CXXRecordDecl *RD = MD->getParent();
8022 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8023 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8024 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8025 return true;
8026 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008027 }
8028 }
8029
8030 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8031
8032 // static, static inline, always_inline, and extern inline functions can
8033 // always be deferred. Normal inline functions can be deferred in C99/C++.
8034 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008035 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8036 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008037 return false;
8038 return true;
8039 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008040
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008041 const VarDecl *VD = cast<VarDecl>(D);
8042 assert(VD->isFileVarDecl() && "Expected file scoped var");
8043
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008044 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8045 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008046 return false;
8047
Richard Smitha0e5e542012-11-12 21:38:00 +00008048 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008049 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008050 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8051 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008052 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008053
Richard Smitha0e5e542012-11-12 21:38:00 +00008054 // Variables that have destruction with side-effects are required.
8055 if (VD->getType().isDestructedType())
8056 return true;
8057
8058 // Variables that have initialization with side-effects are required.
8059 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8060 return true;
8061
8062 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008063}
Charles Davis53c59df2010-08-16 03:33:14 +00008064
Reid Kleckner78af0702013-08-27 23:08:25 +00008065CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8066 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008067 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008068 if (IsCXXMethod)
8069 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008070
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008071 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8072
8073 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008074}
8075
Jay Foad39c79802011-01-12 09:06:06 +00008076bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008077 // Pass through to the C++ ABI object
8078 return ABI->isNearlyEmpty(RD);
8079}
8080
Reid Kleckner96f8f932014-02-05 17:27:08 +00008081VTableContextBase *ASTContext::getVTableContext() {
8082 if (!VTContext.get()) {
8083 if (Target->getCXXABI().isMicrosoft())
8084 VTContext.reset(new MicrosoftVTableContext(*this));
8085 else
8086 VTContext.reset(new ItaniumVTableContext(*this));
8087 }
8088 return VTContext.get();
8089}
8090
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008091MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008092 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008093 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008094 case TargetCXXABI::GenericItanium:
8095 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008096 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008097 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008098 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008099 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008100 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008101 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008102 }
David Blaikie83d382b2011-09-23 05:06:16 +00008103 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008104}
8105
Charles Davis53c59df2010-08-16 03:33:14 +00008106CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008107
8108size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008109 return ASTRecordLayouts.getMemorySize() +
8110 llvm::capacity_in_bytes(ObjCLayouts) +
8111 llvm::capacity_in_bytes(KeyFunctions) +
8112 llvm::capacity_in_bytes(ObjCImpls) +
8113 llvm::capacity_in_bytes(BlockVarCopyInits) +
8114 llvm::capacity_in_bytes(DeclAttrs) +
8115 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8116 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8117 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8118 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8119 llvm::capacity_in_bytes(OverriddenMethods) +
8120 llvm::capacity_in_bytes(Types) +
8121 llvm::capacity_in_bytes(VariableArrayTypes) +
8122 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008123}
Ted Kremenek540017e2011-10-06 05:00:56 +00008124
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008125/// getIntTypeForBitwidth -
8126/// sets integer QualTy according to specified details:
8127/// bitwidth, signed/unsigned.
8128/// Returns empty type if there is no appropriate target types.
8129QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8130 unsigned Signed) const {
8131 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8132 CanQualType QualTy = getFromTargetType(Ty);
8133 if (!QualTy && DestWidth == 128)
8134 return Signed ? Int128Ty : UnsignedInt128Ty;
8135 return QualTy;
8136}
8137
8138/// getRealTypeForBitwidth -
8139/// sets floating point QualTy according to specified bitwidth.
8140/// Returns empty type if there is no appropriate target types.
8141QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8142 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8143 switch (Ty) {
8144 case TargetInfo::Float:
8145 return FloatTy;
8146 case TargetInfo::Double:
8147 return DoubleTy;
8148 case TargetInfo::LongDouble:
8149 return LongDoubleTy;
8150 case TargetInfo::NoFloat:
8151 return QualType();
8152 }
8153
8154 llvm_unreachable("Unhandled TargetInfo::RealType value");
8155}
8156
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008157void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8158 if (Number > 1)
8159 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008160}
8161
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008162unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8163 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8164 MangleNumbers.find(ND);
8165 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008166}
8167
David Majnemer2206bf52014-03-05 08:57:59 +00008168void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8169 if (Number > 1)
8170 StaticLocalNumbers[VD] = Number;
8171}
8172
8173unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8174 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8175 StaticLocalNumbers.find(VD);
8176 return I != StaticLocalNumbers.end() ? I->second : 1;
8177}
8178
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008179MangleNumberingContext &
8180ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008181 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8182 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8183 if (!MCtx)
8184 MCtx = createMangleNumberingContext();
8185 return *MCtx;
8186}
8187
8188MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8189 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008190}
8191
Ted Kremenek540017e2011-10-06 05:00:56 +00008192void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8193 ParamIndices[D] = index;
8194}
8195
8196unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8197 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8198 assert(I != ParamIndices.end() &&
8199 "ParmIndices lacks entry set by ParmVarDecl");
8200 return I->second;
8201}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008202
Richard Smithe6c01442013-06-05 00:46:14 +00008203APValue *
8204ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8205 bool MayCreate) {
8206 assert(E && E->getStorageDuration() == SD_Static &&
8207 "don't need to cache the computed value for this temporary");
8208 if (MayCreate)
8209 return &MaterializedTemporaryValues[E];
8210
8211 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8212 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008213 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008214}
8215
Fariborz Jahanian615de762013-05-28 17:37:39 +00008216bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8217 const llvm::Triple &T = getTargetInfo().getTriple();
8218 if (!T.isOSDarwin())
8219 return false;
8220
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008221 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8222 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8223 return false;
8224
Fariborz Jahanian615de762013-05-28 17:37:39 +00008225 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8226 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8227 uint64_t Size = sizeChars.getQuantity();
8228 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8229 unsigned Align = alignChars.getQuantity();
8230 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8231 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8232}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008233
8234namespace {
8235
8236 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8237 /// parents as defined by the \c RecursiveASTVisitor.
8238 ///
8239 /// Note that the relationship described here is purely in terms of AST
8240 /// traversal - there are other relationships (for example declaration context)
8241 /// in the AST that are better modeled by special matchers.
8242 ///
8243 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8244 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8245
8246 public:
8247 /// \brief Builds and returns the translation unit's parent map.
8248 ///
8249 /// The caller takes ownership of the returned \c ParentMap.
8250 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8251 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8252 Visitor.TraverseDecl(&TU);
8253 return Visitor.Parents;
8254 }
8255
8256 private:
8257 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8258
8259 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8260 }
8261
8262 bool shouldVisitTemplateInstantiations() const {
8263 return true;
8264 }
8265 bool shouldVisitImplicitCode() const {
8266 return true;
8267 }
8268 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8269 // are not triggered during data recursion.
8270 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8271 return false;
8272 }
8273
8274 template <typename T>
8275 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008276 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008277 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008278 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008279 // FIXME: Currently we add the same parent multiple times, but only
8280 // when no memoization data is available for the type.
8281 // For example when we visit all subexpressions of template
8282 // instantiations; this is suboptimal, but benign: the only way to
8283 // visit those is with hasAncestor / hasParent, and those do not create
8284 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008285 // The plan is to enable DynTypedNode to be storable in a map or hash
8286 // map. The main problem there is to implement hash functions /
8287 // comparison operators for all types that DynTypedNode supports that
8288 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008289 auto &NodeOrVector = (*Parents)[Node];
8290 if (NodeOrVector.isNull()) {
8291 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008292 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008293 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8294 auto *Node =
8295 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8296 auto *Vector = new ASTContext::ParentVector(1, *Node);
8297 NodeOrVector = Vector;
8298 delete Node;
8299 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008300 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008301
8302 auto *Vector =
8303 NodeOrVector.template get<ASTContext::ParentVector *>();
8304 // Skip duplicates for types that have memoization data.
8305 // We must check that the type has memoization data before calling
8306 // std::find() because DynTypedNode::operator== can't compare all
8307 // types.
8308 bool Found = ParentStack.back().getMemoizationData() &&
8309 std::find(Vector->begin(), Vector->end(),
8310 ParentStack.back()) != Vector->end();
8311 if (!Found)
8312 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008313 }
8314 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008315 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8316 bool Result = (this ->* traverse) (Node);
8317 ParentStack.pop_back();
8318 return Result;
8319 }
8320
8321 bool TraverseDecl(Decl *DeclNode) {
8322 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8323 }
8324
8325 bool TraverseStmt(Stmt *StmtNode) {
8326 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8327 }
8328
8329 ASTContext::ParentMap *Parents;
8330 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8331
8332 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8333 };
8334
8335} // end namespace
8336
Benjamin Kramer07935292014-10-04 17:01:26 +00008337ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008338ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8339 assert(Node.getMemoizationData() &&
8340 "Invariant broken: only nodes that support memoization may be "
8341 "used in the parent map.");
8342 if (!AllParents) {
8343 // We always need to run over the whole translation unit, as
8344 // hasAncestor can escape any subtree.
8345 AllParents.reset(
8346 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8347 }
8348 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8349 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008350 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008351 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008352 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8353 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008354 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008355 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008356}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008357
8358bool
8359ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8360 const ObjCMethodDecl *MethodImpl) {
8361 // No point trying to match an unavailable/deprecated mothod.
8362 if (MethodDecl->hasAttr<UnavailableAttr>()
8363 || MethodDecl->hasAttr<DeprecatedAttr>())
8364 return false;
8365 if (MethodDecl->getObjCDeclQualifier() !=
8366 MethodImpl->getObjCDeclQualifier())
8367 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008368 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008369 return false;
8370
8371 if (MethodDecl->param_size() != MethodImpl->param_size())
8372 return false;
8373
8374 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8375 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8376 EF = MethodDecl->param_end();
8377 IM != EM && IF != EF; ++IM, ++IF) {
8378 const ParmVarDecl *DeclVar = (*IF);
8379 const ParmVarDecl *ImplVar = (*IM);
8380 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8381 return false;
8382 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8383 return false;
8384 }
8385 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8386
8387}
Richard Smith053f6c62014-05-16 23:01:30 +00008388
8389// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8390// doesn't include ASTContext.h
8391template
8392clang::LazyGenerationalUpdatePtr<
8393 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8394clang::LazyGenerationalUpdatePtr<
8395 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8396 const clang::ASTContext &Ctx, Decl *Value);