blob: c72c239320dcf50cb76930c835e38e41f22064c4 [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:
John McCall359b8852013-01-25 22:30:49 +0000685 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000686 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000687 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000688 return CreateMicrosoftCXXABI(*this);
689 }
David Blaikie8a40f702012-01-17 06:56:22 +0000690 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000691}
692
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000694 const LangOptions &LOpts) {
695 if (LOpts.FakeAddressSpaceMap) {
696 // The fake address space map must have a distinct entry for each
697 // language-specific address space.
698 static const unsigned FakeAddrSpaceMap[] = {
699 1, // opencl_global
700 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000701 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000702 4, // opencl_generic
703 5, // cuda_device
704 6, // cuda_constant
705 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000706 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000707 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 }
711}
712
David Tweed31d09b02013-09-13 12:04:22 +0000713static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
714 const LangOptions &LangOpts) {
715 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000716 case LangOptions::ASMM_Target:
717 return TI.useAddressSpaceMapMangling();
718 case LangOptions::ASMM_On:
719 return true;
720 case LangOptions::ASMM_Off:
721 return false;
722 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000723 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000724}
725
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000726ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000727 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000728 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000729 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
730 DependentTemplateSpecializationTypes(this_()),
731 SubstTemplateTemplateParmPacks(this_()),
732 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
733 UInt128Decl(nullptr), Float128StubDecl(nullptr),
734 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
735 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
736 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
737 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
738 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
739 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Nico Weber227822e2015-01-04 05:29:21 +0000740 FirstLocalImport(), LastLocalImport(),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000741 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova0416102014-11-11 01:26:14 +0000742 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, 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);
Chris Lattner8b23c252008-04-06 22:05:18 +00001685 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001686 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001687 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001688 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001689 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001690
Chris Lattner63d2b362009-10-22 05:17:15 +00001691 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001692 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1693 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001694
Richard Smith30482bc2011-02-20 03:19:35 +00001695 case Type::Auto: {
1696 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001697 assert(!A->getDeducedType().isNull() &&
1698 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001699 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001700 }
1701
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001702 case Type::Paren:
1703 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1704
Douglas Gregoref462e62009-04-30 17:32:17 +00001705 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001706 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001707 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001708 // If the typedef has an aligned attribute on it, it overrides any computed
1709 // alignment we have. This violates the GCC documentation (which says that
1710 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001711 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001712 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001713 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001714 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001715 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001716 AlignIsRequired = Info.AlignIsRequired;
1717 }
David Majnemer34b57492014-07-30 01:30:47 +00001718 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001719 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001720 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001721
Abramo Bagnara6150c882010-05-11 21:36:43 +00001722 case Type::Elaborated:
1723 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001724
John McCall81904512011-01-06 01:58:22 +00001725 case Type::Attributed:
1726 return getTypeInfo(
1727 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1728
Eli Friedman0dfb8892011-10-06 23:00:33 +00001729 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001730 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001731 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1732 Width = Info.Width;
1733 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001734
1735 // If the size of the type doesn't exceed the platform's max
1736 // atomic promotion width, make the size and alignment more
1737 // favorable to atomic operations:
1738 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1739 // Round the size up to a power of 2.
1740 if (!llvm::isPowerOf2_64(Width))
1741 Width = llvm::NextPowerOf2(Width);
1742
1743 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001744 Align = static_cast<unsigned>(Width);
1745 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001746 }
1747
Douglas Gregoref462e62009-04-30 17:32:17 +00001748 }
Mike Stump11289f42009-09-09 15:08:12 +00001749
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001750 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001751 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001752}
1753
Ken Dyckcc56c542011-01-15 18:38:59 +00001754/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1755CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1756 return CharUnits::fromQuantity(BitSize / getCharWidth());
1757}
1758
Ken Dyckb0fcc592011-02-11 01:54:29 +00001759/// toBits - Convert a size in characters to a size in characters.
1760int64_t ASTContext::toBits(CharUnits CharSize) const {
1761 return CharSize.getQuantity() * getCharWidth();
1762}
1763
Ken Dyck8c89d592009-12-22 14:23:30 +00001764/// getTypeSizeInChars - Return the size of the specified type, in characters.
1765/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001766CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001767 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001768}
Jay Foad39c79802011-01-12 09:06:06 +00001769CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001770 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001771}
1772
Ken Dycka6046ab2010-01-26 17:25:18 +00001773/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001774/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001775CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001776 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001777}
Jay Foad39c79802011-01-12 09:06:06 +00001778CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001779 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001780}
1781
Chris Lattnera3402cd2009-01-27 18:08:34 +00001782/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1783/// type for the current target in bits. This can be different than the ABI
1784/// alignment in cases where it is beneficial for performance to overalign
1785/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001786unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001787 TypeInfo TI = getTypeInfo(T);
1788 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001789
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001790 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1791 return ABIAlign; // Never overalign on XCore.
1792
Eli Friedman7ab09572009-05-25 21:27:19 +00001793 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001794 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001795 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001796 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001797 if (const EnumType *ET = T->getAs<EnumType>())
1798 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001799 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001800 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1801 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001802 // Don't increase the alignment if an alignment attribute was specified on a
1803 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001804 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001805 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001806
Chris Lattnera3402cd2009-01-27 18:08:34 +00001807 return ABIAlign;
1808}
1809
Ulrich Weigandfa806422013-05-06 16:23:57 +00001810/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1811/// to a global variable of the specified type.
1812unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1813 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1814}
1815
1816/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1817/// should be given to a global variable of the specified type.
1818CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1819 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1820}
1821
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001822/// DeepCollectObjCIvars -
1823/// This routine first collects all declared, but not synthesized, ivars in
1824/// super class and then collects all ivars, including those synthesized for
1825/// current class. This routine is used for implementation of current class
1826/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001827///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001828void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1829 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001830 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001831 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1832 DeepCollectObjCIvars(SuperClass, false, Ivars);
1833 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001834 for (const auto *I : OI->ivars())
1835 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001836 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001837 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001838 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001839 Iv= Iv->getNextIvar())
1840 Ivars.push_back(Iv);
1841 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001842}
1843
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001844/// CollectInheritedProtocols - Collect all protocols in current class and
1845/// those inherited by it.
1846void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001847 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001848 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001849 // We can use protocol_iterator here instead of
1850 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001851 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001852 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001853 for (auto *P : Proto->protocols()) {
1854 Protocols.insert(P->getCanonicalDecl());
1855 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001856 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001857 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001858
1859 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001860 for (const auto *Cat : OI->visible_categories())
1861 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001862
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001863 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1864 while (SD) {
1865 CollectInheritedProtocols(SD, Protocols);
1866 SD = SD->getSuperClass();
1867 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001868 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001869 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001870 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001871 for (const auto *P : Proto->protocols())
1872 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001873 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001874 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001875 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001876 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001877 for (const auto *P : Proto->protocols())
1878 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001879 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001880 }
1881}
1882
Jay Foad39c79802011-01-12 09:06:06 +00001883unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001884 unsigned count = 0;
1885 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001886 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001887 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001888
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001889 // Count ivar defined in this class's implementation. This
1890 // includes synthesized ivars.
1891 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001892 count += ImplDecl->ivar_size();
1893
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001894 return count;
1895}
1896
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001897bool ASTContext::isSentinelNullExpr(const Expr *E) {
1898 if (!E)
1899 return false;
1900
1901 // nullptr_t is always treated as null.
1902 if (E->getType()->isNullPtrType()) return true;
1903
1904 if (E->getType()->isAnyPointerType() &&
1905 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1906 Expr::NPC_ValueDependentIsNull))
1907 return true;
1908
1909 // Unfortunately, __null has type 'int'.
1910 if (isa<GNUNullExpr>(E)) return true;
1911
1912 return false;
1913}
1914
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001915/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1916ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1917 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1918 I = ObjCImpls.find(D);
1919 if (I != ObjCImpls.end())
1920 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001921 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001922}
1923/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1924ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1925 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1926 I = ObjCImpls.find(D);
1927 if (I != ObjCImpls.end())
1928 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001929 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001930}
1931
1932/// \brief Set the implementation of ObjCInterfaceDecl.
1933void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1934 ObjCImplementationDecl *ImplD) {
1935 assert(IFaceD && ImplD && "Passed null params");
1936 ObjCImpls[IFaceD] = ImplD;
1937}
1938/// \brief Set the implementation of ObjCCategoryDecl.
1939void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1940 ObjCCategoryImplDecl *ImplD) {
1941 assert(CatD && ImplD && "Passed null params");
1942 ObjCImpls[CatD] = ImplD;
1943}
1944
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001945const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1946 const NamedDecl *ND) const {
1947 if (const ObjCInterfaceDecl *ID =
1948 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001949 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001950 if (const ObjCCategoryDecl *CD =
1951 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001952 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001953 if (const ObjCImplDecl *IMD =
1954 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001955 return IMD->getClassInterface();
1956
Craig Topper36250ad2014-05-12 05:36:57 +00001957 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001958}
1959
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001960/// \brief Get the copy initialization expression of VarDecl,or NULL if
1961/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001962Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001963 assert(VD && "Passed null params");
1964 assert(VD->hasAttr<BlocksAttr>() &&
1965 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001966 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001967 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001968 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001969}
1970
1971/// \brief Set the copy inialization expression of a block var decl.
1972void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1973 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001974 assert(VD->hasAttr<BlocksAttr>() &&
1975 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001976 BlockVarCopyInits[VD] = Init;
1977}
1978
John McCallbcd03502009-12-07 02:54:59 +00001979TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001980 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001981 if (!DataSize)
1982 DataSize = TypeLoc::getFullDataSizeForType(T);
1983 else
1984 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001985 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001986
John McCallbcd03502009-12-07 02:54:59 +00001987 TypeSourceInfo *TInfo =
1988 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1989 new (TInfo) TypeSourceInfo(T);
1990 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001991}
1992
John McCallbcd03502009-12-07 02:54:59 +00001993TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001994 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001995 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001996 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001997 return DI;
1998}
1999
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002000const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002001ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002002 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002003}
2004
2005const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002006ASTContext::getASTObjCImplementationLayout(
2007 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002008 return getObjCLayout(D->getClassInterface(), D);
2009}
2010
Chris Lattner983a8bb2007-07-13 22:13:22 +00002011//===----------------------------------------------------------------------===//
2012// Type creation/memoization methods
2013//===----------------------------------------------------------------------===//
2014
Jay Foad39c79802011-01-12 09:06:06 +00002015QualType
John McCall33ddac02011-01-19 10:06:00 +00002016ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2017 unsigned fastQuals = quals.getFastQualifiers();
2018 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002019
2020 // Check if we've already instantiated this type.
2021 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002022 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002023 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002024 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2025 assert(eq->getQualifiers() == quals);
2026 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002027 }
2028
John McCall33ddac02011-01-19 10:06:00 +00002029 // If the base type is not canonical, make the appropriate canonical type.
2030 QualType canon;
2031 if (!baseType->isCanonicalUnqualified()) {
2032 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002033 canonSplit.Quals.addConsistentQualifiers(quals);
2034 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002035
2036 // Re-find the insert position.
2037 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2038 }
2039
2040 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2041 ExtQualNodes.InsertNode(eq, insertPos);
2042 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002043}
2044
Jay Foad39c79802011-01-12 09:06:06 +00002045QualType
2046ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002047 QualType CanT = getCanonicalType(T);
2048 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002049 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002050
John McCall8ccfcb52009-09-24 19:53:00 +00002051 // If we are composing extended qualifiers together, merge together
2052 // into one ExtQuals node.
2053 QualifierCollector Quals;
2054 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002055
John McCall8ccfcb52009-09-24 19:53:00 +00002056 // If this type already has an address space specified, it cannot get
2057 // another one.
2058 assert(!Quals.hasAddressSpace() &&
2059 "Type cannot be in multiple addr spaces!");
2060 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002061
John McCall8ccfcb52009-09-24 19:53:00 +00002062 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002063}
2064
Chris Lattnerd60183d2009-02-18 22:53:11 +00002065QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002066 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002067 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002068 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002069 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002070
John McCall53fa7142010-12-24 02:08:15 +00002071 if (const PointerType *ptr = T->getAs<PointerType>()) {
2072 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002073 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002074 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2075 return getPointerType(ResultType);
2076 }
2077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
John McCall8ccfcb52009-09-24 19:53:00 +00002079 // If we are composing extended qualifiers together, merge together
2080 // into one ExtQuals node.
2081 QualifierCollector Quals;
2082 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002083
John McCall8ccfcb52009-09-24 19:53:00 +00002084 // If this type already has an ObjCGC specified, it cannot get
2085 // another one.
2086 assert(!Quals.hasObjCGCAttr() &&
2087 "Type cannot have multiple ObjCGCs!");
2088 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002089
John McCall8ccfcb52009-09-24 19:53:00 +00002090 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002091}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002092
John McCall4f5019e2010-12-19 02:44:49 +00002093const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2094 FunctionType::ExtInfo Info) {
2095 if (T->getExtInfo() == Info)
2096 return T;
2097
2098 QualType Result;
2099 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002100 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002101 } else {
2102 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2103 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2104 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002105 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002106 }
2107
2108 return cast<FunctionType>(Result.getTypePtr());
2109}
2110
Richard Smith2a7d4812013-05-04 07:00:32 +00002111void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2112 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002113 FD = FD->getMostRecentDecl();
2114 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002115 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2116 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002117 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002118 if (FunctionDecl *Next = FD->getPreviousDecl())
2119 FD = Next;
2120 else
2121 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002122 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002123 if (ASTMutationListener *L = getASTMutationListener())
2124 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002125}
2126
Richard Smith0b3a4622014-11-13 20:01:57 +00002127/// Get a function type and produce the equivalent function type with the
2128/// specified exception specification. Type sugar that can be present on a
2129/// declaration of a function with an exception specification is permitted
2130/// and preserved. Other type sugar (for instance, typedefs) is not.
2131static QualType getFunctionTypeWithExceptionSpec(
2132 ASTContext &Context, QualType Orig,
2133 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2134 // Might have some parens.
2135 if (auto *PT = dyn_cast<ParenType>(Orig))
2136 return Context.getParenType(
2137 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2138
2139 // Might have a calling-convention attribute.
2140 if (auto *AT = dyn_cast<AttributedType>(Orig))
2141 return Context.getAttributedType(
2142 AT->getAttrKind(),
2143 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2144 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2145 ESI));
2146
2147 // Anything else must be a function type. Rebuild it with the new exception
2148 // specification.
2149 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2150 return Context.getFunctionType(
2151 Proto->getReturnType(), Proto->getParamTypes(),
2152 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2153}
2154
2155void ASTContext::adjustExceptionSpec(
2156 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2157 bool AsWritten) {
2158 // Update the type.
2159 QualType Updated =
2160 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2161 FD->setType(Updated);
2162
2163 if (!AsWritten)
2164 return;
2165
2166 // Update the type in the type source information too.
2167 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2168 // If the type and the type-as-written differ, we may need to update
2169 // the type-as-written too.
2170 if (TSInfo->getType() != FD->getType())
2171 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2172
2173 // FIXME: When we get proper type location information for exceptions,
2174 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2175 // up the TypeSourceInfo;
2176 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2177 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2178 "TypeLoc size mismatch from updating exception specification");
2179 TSInfo->overrideType(Updated);
2180 }
2181}
2182
Chris Lattnerc6395932007-06-22 20:56:16 +00002183/// getComplexType - Return the uniqued reference to the type for a complex
2184/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002185QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002186 // Unique pointers, to guarantee there is only one pointer of a particular
2187 // structure.
2188 llvm::FoldingSetNodeID ID;
2189 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002190
Craig Topper36250ad2014-05-12 05:36:57 +00002191 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002192 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2193 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002194
Chris Lattnerc6395932007-06-22 20:56:16 +00002195 // If the pointee type isn't canonical, this won't be a canonical type either,
2196 // so fill in the canonical type field.
2197 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002198 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002199 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerc6395932007-06-22 20:56:16 +00002201 // Get the new insert position for the node we care about.
2202 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002203 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002204 }
John McCall90d1c2d2009-09-24 23:30:46 +00002205 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002206 Types.push_back(New);
2207 ComplexTypes.InsertNode(New, InsertPos);
2208 return QualType(New, 0);
2209}
2210
Chris Lattner970e54e2006-11-12 00:37:36 +00002211/// getPointerType - Return the uniqued reference to the type for a pointer to
2212/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002213QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002214 // Unique pointers, to guarantee there is only one pointer of a particular
2215 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002216 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002217 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002218
Craig Topper36250ad2014-05-12 05:36:57 +00002219 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002220 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002221 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattner7ccecb92006-11-12 08:50:50 +00002223 // If the pointee type isn't canonical, this won't be a canonical type either,
2224 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002225 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002226 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002227 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002228
Bob Wilsonc8541f22013-03-15 17:12:43 +00002229 // Get the new insert position for the node we care about.
2230 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002231 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002232 }
John McCall90d1c2d2009-09-24 23:30:46 +00002233 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002234 Types.push_back(New);
2235 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002236 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002237}
2238
Reid Kleckner0503a872013-12-05 01:23:43 +00002239QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2240 llvm::FoldingSetNodeID ID;
2241 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002242 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002243 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2244 if (AT)
2245 return QualType(AT, 0);
2246
2247 QualType Canonical = getCanonicalType(New);
2248
2249 // Get the new insert position for the node we care about.
2250 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002251 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002252
2253 AT = new (*this, TypeAlignment)
2254 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2255 Types.push_back(AT);
2256 AdjustedTypes.InsertNode(AT, InsertPos);
2257 return QualType(AT, 0);
2258}
2259
Reid Kleckner8a365022013-06-24 17:51:48 +00002260QualType ASTContext::getDecayedType(QualType T) const {
2261 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2262
Reid Kleckner8a365022013-06-24 17:51:48 +00002263 QualType Decayed;
2264
2265 // C99 6.7.5.3p7:
2266 // A declaration of a parameter as "array of type" shall be
2267 // adjusted to "qualified pointer to type", where the type
2268 // qualifiers (if any) are those specified within the [ and ] of
2269 // the array type derivation.
2270 if (T->isArrayType())
2271 Decayed = getArrayDecayedType(T);
2272
2273 // C99 6.7.5.3p8:
2274 // A declaration of a parameter as "function returning type"
2275 // shall be adjusted to "pointer to function returning type", as
2276 // in 6.3.2.1.
2277 if (T->isFunctionType())
2278 Decayed = getPointerType(T);
2279
Reid Kleckner0503a872013-12-05 01:23:43 +00002280 llvm::FoldingSetNodeID ID;
2281 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002282 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002283 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2284 if (AT)
2285 return QualType(AT, 0);
2286
Reid Kleckner8a365022013-06-24 17:51:48 +00002287 QualType Canonical = getCanonicalType(Decayed);
2288
2289 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002290 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002291 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002292
Reid Kleckner0503a872013-12-05 01:23:43 +00002293 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2294 Types.push_back(AT);
2295 AdjustedTypes.InsertNode(AT, InsertPos);
2296 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002297}
2298
Mike Stump11289f42009-09-09 15:08:12 +00002299/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002300/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002301QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002302 assert(T->isFunctionType() && "block of function types only");
2303 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002304 // structure.
2305 llvm::FoldingSetNodeID ID;
2306 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002307
Craig Topper36250ad2014-05-12 05:36:57 +00002308 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002309 if (BlockPointerType *PT =
2310 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2311 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002312
2313 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002314 // type either so fill in the canonical type field.
2315 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002316 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002317 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002318
Steve Naroffec33ed92008-08-27 16:04:49 +00002319 // Get the new insert position for the node we care about.
2320 BlockPointerType *NewIP =
2321 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002322 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002323 }
John McCall90d1c2d2009-09-24 23:30:46 +00002324 BlockPointerType *New
2325 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002326 Types.push_back(New);
2327 BlockPointerTypes.InsertNode(New, InsertPos);
2328 return QualType(New, 0);
2329}
2330
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002331/// getLValueReferenceType - Return the uniqued reference to the type for an
2332/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002333QualType
2334ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002335 assert(getCanonicalType(T) != OverloadTy &&
2336 "Unresolved overloaded function type");
2337
Bill Wendling3708c182007-05-27 10:15:43 +00002338 // Unique pointers, to guarantee there is only one pointer of a particular
2339 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002340 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002341 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002342
Craig Topper36250ad2014-05-12 05:36:57 +00002343 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002344 if (LValueReferenceType *RT =
2345 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002346 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002347
John McCallfc93cf92009-10-22 22:37:11 +00002348 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2349
Bill Wendling3708c182007-05-27 10:15:43 +00002350 // If the referencee type isn't canonical, this won't be a canonical type
2351 // either, so fill in the canonical type field.
2352 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002353 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2354 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2355 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002356
Bill Wendling3708c182007-05-27 10:15:43 +00002357 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002358 LValueReferenceType *NewIP =
2359 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002360 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002361 }
2362
John McCall90d1c2d2009-09-24 23:30:46 +00002363 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002364 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2365 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002366 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002367 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002368
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002369 return QualType(New, 0);
2370}
2371
2372/// getRValueReferenceType - Return the uniqued reference to the type for an
2373/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002374QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002375 // Unique pointers, to guarantee there is only one pointer of a particular
2376 // structure.
2377 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002378 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002379
Craig Topper36250ad2014-05-12 05:36:57 +00002380 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002381 if (RValueReferenceType *RT =
2382 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2383 return QualType(RT, 0);
2384
John McCallfc93cf92009-10-22 22:37:11 +00002385 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2386
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002387 // If the referencee type isn't canonical, this won't be a canonical type
2388 // either, so fill in the canonical type field.
2389 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002390 if (InnerRef || !T.isCanonical()) {
2391 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2392 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002393
2394 // Get the new insert position for the node we care about.
2395 RValueReferenceType *NewIP =
2396 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002397 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002398 }
2399
John McCall90d1c2d2009-09-24 23:30:46 +00002400 RValueReferenceType *New
2401 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002402 Types.push_back(New);
2403 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002404 return QualType(New, 0);
2405}
2406
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002407/// getMemberPointerType - Return the uniqued reference to the type for a
2408/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002409QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002410 // Unique pointers, to guarantee there is only one pointer of a particular
2411 // structure.
2412 llvm::FoldingSetNodeID ID;
2413 MemberPointerType::Profile(ID, T, Cls);
2414
Craig Topper36250ad2014-05-12 05:36:57 +00002415 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002416 if (MemberPointerType *PT =
2417 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2418 return QualType(PT, 0);
2419
2420 // If the pointee or class type isn't canonical, this won't be a canonical
2421 // type either, so fill in the canonical type field.
2422 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002423 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002424 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2425
2426 // Get the new insert position for the node we care about.
2427 MemberPointerType *NewIP =
2428 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002429 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002430 }
John McCall90d1c2d2009-09-24 23:30:46 +00002431 MemberPointerType *New
2432 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002433 Types.push_back(New);
2434 MemberPointerTypes.InsertNode(New, InsertPos);
2435 return QualType(New, 0);
2436}
2437
Mike Stump11289f42009-09-09 15:08:12 +00002438/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002439/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002440QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002441 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002442 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002443 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002444 assert((EltTy->isDependentType() ||
2445 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002446 "Constant array of VLAs is illegal!");
2447
Chris Lattnere2df3f92009-05-13 04:12:56 +00002448 // Convert the array size into a canonical width matching the pointer size for
2449 // the target.
2450 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002451 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002452 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002453
Chris Lattner23b7eb62007-06-15 23:05:46 +00002454 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002455 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002456
Craig Topper36250ad2014-05-12 05:36:57 +00002457 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002458 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002459 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002460 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002461
John McCall33ddac02011-01-19 10:06:00 +00002462 // If the element type isn't canonical or has qualifiers, this won't
2463 // be a canonical type either, so fill in the canonical type field.
2464 QualType Canon;
2465 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2466 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002467 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002468 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002469 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002470
Chris Lattner36f8e652007-01-27 08:31:04 +00002471 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002472 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002473 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002474 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
John McCall90d1c2d2009-09-24 23:30:46 +00002477 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002478 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002479 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002480 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002481 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002482}
2483
John McCall06549462011-01-18 08:40:38 +00002484/// getVariableArrayDecayedType - Turns the given type, which may be
2485/// variably-modified, into the corresponding type with all the known
2486/// sizes replaced with [*].
2487QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2488 // Vastly most common case.
2489 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002490
John McCall06549462011-01-18 08:40:38 +00002491 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002492
John McCall06549462011-01-18 08:40:38 +00002493 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002494 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002495 switch (ty->getTypeClass()) {
2496#define TYPE(Class, Base)
2497#define ABSTRACT_TYPE(Class, Base)
2498#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2499#include "clang/AST/TypeNodes.def"
2500 llvm_unreachable("didn't desugar past all non-canonical types?");
2501
2502 // These types should never be variably-modified.
2503 case Type::Builtin:
2504 case Type::Complex:
2505 case Type::Vector:
2506 case Type::ExtVector:
2507 case Type::DependentSizedExtVector:
2508 case Type::ObjCObject:
2509 case Type::ObjCInterface:
2510 case Type::ObjCObjectPointer:
2511 case Type::Record:
2512 case Type::Enum:
2513 case Type::UnresolvedUsing:
2514 case Type::TypeOfExpr:
2515 case Type::TypeOf:
2516 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002517 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002518 case Type::DependentName:
2519 case Type::InjectedClassName:
2520 case Type::TemplateSpecialization:
2521 case Type::DependentTemplateSpecialization:
2522 case Type::TemplateTypeParm:
2523 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002524 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002525 case Type::PackExpansion:
2526 llvm_unreachable("type should never be variably-modified");
2527
2528 // These types can be variably-modified but should never need to
2529 // further decay.
2530 case Type::FunctionNoProto:
2531 case Type::FunctionProto:
2532 case Type::BlockPointer:
2533 case Type::MemberPointer:
2534 return type;
2535
2536 // These types can be variably-modified. All these modifications
2537 // preserve structure except as noted by comments.
2538 // TODO: if we ever care about optimizing VLAs, there are no-op
2539 // optimizations available here.
2540 case Type::Pointer:
2541 result = getPointerType(getVariableArrayDecayedType(
2542 cast<PointerType>(ty)->getPointeeType()));
2543 break;
2544
2545 case Type::LValueReference: {
2546 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2547 result = getLValueReferenceType(
2548 getVariableArrayDecayedType(lv->getPointeeType()),
2549 lv->isSpelledAsLValue());
2550 break;
2551 }
2552
2553 case Type::RValueReference: {
2554 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2555 result = getRValueReferenceType(
2556 getVariableArrayDecayedType(lv->getPointeeType()));
2557 break;
2558 }
2559
Eli Friedman0dfb8892011-10-06 23:00:33 +00002560 case Type::Atomic: {
2561 const AtomicType *at = cast<AtomicType>(ty);
2562 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2563 break;
2564 }
2565
John McCall06549462011-01-18 08:40:38 +00002566 case Type::ConstantArray: {
2567 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2568 result = getConstantArrayType(
2569 getVariableArrayDecayedType(cat->getElementType()),
2570 cat->getSize(),
2571 cat->getSizeModifier(),
2572 cat->getIndexTypeCVRQualifiers());
2573 break;
2574 }
2575
2576 case Type::DependentSizedArray: {
2577 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2578 result = getDependentSizedArrayType(
2579 getVariableArrayDecayedType(dat->getElementType()),
2580 dat->getSizeExpr(),
2581 dat->getSizeModifier(),
2582 dat->getIndexTypeCVRQualifiers(),
2583 dat->getBracketsRange());
2584 break;
2585 }
2586
2587 // Turn incomplete types into [*] types.
2588 case Type::IncompleteArray: {
2589 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2590 result = getVariableArrayType(
2591 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002592 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002593 ArrayType::Normal,
2594 iat->getIndexTypeCVRQualifiers(),
2595 SourceRange());
2596 break;
2597 }
2598
2599 // Turn VLA types into [*] types.
2600 case Type::VariableArray: {
2601 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2602 result = getVariableArrayType(
2603 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002604 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002605 ArrayType::Star,
2606 vat->getIndexTypeCVRQualifiers(),
2607 vat->getBracketsRange());
2608 break;
2609 }
2610 }
2611
2612 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002613 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002614}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002615
Steve Naroffcadebd02007-08-30 18:14:25 +00002616/// getVariableArrayType - Returns a non-unique reference to the type for a
2617/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002618QualType ASTContext::getVariableArrayType(QualType EltTy,
2619 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002620 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002621 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002622 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002623 // Since we don't unique expressions, it isn't possible to unique VLA's
2624 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002625 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002626
John McCall33ddac02011-01-19 10:06:00 +00002627 // Be sure to pull qualifiers off the element type.
2628 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2629 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002630 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002631 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002632 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002633 }
2634
John McCall90d1c2d2009-09-24 23:30:46 +00002635 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002636 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002637
2638 VariableArrayTypes.push_back(New);
2639 Types.push_back(New);
2640 return QualType(New, 0);
2641}
2642
Douglas Gregor4619e432008-12-05 23:32:09 +00002643/// getDependentSizedArrayType - Returns a non-unique reference to
2644/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002645/// type.
John McCall33ddac02011-01-19 10:06:00 +00002646QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2647 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002648 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002649 unsigned elementTypeQuals,
2650 SourceRange brackets) const {
2651 assert((!numElements || numElements->isTypeDependent() ||
2652 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002653 "Size must be type- or value-dependent!");
2654
John McCall33ddac02011-01-19 10:06:00 +00002655 // Dependently-sized array types that do not have a specified number
2656 // of elements will have their sizes deduced from a dependent
2657 // initializer. We do no canonicalization here at all, which is okay
2658 // because they can't be used in most locations.
2659 if (!numElements) {
2660 DependentSizedArrayType *newType
2661 = new (*this, TypeAlignment)
2662 DependentSizedArrayType(*this, elementType, QualType(),
2663 numElements, ASM, elementTypeQuals,
2664 brackets);
2665 Types.push_back(newType);
2666 return QualType(newType, 0);
2667 }
2668
2669 // Otherwise, we actually build a new type every time, but we
2670 // also build a canonical type.
2671
2672 SplitQualType canonElementType = getCanonicalType(elementType).split();
2673
Craig Topper36250ad2014-05-12 05:36:57 +00002674 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002675 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002676 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002677 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002678 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002679
John McCall33ddac02011-01-19 10:06:00 +00002680 // Look for an existing type with these properties.
2681 DependentSizedArrayType *canonTy =
2682 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002683
John McCall33ddac02011-01-19 10:06:00 +00002684 // If we don't have one, build one.
2685 if (!canonTy) {
2686 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002687 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002688 QualType(), numElements, ASM, elementTypeQuals,
2689 brackets);
2690 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2691 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002692 }
2693
John McCall33ddac02011-01-19 10:06:00 +00002694 // Apply qualifiers from the element type to the array.
2695 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002696 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002697
John McCall33ddac02011-01-19 10:06:00 +00002698 // If we didn't need extra canonicalization for the element type,
2699 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002700 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002701 return canon;
2702
2703 // Otherwise, we need to build a type which follows the spelling
2704 // of the element type.
2705 DependentSizedArrayType *sugaredType
2706 = new (*this, TypeAlignment)
2707 DependentSizedArrayType(*this, elementType, canon, numElements,
2708 ASM, elementTypeQuals, brackets);
2709 Types.push_back(sugaredType);
2710 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002711}
2712
John McCall33ddac02011-01-19 10:06:00 +00002713QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002714 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002715 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002716 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002717 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002718
Craig Topper36250ad2014-05-12 05:36:57 +00002719 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002720 if (IncompleteArrayType *iat =
2721 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2722 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002723
2724 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002725 // either, so fill in the canonical type field. We also have to pull
2726 // qualifiers off the element type.
2727 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002728
John McCall33ddac02011-01-19 10:06:00 +00002729 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2730 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002731 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002732 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002733 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002734
2735 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002736 IncompleteArrayType *existing =
2737 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2738 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002739 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002740
John McCall33ddac02011-01-19 10:06:00 +00002741 IncompleteArrayType *newType = new (*this, TypeAlignment)
2742 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002743
John McCall33ddac02011-01-19 10:06:00 +00002744 IncompleteArrayTypes.InsertNode(newType, insertPos);
2745 Types.push_back(newType);
2746 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002747}
2748
Steve Naroff91fcddb2007-07-18 18:00:27 +00002749/// getVectorType - Return the unique reference to a vector type of
2750/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002751QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002752 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002753 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002754
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002755 // Check if we've already instantiated a vector of this type.
2756 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002757 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002758
Craig Topper36250ad2014-05-12 05:36:57 +00002759 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002760 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2761 return QualType(VTP, 0);
2762
2763 // If the element type isn't canonical, this won't be a canonical type either,
2764 // so fill in the canonical type field.
2765 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002766 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002767 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002768
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002769 // Get the new insert position for the node we care about.
2770 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002771 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002772 }
John McCall90d1c2d2009-09-24 23:30:46 +00002773 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002774 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002775 VectorTypes.InsertNode(New, InsertPos);
2776 Types.push_back(New);
2777 return QualType(New, 0);
2778}
2779
Nate Begemance4d7fc2008-04-18 23:10:10 +00002780/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002781/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002782QualType
2783ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002784 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002785
Steve Naroff91fcddb2007-07-18 18:00:27 +00002786 // Check if we've already instantiated a vector of this type.
2787 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002788 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002789 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002790 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002791 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2792 return QualType(VTP, 0);
2793
2794 // If the element type isn't canonical, this won't be a canonical type either,
2795 // so fill in the canonical type field.
2796 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002797 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002798 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Steve Naroff91fcddb2007-07-18 18:00:27 +00002800 // Get the new insert position for the node we care about.
2801 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002802 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002803 }
John McCall90d1c2d2009-09-24 23:30:46 +00002804 ExtVectorType *New = new (*this, TypeAlignment)
2805 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002806 VectorTypes.InsertNode(New, InsertPos);
2807 Types.push_back(New);
2808 return QualType(New, 0);
2809}
2810
Jay Foad39c79802011-01-12 09:06:06 +00002811QualType
2812ASTContext::getDependentSizedExtVectorType(QualType vecType,
2813 Expr *SizeExpr,
2814 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002815 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002816 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002817 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002818
Craig Topper36250ad2014-05-12 05:36:57 +00002819 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002820 DependentSizedExtVectorType *Canon
2821 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2822 DependentSizedExtVectorType *New;
2823 if (Canon) {
2824 // We already have a canonical version of this array type; use it as
2825 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002826 New = new (*this, TypeAlignment)
2827 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2828 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002829 } else {
2830 QualType CanonVecTy = getCanonicalType(vecType);
2831 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002832 New = new (*this, TypeAlignment)
2833 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2834 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002835
2836 DependentSizedExtVectorType *CanonCheck
2837 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2838 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2839 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002840 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2841 } else {
2842 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2843 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002844 New = new (*this, TypeAlignment)
2845 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002846 }
2847 }
Mike Stump11289f42009-09-09 15:08:12 +00002848
Douglas Gregor758a8692009-06-17 21:51:59 +00002849 Types.push_back(New);
2850 return QualType(New, 0);
2851}
2852
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002853/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002854///
Jay Foad39c79802011-01-12 09:06:06 +00002855QualType
2856ASTContext::getFunctionNoProtoType(QualType ResultTy,
2857 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002858 const CallingConv CallConv = Info.getCC();
2859
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002860 // Unique functions, to guarantee there is only one function of a particular
2861 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002862 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002863 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002864
Craig Topper36250ad2014-05-12 05:36:57 +00002865 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002866 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002867 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002868 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002869
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002870 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002871 if (!ResultTy.isCanonical()) {
2872 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002873
Chris Lattner47955de2007-01-27 08:37:20 +00002874 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002875 FunctionNoProtoType *NewIP =
2876 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002877 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002878 }
Mike Stump11289f42009-09-09 15:08:12 +00002879
Roman Divacky65b88cd2011-03-01 17:40:53 +00002880 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002881 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002882 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002883 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002884 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002885 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002886}
2887
Douglas Gregorcd780372013-01-17 23:36:45 +00002888/// \brief Determine whether \p T is canonical as the result type of a function.
2889static bool isCanonicalResultType(QualType T) {
2890 return T.isCanonical() &&
2891 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2892 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2893}
2894
Jay Foad39c79802011-01-12 09:06:06 +00002895QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002896ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002897 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002898 size_t NumArgs = ArgArray.size();
2899
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002900 // Unique functions, to guarantee there is only one function of a particular
2901 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002902 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002903 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2904 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002905
Craig Topper36250ad2014-05-12 05:36:57 +00002906 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002907 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002908 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002909 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002910
2911 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002912 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002913 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002914 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002915 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002916 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002917 isCanonical = false;
2918
2919 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002920 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002921 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002922 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002923 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002924 CanonicalArgs.reserve(NumArgs);
2925 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002926 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002927
John McCalldb40c7f2010-12-14 08:05:40 +00002928 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002929 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002930 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002931
Douglas Gregorcd780372013-01-17 23:36:45 +00002932 // Result types do not have ARC lifetime qualifiers.
2933 QualType CanResultTy = getCanonicalType(ResultTy);
2934 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2935 Qualifiers Qs = CanResultTy.getQualifiers();
2936 Qs.removeObjCLifetime();
2937 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2938 }
2939
Jordan Rose5c382722013-03-08 21:51:21 +00002940 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002941
Chris Lattnerfd4de792007-01-27 01:15:32 +00002942 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002943 FunctionProtoType *NewIP =
2944 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002945 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002946 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002947
John McCall31168b02011-06-15 23:02:42 +00002948 // FunctionProtoType objects are allocated with extra bytes after
2949 // them for three variable size arrays at the end:
2950 // - parameter types
2951 // - exception types
2952 // - consumed-arguments flags
2953 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002954 // expression, or information used to resolve the exception
2955 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002956 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002957 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002958 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2959 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2960 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002961 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002962 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002963 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002964 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002965 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002966 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002967 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002968 Size += NumArgs * sizeof(bool);
2969
John McCalldb40c7f2010-12-14 08:05:40 +00002970 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002971 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002972 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002973 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002974 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002975 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002976}
Chris Lattneref51c202006-11-10 07:17:23 +00002977
John McCalle78aac42010-03-10 03:28:59 +00002978#ifndef NDEBUG
2979static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2980 if (!isa<CXXRecordDecl>(D)) return false;
2981 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2982 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2983 return true;
2984 if (RD->getDescribedClassTemplate() &&
2985 !isa<ClassTemplateSpecializationDecl>(RD))
2986 return true;
2987 return false;
2988}
2989#endif
2990
2991/// getInjectedClassNameType - Return the unique reference to the
2992/// injected class name type for the specified templated declaration.
2993QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002994 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002995 assert(NeedsInjectedClassNameType(Decl));
2996 if (Decl->TypeForDecl) {
2997 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002998 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002999 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3000 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3001 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3002 } else {
John McCall424cec92011-01-19 06:33:43 +00003003 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003004 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003005 Decl->TypeForDecl = newType;
3006 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003007 }
3008 return QualType(Decl->TypeForDecl, 0);
3009}
3010
Douglas Gregor83a586e2008-04-13 21:07:44 +00003011/// getTypeDeclType - Return the unique reference to the type for the
3012/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003013QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003014 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003015 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003016
Richard Smithdda56e42011-04-15 14:24:37 +00003017 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003018 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003019
John McCall96f0b5f2010-03-10 06:48:02 +00003020 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3021 "Template type parameter types are always available.");
3022
John McCall81e38502010-02-16 03:57:14 +00003023 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003024 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003025 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003026 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003027 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003028 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003029 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003030 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003031 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003032 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3033 Decl->TypeForDecl = newType;
3034 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003035 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003036 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003037
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003038 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003039}
3040
Chris Lattner32d920b2007-01-26 02:01:53 +00003041/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003042/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003043QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003044ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3045 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003046 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003047
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003048 if (Canonical.isNull())
3049 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003050 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003051 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003052 Decl->TypeForDecl = newType;
3053 Types.push_back(newType);
3054 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003055}
3056
Jay Foad39c79802011-01-12 09:06:06 +00003057QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003058 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3059
Douglas Gregorec9fd132012-01-14 16:38:05 +00003060 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003061 if (PrevDecl->TypeForDecl)
3062 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3063
John McCall424cec92011-01-19 06:33:43 +00003064 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3065 Decl->TypeForDecl = newType;
3066 Types.push_back(newType);
3067 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003068}
3069
Jay Foad39c79802011-01-12 09:06:06 +00003070QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003071 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3072
Douglas Gregorec9fd132012-01-14 16:38:05 +00003073 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003074 if (PrevDecl->TypeForDecl)
3075 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3076
John McCall424cec92011-01-19 06:33:43 +00003077 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3078 Decl->TypeForDecl = newType;
3079 Types.push_back(newType);
3080 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003081}
3082
John McCall81904512011-01-06 01:58:22 +00003083QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3084 QualType modifiedType,
3085 QualType equivalentType) {
3086 llvm::FoldingSetNodeID id;
3087 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3088
Craig Topper36250ad2014-05-12 05:36:57 +00003089 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003090 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3091 if (type) return QualType(type, 0);
3092
3093 QualType canon = getCanonicalType(equivalentType);
3094 type = new (*this, TypeAlignment)
3095 AttributedType(canon, attrKind, modifiedType, equivalentType);
3096
3097 Types.push_back(type);
3098 AttributedTypes.InsertNode(type, insertPos);
3099
3100 return QualType(type, 0);
3101}
3102
3103
John McCallcebee162009-10-18 09:09:24 +00003104/// \brief Retrieve a substitution-result type.
3105QualType
3106ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003107 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003108 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003109 && "replacement types must always be canonical");
3110
3111 llvm::FoldingSetNodeID ID;
3112 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003113 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003114 SubstTemplateTypeParmType *SubstParm
3115 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3116
3117 if (!SubstParm) {
3118 SubstParm = new (*this, TypeAlignment)
3119 SubstTemplateTypeParmType(Parm, Replacement);
3120 Types.push_back(SubstParm);
3121 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3122 }
3123
3124 return QualType(SubstParm, 0);
3125}
3126
Douglas Gregorada4b792011-01-14 02:55:32 +00003127/// \brief Retrieve a
3128QualType ASTContext::getSubstTemplateTypeParmPackType(
3129 const TemplateTypeParmType *Parm,
3130 const TemplateArgument &ArgPack) {
3131#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003132 for (const auto &P : ArgPack.pack_elements()) {
3133 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3134 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003135 }
3136#endif
3137
3138 llvm::FoldingSetNodeID ID;
3139 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003140 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003141 if (SubstTemplateTypeParmPackType *SubstParm
3142 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3143 return QualType(SubstParm, 0);
3144
3145 QualType Canon;
3146 if (!Parm->isCanonicalUnqualified()) {
3147 Canon = getCanonicalType(QualType(Parm, 0));
3148 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3149 ArgPack);
3150 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3151 }
3152
3153 SubstTemplateTypeParmPackType *SubstParm
3154 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3155 ArgPack);
3156 Types.push_back(SubstParm);
3157 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3158 return QualType(SubstParm, 0);
3159}
3160
Douglas Gregoreff93e02009-02-05 23:33:38 +00003161/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003162/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003163/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003164QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003165 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003166 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003167 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003168 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003169 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003170 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003171 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3172
3173 if (TypeParm)
3174 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003175
Chandler Carruth08836322011-05-01 00:51:33 +00003176 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003177 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003178 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003179
3180 TemplateTypeParmType *TypeCheck
3181 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3182 assert(!TypeCheck && "Template type parameter canonical type broken");
3183 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003184 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003185 TypeParm = new (*this, TypeAlignment)
3186 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003187
3188 Types.push_back(TypeParm);
3189 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3190
3191 return QualType(TypeParm, 0);
3192}
3193
John McCalle78aac42010-03-10 03:28:59 +00003194TypeSourceInfo *
3195ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3196 SourceLocation NameLoc,
3197 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003198 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003199 assert(!Name.getAsDependentTemplateName() &&
3200 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003201 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003202
3203 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003204 TemplateSpecializationTypeLoc TL =
3205 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003206 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003207 TL.setTemplateNameLoc(NameLoc);
3208 TL.setLAngleLoc(Args.getLAngleLoc());
3209 TL.setRAngleLoc(Args.getRAngleLoc());
3210 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3211 TL.setArgLocInfo(i, Args[i].getLocInfo());
3212 return DI;
3213}
3214
Mike Stump11289f42009-09-09 15:08:12 +00003215QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003216ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003217 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003218 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003219 assert(!Template.getAsDependentTemplateName() &&
3220 "No dependent template names here!");
3221
John McCall6b51f282009-11-23 01:53:49 +00003222 unsigned NumArgs = Args.size();
3223
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003224 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003225 ArgVec.reserve(NumArgs);
3226 for (unsigned i = 0; i != NumArgs; ++i)
3227 ArgVec.push_back(Args[i].getArgument());
3228
John McCall2408e322010-04-27 00:57:59 +00003229 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003230 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003231}
3232
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003233#ifndef NDEBUG
3234static bool hasAnyPackExpansions(const TemplateArgument *Args,
3235 unsigned NumArgs) {
3236 for (unsigned I = 0; I != NumArgs; ++I)
3237 if (Args[I].isPackExpansion())
3238 return true;
3239
3240 return true;
3241}
3242#endif
3243
John McCall0ad16662009-10-29 08:12:44 +00003244QualType
3245ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003246 const TemplateArgument *Args,
3247 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003248 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003249 assert(!Template.getAsDependentTemplateName() &&
3250 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003251 // Look through qualified template names.
3252 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3253 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003254
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003255 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003256 Template.getAsTemplateDecl() &&
3257 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003258 QualType CanonType;
3259 if (!Underlying.isNull())
3260 CanonType = getCanonicalType(Underlying);
3261 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003262 // We can get here with an alias template when the specialization contains
3263 // a pack expansion that does not match up with a parameter pack.
3264 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3265 "Caller must compute aliased type");
3266 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003267 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3268 NumArgs);
3269 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003270
Douglas Gregora8e02e72009-07-28 23:00:59 +00003271 // Allocate the (non-canonical) template specialization type, but don't
3272 // try to unique it: these types typically have location information that
3273 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003274 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3275 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003276 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003277 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003278 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003279 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3280 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003281
Douglas Gregor8bf42052009-02-09 18:46:07 +00003282 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003283 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003284}
3285
Mike Stump11289f42009-09-09 15:08:12 +00003286QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003287ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3288 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003289 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003290 assert(!Template.getAsDependentTemplateName() &&
3291 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003292
Douglas Gregore29139c2011-03-03 17:04:51 +00003293 // Look through qualified template names.
3294 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3295 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003296
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003297 // Build the canonical template specialization type.
3298 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003299 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003300 CanonArgs.reserve(NumArgs);
3301 for (unsigned I = 0; I != NumArgs; ++I)
3302 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3303
3304 // Determine whether this canonical template specialization type already
3305 // exists.
3306 llvm::FoldingSetNodeID ID;
3307 TemplateSpecializationType::Profile(ID, CanonTemplate,
3308 CanonArgs.data(), NumArgs, *this);
3309
Craig Topper36250ad2014-05-12 05:36:57 +00003310 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003311 TemplateSpecializationType *Spec
3312 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3313
3314 if (!Spec) {
3315 // Allocate a new canonical template specialization type.
3316 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3317 sizeof(TemplateArgument) * NumArgs),
3318 TypeAlignment);
3319 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3320 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003321 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003322 Types.push_back(Spec);
3323 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3324 }
3325
3326 assert(Spec->isDependentType() &&
3327 "Non-dependent template-id type must have a canonical type");
3328 return QualType(Spec, 0);
3329}
3330
3331QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003332ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3333 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003334 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003335 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003336 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003337
Craig Topper36250ad2014-05-12 05:36:57 +00003338 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003339 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003340 if (T)
3341 return QualType(T, 0);
3342
Douglas Gregorc42075a2010-02-04 18:10:26 +00003343 QualType Canon = NamedType;
3344 if (!Canon.isCanonical()) {
3345 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003346 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3347 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003348 (void)CheckT;
3349 }
3350
Abramo Bagnara6150c882010-05-11 21:36:43 +00003351 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003352 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003353 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003354 return QualType(T, 0);
3355}
3356
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003357QualType
Jay Foad39c79802011-01-12 09:06:06 +00003358ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003359 llvm::FoldingSetNodeID ID;
3360 ParenType::Profile(ID, InnerType);
3361
Craig Topper36250ad2014-05-12 05:36:57 +00003362 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003363 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3364 if (T)
3365 return QualType(T, 0);
3366
3367 QualType Canon = InnerType;
3368 if (!Canon.isCanonical()) {
3369 Canon = getCanonicalType(InnerType);
3370 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3371 assert(!CheckT && "Paren canonical type broken");
3372 (void)CheckT;
3373 }
3374
3375 T = new (*this) ParenType(InnerType, Canon);
3376 Types.push_back(T);
3377 ParenTypes.InsertNode(T, InsertPos);
3378 return QualType(T, 0);
3379}
3380
Douglas Gregor02085352010-03-31 20:19:30 +00003381QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3382 NestedNameSpecifier *NNS,
3383 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003384 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003385 if (Canon.isNull()) {
3386 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003387 ElaboratedTypeKeyword CanonKeyword = Keyword;
3388 if (Keyword == ETK_None)
3389 CanonKeyword = ETK_Typename;
3390
3391 if (CanonNNS != NNS || CanonKeyword != Keyword)
3392 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003393 }
3394
3395 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003396 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003397
Craig Topper36250ad2014-05-12 05:36:57 +00003398 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003399 DependentNameType *T
3400 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003401 if (T)
3402 return QualType(T, 0);
3403
Douglas Gregor02085352010-03-31 20:19:30 +00003404 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003405 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003406 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003407 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003408}
3409
Mike Stump11289f42009-09-09 15:08:12 +00003410QualType
John McCallc392f372010-06-11 00:33:02 +00003411ASTContext::getDependentTemplateSpecializationType(
3412 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003413 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003414 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003415 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003416 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003417 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003418 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3419 ArgCopy.push_back(Args[I].getArgument());
3420 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3421 ArgCopy.size(),
3422 ArgCopy.data());
3423}
3424
3425QualType
3426ASTContext::getDependentTemplateSpecializationType(
3427 ElaboratedTypeKeyword Keyword,
3428 NestedNameSpecifier *NNS,
3429 const IdentifierInfo *Name,
3430 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003431 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003432 assert((!NNS || NNS->isDependent()) &&
3433 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003434
Douglas Gregorc42075a2010-02-04 18:10:26 +00003435 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003436 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3437 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003438
Craig Topper36250ad2014-05-12 05:36:57 +00003439 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003440 DependentTemplateSpecializationType *T
3441 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003442 if (T)
3443 return QualType(T, 0);
3444
John McCallc392f372010-06-11 00:33:02 +00003445 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003446
John McCallc392f372010-06-11 00:33:02 +00003447 ElaboratedTypeKeyword CanonKeyword = Keyword;
3448 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3449
3450 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003451 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003452 for (unsigned I = 0; I != NumArgs; ++I) {
3453 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3454 if (!CanonArgs[I].structurallyEquals(Args[I]))
3455 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003456 }
3457
John McCallc392f372010-06-11 00:33:02 +00003458 QualType Canon;
3459 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3460 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3461 Name, NumArgs,
3462 CanonArgs.data());
3463
3464 // Find the insert position again.
3465 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3466 }
3467
3468 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3469 sizeof(TemplateArgument) * NumArgs),
3470 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003471 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003472 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003473 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003474 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003475 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003476}
3477
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003478QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003479 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003480 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003481 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003482
3483 assert(Pattern->containsUnexpandedParameterPack() &&
3484 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003485 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003486 PackExpansionType *T
3487 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3488 if (T)
3489 return QualType(T, 0);
3490
3491 QualType Canon;
3492 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003493 Canon = getCanonicalType(Pattern);
3494 // The canonical type might not contain an unexpanded parameter pack, if it
3495 // contains an alias template specialization which ignores one of its
3496 // parameters.
3497 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003498 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003499
Richard Smith68eea502012-07-16 00:20:35 +00003500 // Find the insert position again, in case we inserted an element into
3501 // PackExpansionTypes and invalidated our insert position.
3502 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3503 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003504 }
3505
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003506 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003507 Types.push_back(T);
3508 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003509 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003510}
3511
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003512/// CmpProtocolNames - Comparison predicate for sorting protocols
3513/// alphabetically.
3514static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3515 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003516 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003517}
3518
John McCall8b07ec22010-05-15 11:32:37 +00003519static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003520 unsigned NumProtocols) {
3521 if (NumProtocols == 0) return true;
3522
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003523 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3524 return false;
3525
John McCallfc93cf92009-10-22 22:37:11 +00003526 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003527 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3528 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003529 return false;
3530 return true;
3531}
3532
3533static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003534 unsigned &NumProtocols) {
3535 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003536
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003537 // Sort protocols, keyed by name.
3538 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3539
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003540 // Canonicalize.
3541 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3542 Protocols[I] = Protocols[I]->getCanonicalDecl();
3543
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003544 // Remove duplicates.
3545 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3546 NumProtocols = ProtocolsEnd-Protocols;
3547}
3548
John McCall8b07ec22010-05-15 11:32:37 +00003549QualType ASTContext::getObjCObjectType(QualType BaseType,
3550 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003551 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003552 // If the base type is an interface and there aren't any protocols
3553 // to add, then the interface type will do just fine.
3554 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3555 return BaseType;
3556
3557 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003558 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003559 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003560 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003561 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3562 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003563
John McCall8b07ec22010-05-15 11:32:37 +00003564 // Build the canonical type, which has the canonical base type and
3565 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003566 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003567 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3568 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3569 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003570 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003571 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003572 unsigned UniqueCount = NumProtocols;
3573
John McCallfc93cf92009-10-22 22:37:11 +00003574 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003575 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3576 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003577 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003578 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3579 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003580 }
3581
3582 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003583 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3584 }
3585
3586 unsigned Size = sizeof(ObjCObjectTypeImpl);
3587 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3588 void *Mem = Allocate(Size, TypeAlignment);
3589 ObjCObjectTypeImpl *T =
3590 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3591
3592 Types.push_back(T);
3593 ObjCObjectTypes.InsertNode(T, InsertPos);
3594 return QualType(T, 0);
3595}
3596
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003597/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3598/// protocol list adopt all protocols in QT's qualified-id protocol
3599/// list.
3600bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3601 ObjCInterfaceDecl *IC) {
3602 if (!QT->isObjCQualifiedIdType())
3603 return false;
3604
3605 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3606 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003607 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003608 if (!IC->ClassImplementsProtocol(Proto, false))
3609 return false;
3610 }
3611 return true;
3612 }
3613 return false;
3614}
3615
3616/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3617/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3618/// of protocols.
3619bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3620 ObjCInterfaceDecl *IDecl) {
3621 if (!QT->isObjCQualifiedIdType())
3622 return false;
3623 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3624 if (!OPT)
3625 return false;
3626 if (!IDecl->hasDefinition())
3627 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003628 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3629 CollectInheritedProtocols(IDecl, InheritedProtocols);
3630 if (InheritedProtocols.empty())
3631 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003632 // Check that if every protocol in list of id<plist> conforms to a protcol
3633 // of IDecl's, then bridge casting is ok.
3634 bool Conforms = false;
3635 for (auto *Proto : OPT->quals()) {
3636 Conforms = false;
3637 for (auto *PI : InheritedProtocols) {
3638 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3639 Conforms = true;
3640 break;
3641 }
3642 }
3643 if (!Conforms)
3644 break;
3645 }
3646 if (Conforms)
3647 return true;
3648
Aaron Ballman83731462014-03-17 16:14:00 +00003649 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003650 // If both the right and left sides have qualifiers.
3651 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003652 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003653 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003654 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003655 break;
3656 }
3657 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003658 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003659 }
3660 return true;
3661}
3662
John McCall8b07ec22010-05-15 11:32:37 +00003663/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3664/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003665QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003666 llvm::FoldingSetNodeID ID;
3667 ObjCObjectPointerType::Profile(ID, ObjectT);
3668
Craig Topper36250ad2014-05-12 05:36:57 +00003669 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003670 if (ObjCObjectPointerType *QT =
3671 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3672 return QualType(QT, 0);
3673
3674 // Find the canonical object type.
3675 QualType Canonical;
3676 if (!ObjectT.isCanonical()) {
3677 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3678
3679 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003680 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3681 }
3682
Douglas Gregorf85bee62010-02-08 22:59:26 +00003683 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003684 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3685 ObjCObjectPointerType *QType =
3686 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Steve Narofffb4330f2009-06-17 22:40:22 +00003688 Types.push_back(QType);
3689 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003690 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003691}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003692
Douglas Gregor1c283312010-08-11 12:19:30 +00003693/// getObjCInterfaceType - Return the unique reference to the type for the
3694/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003695QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3696 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003697 if (Decl->TypeForDecl)
3698 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003699
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003700 if (PrevDecl) {
3701 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3702 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3703 return QualType(PrevDecl->TypeForDecl, 0);
3704 }
3705
Douglas Gregor7671e532011-12-16 16:34:57 +00003706 // Prefer the definition, if there is one.
3707 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3708 Decl = Def;
3709
Douglas Gregor1c283312010-08-11 12:19:30 +00003710 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3711 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3712 Decl->TypeForDecl = T;
3713 Types.push_back(T);
3714 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003715}
3716
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003717/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3718/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003719/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003720/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003721/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003722QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003723 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003724 if (tofExpr->isTypeDependent()) {
3725 llvm::FoldingSetNodeID ID;
3726 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003727
Craig Topper36250ad2014-05-12 05:36:57 +00003728 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003729 DependentTypeOfExprType *Canon
3730 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3731 if (Canon) {
3732 // We already have a "canonical" version of an identical, dependent
3733 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003734 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003735 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003736 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003737 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003738 Canon
3739 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003740 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3741 toe = Canon;
3742 }
3743 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003744 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003745 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003746 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003747 Types.push_back(toe);
3748 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003749}
3750
Steve Naroffa773cd52007-08-01 18:02:17 +00003751/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003752/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003753/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003754/// an issue. This doesn't affect the type checker, since it operates
3755/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003756QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003757 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003758 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003759 Types.push_back(tot);
3760 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003761}
3762
Anders Carlssonad6bd352009-06-24 21:24:56 +00003763
Richard Smith8eb1d322014-06-05 20:13:13 +00003764/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3765/// nodes. This would never be helpful, since each such type has its own
3766/// expression, and would not give a significant memory saving, since there
3767/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003768QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003769 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003770
3771 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003772 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003773 // unique dependent type. Two such decltype-specifiers refer to the same
3774 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003775 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003776 llvm::FoldingSetNodeID ID;
3777 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003778
Craig Topper36250ad2014-05-12 05:36:57 +00003779 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003780 DependentDecltypeType *Canon
3781 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003782 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003783 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003784 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003785 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003786 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003787 dt = new (*this, TypeAlignment)
3788 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003789 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003790 dt = new (*this, TypeAlignment)
3791 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003792 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003793 Types.push_back(dt);
3794 return QualType(dt, 0);
3795}
3796
Alexis Hunte852b102011-05-24 22:41:36 +00003797/// getUnaryTransformationType - We don't unique these, since the memory
3798/// savings are minimal and these are rare.
3799QualType ASTContext::getUnaryTransformType(QualType BaseType,
3800 QualType UnderlyingType,
3801 UnaryTransformType::UTTKind Kind)
3802 const {
3803 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003804 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3805 Kind,
3806 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003807 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003808 Types.push_back(Ty);
3809 return QualType(Ty, 0);
3810}
3811
Richard Smith2a7d4812013-05-04 07:00:32 +00003812/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3813/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3814/// canonical deduced-but-dependent 'auto' type.
3815QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003816 bool IsDependent) const {
3817 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003818 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003819
Richard Smith2a7d4812013-05-04 07:00:32 +00003820 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003821 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003822 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003823 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003824 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3825 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003826
Richard Smith74aeef52013-04-26 16:15:35 +00003827 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003828 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003829 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003830 Types.push_back(AT);
3831 if (InsertPos)
3832 AutoTypes.InsertNode(AT, InsertPos);
3833 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003834}
3835
Eli Friedman0dfb8892011-10-06 23:00:33 +00003836/// getAtomicType - Return the uniqued reference to the atomic type for
3837/// the given value type.
3838QualType ASTContext::getAtomicType(QualType T) const {
3839 // Unique pointers, to guarantee there is only one pointer of a particular
3840 // structure.
3841 llvm::FoldingSetNodeID ID;
3842 AtomicType::Profile(ID, T);
3843
Craig Topper36250ad2014-05-12 05:36:57 +00003844 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003845 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3846 return QualType(AT, 0);
3847
3848 // If the atomic value type isn't canonical, this won't be a canonical type
3849 // either, so fill in the canonical type field.
3850 QualType Canonical;
3851 if (!T.isCanonical()) {
3852 Canonical = getAtomicType(getCanonicalType(T));
3853
3854 // Get the new insert position for the node we care about.
3855 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003856 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003857 }
3858 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3859 Types.push_back(New);
3860 AtomicTypes.InsertNode(New, InsertPos);
3861 return QualType(New, 0);
3862}
3863
Richard Smith02e85f32011-04-14 22:09:26 +00003864/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3865QualType ASTContext::getAutoDeductType() const {
3866 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003867 AutoDeductTy = QualType(
3868 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003869 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003870 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003871 return AutoDeductTy;
3872}
3873
3874/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3875QualType ASTContext::getAutoRRefDeductType() const {
3876 if (AutoRRefDeductTy.isNull())
3877 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3878 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3879 return AutoRRefDeductTy;
3880}
3881
Chris Lattnerfb072462007-01-23 05:45:31 +00003882/// getTagDeclType - Return the unique reference to the type for the
3883/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003884QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003885 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003886 // FIXME: What is the design on getTagDeclType when it requires casting
3887 // away const? mutable?
3888 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003889}
3890
Mike Stump11289f42009-09-09 15:08:12 +00003891/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3892/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3893/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003894CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003895 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003896}
Chris Lattnerfb072462007-01-23 05:45:31 +00003897
Hans Wennborg27541db2011-10-27 08:29:09 +00003898/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3899CanQualType ASTContext::getIntMaxType() const {
3900 return getFromTargetType(Target->getIntMaxType());
3901}
3902
3903/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3904CanQualType ASTContext::getUIntMaxType() const {
3905 return getFromTargetType(Target->getUIntMaxType());
3906}
3907
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003908/// getSignedWCharType - Return the type of "signed wchar_t".
3909/// Used when in C++, as a GCC extension.
3910QualType ASTContext::getSignedWCharType() const {
3911 // FIXME: derive from "Target" ?
3912 return WCharTy;
3913}
3914
3915/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3916/// Used when in C++, as a GCC extension.
3917QualType ASTContext::getUnsignedWCharType() const {
3918 // FIXME: derive from "Target" ?
3919 return UnsignedIntTy;
3920}
3921
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003922QualType ASTContext::getIntPtrType() const {
3923 return getFromTargetType(Target->getIntPtrType());
3924}
3925
3926QualType ASTContext::getUIntPtrType() const {
3927 return getCorrespondingUnsignedType(getIntPtrType());
3928}
3929
Hans Wennborg27541db2011-10-27 08:29:09 +00003930/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003931/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3932QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003933 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003934}
3935
Eli Friedman4e91899e2012-11-27 02:58:24 +00003936/// \brief Return the unique type for "pid_t" defined in
3937/// <sys/types.h>. We need this to compute the correct type for vfork().
3938QualType ASTContext::getProcessIDType() const {
3939 return getFromTargetType(Target->getProcessIDType());
3940}
3941
Chris Lattnera21ad802008-04-02 05:18:44 +00003942//===----------------------------------------------------------------------===//
3943// Type Operators
3944//===----------------------------------------------------------------------===//
3945
Jay Foad39c79802011-01-12 09:06:06 +00003946CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003947 // Push qualifiers into arrays, and then discard any remaining
3948 // qualifiers.
3949 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003950 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003951 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003952 QualType Result;
3953 if (isa<ArrayType>(Ty)) {
3954 Result = getArrayDecayedType(QualType(Ty,0));
3955 } else if (isa<FunctionType>(Ty)) {
3956 Result = getPointerType(QualType(Ty, 0));
3957 } else {
3958 Result = QualType(Ty, 0);
3959 }
3960
3961 return CanQualType::CreateUnsafe(Result);
3962}
3963
John McCall6c9dd522011-01-18 07:41:22 +00003964QualType ASTContext::getUnqualifiedArrayType(QualType type,
3965 Qualifiers &quals) {
3966 SplitQualType splitType = type.getSplitUnqualifiedType();
3967
3968 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3969 // the unqualified desugared type and then drops it on the floor.
3970 // We then have to strip that sugar back off with
3971 // getUnqualifiedDesugaredType(), which is silly.
3972 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003973 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003974
3975 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003976 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003977 quals = splitType.Quals;
3978 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003979 }
3980
John McCall6c9dd522011-01-18 07:41:22 +00003981 // Otherwise, recurse on the array's element type.
3982 QualType elementType = AT->getElementType();
3983 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3984
3985 // If that didn't change the element type, AT has no qualifiers, so we
3986 // can just use the results in splitType.
3987 if (elementType == unqualElementType) {
3988 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003989 quals = splitType.Quals;
3990 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003991 }
3992
3993 // Otherwise, add in the qualifiers from the outermost type, then
3994 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003995 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003996
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003997 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003998 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003999 CAT->getSizeModifier(), 0);
4000 }
4001
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004002 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004003 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004004 }
4005
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004006 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004007 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004008 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004009 VAT->getSizeModifier(),
4010 VAT->getIndexTypeCVRQualifiers(),
4011 VAT->getBracketsRange());
4012 }
4013
4014 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004015 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004016 DSAT->getSizeModifier(), 0,
4017 SourceRange());
4018}
4019
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004020/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4021/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4022/// they point to and return true. If T1 and T2 aren't pointer types
4023/// or pointer-to-member types, or if they are not similar at this
4024/// level, returns false and leaves T1 and T2 unchanged. Top-level
4025/// qualifiers on T1 and T2 are ignored. This function will typically
4026/// be called in a loop that successively "unwraps" pointer and
4027/// pointer-to-member types to compare them at each level.
4028bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4029 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4030 *T2PtrType = T2->getAs<PointerType>();
4031 if (T1PtrType && T2PtrType) {
4032 T1 = T1PtrType->getPointeeType();
4033 T2 = T2PtrType->getPointeeType();
4034 return true;
4035 }
4036
4037 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4038 *T2MPType = T2->getAs<MemberPointerType>();
4039 if (T1MPType && T2MPType &&
4040 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4041 QualType(T2MPType->getClass(), 0))) {
4042 T1 = T1MPType->getPointeeType();
4043 T2 = T2MPType->getPointeeType();
4044 return true;
4045 }
4046
David Blaikiebbafb8a2012-03-11 07:00:24 +00004047 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004048 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4049 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4050 if (T1OPType && T2OPType) {
4051 T1 = T1OPType->getPointeeType();
4052 T2 = T2OPType->getPointeeType();
4053 return true;
4054 }
4055 }
4056
4057 // FIXME: Block pointers, too?
4058
4059 return false;
4060}
4061
Jay Foad39c79802011-01-12 09:06:06 +00004062DeclarationNameInfo
4063ASTContext::getNameForTemplate(TemplateName Name,
4064 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004065 switch (Name.getKind()) {
4066 case TemplateName::QualifiedTemplate:
4067 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004068 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004069 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4070 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004071
John McCalld9dfe3a2011-06-30 08:33:18 +00004072 case TemplateName::OverloadedTemplate: {
4073 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4074 // DNInfo work in progress: CHECKME: what about DNLoc?
4075 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4076 }
4077
4078 case TemplateName::DependentTemplate: {
4079 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004080 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004081 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004082 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4083 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004084 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004085 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4086 // DNInfo work in progress: FIXME: source locations?
4087 DeclarationNameLoc DNLoc;
4088 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4089 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4090 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004091 }
4092 }
4093
John McCalld9dfe3a2011-06-30 08:33:18 +00004094 case TemplateName::SubstTemplateTemplateParm: {
4095 SubstTemplateTemplateParmStorage *subst
4096 = Name.getAsSubstTemplateTemplateParm();
4097 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4098 NameLoc);
4099 }
4100
4101 case TemplateName::SubstTemplateTemplateParmPack: {
4102 SubstTemplateTemplateParmPackStorage *subst
4103 = Name.getAsSubstTemplateTemplateParmPack();
4104 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4105 NameLoc);
4106 }
4107 }
4108
4109 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004110}
4111
Jay Foad39c79802011-01-12 09:06:06 +00004112TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004113 switch (Name.getKind()) {
4114 case TemplateName::QualifiedTemplate:
4115 case TemplateName::Template: {
4116 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004117 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004118 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004119 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4120
4121 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004122 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004123 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004124
John McCalld9dfe3a2011-06-30 08:33:18 +00004125 case TemplateName::OverloadedTemplate:
4126 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004127
John McCalld9dfe3a2011-06-30 08:33:18 +00004128 case TemplateName::DependentTemplate: {
4129 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4130 assert(DTN && "Non-dependent template names must refer to template decls.");
4131 return DTN->CanonicalTemplateName;
4132 }
4133
4134 case TemplateName::SubstTemplateTemplateParm: {
4135 SubstTemplateTemplateParmStorage *subst
4136 = Name.getAsSubstTemplateTemplateParm();
4137 return getCanonicalTemplateName(subst->getReplacement());
4138 }
4139
4140 case TemplateName::SubstTemplateTemplateParmPack: {
4141 SubstTemplateTemplateParmPackStorage *subst
4142 = Name.getAsSubstTemplateTemplateParmPack();
4143 TemplateTemplateParmDecl *canonParameter
4144 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4145 TemplateArgument canonArgPack
4146 = getCanonicalTemplateArgument(subst->getArgumentPack());
4147 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4148 }
4149 }
4150
4151 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004152}
4153
Douglas Gregoradee3e32009-11-11 23:06:43 +00004154bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4155 X = getCanonicalTemplateName(X);
4156 Y = getCanonicalTemplateName(Y);
4157 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4158}
4159
Mike Stump11289f42009-09-09 15:08:12 +00004160TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004161ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004162 switch (Arg.getKind()) {
4163 case TemplateArgument::Null:
4164 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004165
Douglas Gregora8e02e72009-07-28 23:00:59 +00004166 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004167 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004168
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004169 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004170 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004171 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004172 }
Mike Stump11289f42009-09-09 15:08:12 +00004173
Eli Friedmanb826a002012-09-26 02:36:12 +00004174 case TemplateArgument::NullPtr:
4175 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4176 /*isNullPtr*/true);
4177
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004178 case TemplateArgument::Template:
4179 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004180
4181 case TemplateArgument::TemplateExpansion:
4182 return TemplateArgument(getCanonicalTemplateName(
4183 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004184 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004185
Douglas Gregora8e02e72009-07-28 23:00:59 +00004186 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004187 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004188
Douglas Gregora8e02e72009-07-28 23:00:59 +00004189 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004190 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004191
Douglas Gregora8e02e72009-07-28 23:00:59 +00004192 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004193 if (Arg.pack_size() == 0)
4194 return Arg;
4195
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004196 TemplateArgument *CanonArgs
4197 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004198 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004199 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004200 AEnd = Arg.pack_end();
4201 A != AEnd; (void)++A, ++Idx)
4202 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004203
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004204 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004205 }
4206 }
4207
4208 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004209 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004210}
4211
Douglas Gregor333489b2009-03-27 23:10:48 +00004212NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004213ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004214 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004215 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004216
4217 switch (NNS->getKind()) {
4218 case NestedNameSpecifier::Identifier:
4219 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004220 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004221 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4222 NNS->getAsIdentifier());
4223
4224 case NestedNameSpecifier::Namespace:
4225 // A namespace is canonical; build a nested-name-specifier with
4226 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004227 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004228 NNS->getAsNamespace()->getOriginalNamespace());
4229
4230 case NestedNameSpecifier::NamespaceAlias:
4231 // A namespace is canonical; build a nested-name-specifier with
4232 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004233 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004234 NNS->getAsNamespaceAlias()->getNamespace()
4235 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004236
4237 case NestedNameSpecifier::TypeSpec:
4238 case NestedNameSpecifier::TypeSpecWithTemplate: {
4239 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004240
4241 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4242 // break it apart into its prefix and identifier, then reconsititute those
4243 // as the canonical nested-name-specifier. This is required to canonicalize
4244 // a dependent nested-name-specifier involving typedefs of dependent-name
4245 // types, e.g.,
4246 // typedef typename T::type T1;
4247 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004248 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4249 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004250 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004251
Eli Friedman5358a0a2012-03-03 04:09:56 +00004252 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4253 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4254 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004255 return NestedNameSpecifier::Create(*this, nullptr, false,
4256 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004257 }
4258
4259 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004260 case NestedNameSpecifier::Super:
4261 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004262 return NNS;
4263 }
4264
David Blaikie8a40f702012-01-17 06:56:22 +00004265 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004266}
4267
Chris Lattner7adf0762008-08-04 07:31:14 +00004268
Jay Foad39c79802011-01-12 09:06:06 +00004269const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004270 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004271 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004272 // Handle the common positive case fast.
4273 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4274 return AT;
4275 }
Mike Stump11289f42009-09-09 15:08:12 +00004276
John McCall8ccfcb52009-09-24 19:53:00 +00004277 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004278 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004279 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004280
John McCall8ccfcb52009-09-24 19:53:00 +00004281 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004282 // implements C99 6.7.3p8: "If the specification of an array type includes
4283 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004284
Chris Lattner7adf0762008-08-04 07:31:14 +00004285 // If we get here, we either have type qualifiers on the type, or we have
4286 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004287 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004288
John McCall33ddac02011-01-19 10:06:00 +00004289 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004290 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004291
Chris Lattner7adf0762008-08-04 07:31:14 +00004292 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004293 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004294 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004295 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004296
Chris Lattner7adf0762008-08-04 07:31:14 +00004297 // Otherwise, we have an array and we have qualifiers on it. Push the
4298 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004299 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004300
Chris Lattner7adf0762008-08-04 07:31:14 +00004301 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4302 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4303 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004304 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004305 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4306 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4307 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004308 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004309
Mike Stump11289f42009-09-09 15:08:12 +00004310 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004311 = dyn_cast<DependentSizedArrayType>(ATy))
4312 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004313 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004314 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004315 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004316 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004317 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004318
Chris Lattner7adf0762008-08-04 07:31:14 +00004319 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004320 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004321 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004322 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004323 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004324 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004325}
4326
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004327QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004328 if (T->isArrayType() || T->isFunctionType())
4329 return getDecayedType(T);
4330 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004331}
4332
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004333QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004334 T = getVariableArrayDecayedType(T);
4335 T = getAdjustedParameterType(T);
4336 return T.getUnqualifiedType();
4337}
4338
Chris Lattnera21ad802008-04-02 05:18:44 +00004339/// getArrayDecayedType - Return the properly qualified result of decaying the
4340/// specified array type to a pointer. This operation is non-trivial when
4341/// handling typedefs etc. The canonical type of "T" must be an array type,
4342/// this returns a pointer to a properly qualified element of the array.
4343///
4344/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004345QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004346 // Get the element type with 'getAsArrayType' so that we don't lose any
4347 // typedefs in the element type of the array. This also handles propagation
4348 // of type qualifiers from the array type into the element type if present
4349 // (C99 6.7.3p8).
4350 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4351 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004352
Chris Lattner7adf0762008-08-04 07:31:14 +00004353 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004354
4355 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004356 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004357}
4358
John McCall33ddac02011-01-19 10:06:00 +00004359QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4360 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004361}
4362
John McCall33ddac02011-01-19 10:06:00 +00004363QualType ASTContext::getBaseElementType(QualType type) const {
4364 Qualifiers qs;
4365 while (true) {
4366 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004367 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004368 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004369
John McCall33ddac02011-01-19 10:06:00 +00004370 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004371 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004372 }
Mike Stump11289f42009-09-09 15:08:12 +00004373
John McCall33ddac02011-01-19 10:06:00 +00004374 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004375}
4376
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004377/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004378uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004379ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4380 uint64_t ElementCount = 1;
4381 do {
4382 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004383 CA = dyn_cast_or_null<ConstantArrayType>(
4384 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004385 } while (CA);
4386 return ElementCount;
4387}
4388
Steve Naroff0af91202007-04-27 21:51:21 +00004389/// getFloatingRank - Return a relative rank for floating point types.
4390/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004391static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004392 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004393 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004394
John McCall9dd450b2009-09-21 23:43:11 +00004395 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4396 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004397 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004398 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004399 case BuiltinType::Float: return FloatRank;
4400 case BuiltinType::Double: return DoubleRank;
4401 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004402 }
4403}
4404
Mike Stump11289f42009-09-09 15:08:12 +00004405/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4406/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004407/// 'typeDomain' is a real floating point or complex type.
4408/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004409QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4410 QualType Domain) const {
4411 FloatingRank EltRank = getFloatingRank(Size);
4412 if (Domain->isComplexType()) {
4413 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004414 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004415 case FloatRank: return FloatComplexTy;
4416 case DoubleRank: return DoubleComplexTy;
4417 case LongDoubleRank: return LongDoubleComplexTy;
4418 }
Steve Naroff0af91202007-04-27 21:51:21 +00004419 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004420
4421 assert(Domain->isRealFloatingType() && "Unknown domain!");
4422 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004423 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004424 case FloatRank: return FloatTy;
4425 case DoubleRank: return DoubleTy;
4426 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004427 }
David Blaikief47fa302012-01-17 02:30:50 +00004428 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004429}
4430
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004431/// getFloatingTypeOrder - Compare the rank of the two specified floating
4432/// point types, ignoring the domain of the type (i.e. 'double' ==
4433/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004434/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004435int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004436 FloatingRank LHSR = getFloatingRank(LHS);
4437 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004438
Chris Lattnerb90739d2008-04-06 23:38:49 +00004439 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004440 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004441 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004442 return 1;
4443 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004444}
4445
Chris Lattner76a00cf2008-04-06 22:59:24 +00004446/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4447/// routine will assert if passed a built-in type that isn't an integer or enum,
4448/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004449unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004450 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004451
Chris Lattner76a00cf2008-04-06 22:59:24 +00004452 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004453 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004454 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004455 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004456 case BuiltinType::Char_S:
4457 case BuiltinType::Char_U:
4458 case BuiltinType::SChar:
4459 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004460 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004461 case BuiltinType::Short:
4462 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004463 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004464 case BuiltinType::Int:
4465 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004466 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004467 case BuiltinType::Long:
4468 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004469 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004470 case BuiltinType::LongLong:
4471 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004472 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004473 case BuiltinType::Int128:
4474 case BuiltinType::UInt128:
4475 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004476 }
4477}
4478
Eli Friedman629ffb92009-08-20 04:21:42 +00004479/// \brief Whether this is a promotable bitfield reference according
4480/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4481///
4482/// \returns the type this bit-field will promote to, or NULL if no
4483/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004484QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004485 if (E->isTypeDependent() || E->isValueDependent())
4486 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004487
4488 // FIXME: We should not do this unless E->refersToBitField() is true. This
4489 // matters in C where getSourceBitField() will find bit-fields for various
4490 // cases where the source expression is not a bit-field designator.
4491
John McCalld25db7e2013-05-06 21:39:12 +00004492 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004493 if (!Field)
4494 return QualType();
4495
4496 QualType FT = Field->getType();
4497
Richard Smithcaf33902011-10-10 18:28:20 +00004498 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004499 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004500 // C++ [conv.prom]p5:
4501 // A prvalue for an integral bit-field can be converted to a prvalue of type
4502 // int if int can represent all the values of the bit-field; otherwise, it
4503 // can be converted to unsigned int if unsigned int can represent all the
4504 // values of the bit-field. If the bit-field is larger yet, no integral
4505 // promotion applies to it.
4506 // C11 6.3.1.1/2:
4507 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4508 // If an int can represent all values of the original type (as restricted by
4509 // the width, for a bit-field), the value is converted to an int; otherwise,
4510 // it is converted to an unsigned int.
4511 //
4512 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4513 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004514 if (BitWidth < IntSize)
4515 return IntTy;
4516
4517 if (BitWidth == IntSize)
4518 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4519
4520 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004521 // like the base type. GCC has some weird bugs in this area that we
4522 // deliberately do not follow (GCC follows a pre-standard resolution to
4523 // C's DR315 which treats bit-width as being part of the type, and this leaks
4524 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004525 return QualType();
4526}
4527
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004528/// getPromotedIntegerType - Returns the type that Promotable will
4529/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4530/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004531QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004532 assert(!Promotable.isNull());
4533 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004534 if (const EnumType *ET = Promotable->getAs<EnumType>())
4535 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004536
4537 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4538 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4539 // (3.9.1) can be converted to a prvalue of the first of the following
4540 // types that can represent all the values of its underlying type:
4541 // int, unsigned int, long int, unsigned long int, long long int, or
4542 // unsigned long long int [...]
4543 // FIXME: Is there some better way to compute this?
4544 if (BT->getKind() == BuiltinType::WChar_S ||
4545 BT->getKind() == BuiltinType::WChar_U ||
4546 BT->getKind() == BuiltinType::Char16 ||
4547 BT->getKind() == BuiltinType::Char32) {
4548 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4549 uint64_t FromSize = getTypeSize(BT);
4550 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4551 LongLongTy, UnsignedLongLongTy };
4552 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4553 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4554 if (FromSize < ToSize ||
4555 (FromSize == ToSize &&
4556 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4557 return PromoteTypes[Idx];
4558 }
4559 llvm_unreachable("char type should fit into long long");
4560 }
4561 }
4562
4563 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004564 if (Promotable->isSignedIntegerType())
4565 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004566 uint64_t PromotableSize = getIntWidth(Promotable);
4567 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004568 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4569 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4570}
4571
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004572/// \brief Recurses in pointer/array types until it finds an objc retainable
4573/// type and returns its ownership.
4574Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4575 while (!T.isNull()) {
4576 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4577 return T.getObjCLifetime();
4578 if (T->isArrayType())
4579 T = getBaseElementType(T);
4580 else if (const PointerType *PT = T->getAs<PointerType>())
4581 T = PT->getPointeeType();
4582 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004583 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004584 else
4585 break;
4586 }
4587
4588 return Qualifiers::OCL_None;
4589}
4590
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004591static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4592 // Incomplete enum types are not treated as integer types.
4593 // FIXME: In C++, enum types are never integer types.
4594 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4595 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004596 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004597}
4598
Mike Stump11289f42009-09-09 15:08:12 +00004599/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004600/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004601/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004602int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004603 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4604 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004605
4606 // Unwrap enums to their underlying type.
4607 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4608 LHSC = getIntegerTypeForEnum(ET);
4609 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4610 RHSC = getIntegerTypeForEnum(ET);
4611
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004612 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004613
Chris Lattner76a00cf2008-04-06 22:59:24 +00004614 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4615 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004616
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004617 unsigned LHSRank = getIntegerRank(LHSC);
4618 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004619
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004620 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4621 if (LHSRank == RHSRank) return 0;
4622 return LHSRank > RHSRank ? 1 : -1;
4623 }
Mike Stump11289f42009-09-09 15:08:12 +00004624
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004625 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4626 if (LHSUnsigned) {
4627 // If the unsigned [LHS] type is larger, return it.
4628 if (LHSRank >= RHSRank)
4629 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004630
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004631 // If the signed type can represent all values of the unsigned type, it
4632 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004633 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004634 return -1;
4635 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004636
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004637 // If the unsigned [RHS] type is larger, return it.
4638 if (RHSRank >= LHSRank)
4639 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004640
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004641 // If the signed type can represent all values of the unsigned type, it
4642 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004643 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004644 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004645}
Anders Carlsson98f07902007-08-17 05:31:46 +00004646
Mike Stump11289f42009-09-09 15:08:12 +00004647// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004648QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004649 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004650 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004651 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004652
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004653 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004654
Anders Carlsson98f07902007-08-17 05:31:46 +00004655 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004656 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004657 // int flags;
4658 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004659 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004660 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004661 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004662 FieldTypes[3] = LongTy;
4663
Anders Carlsson98f07902007-08-17 05:31:46 +00004664 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004665 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004666 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004667 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004668 SourceLocation(), nullptr,
4669 FieldTypes[i], /*TInfo=*/nullptr,
4670 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004671 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004672 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004673 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004674 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004675 }
4676
Douglas Gregord5058122010-02-11 01:19:42 +00004677 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004678 }
Mike Stump11289f42009-09-09 15:08:12 +00004679
Anders Carlsson98f07902007-08-17 05:31:46 +00004680 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004681}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004682
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004683QualType ASTContext::getObjCSuperType() const {
4684 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004685 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004686 TUDecl->addDecl(ObjCSuperTypeDecl);
4687 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4688 }
4689 return ObjCSuperType;
4690}
4691
Douglas Gregor512b0772009-04-23 22:29:11 +00004692void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004693 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004694 assert(Rec && "Invalid CFConstantStringType");
4695 CFConstantStringTypeDecl = Rec->getDecl();
4696}
4697
Jay Foad39c79802011-01-12 09:06:06 +00004698QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004699 if (BlockDescriptorType)
4700 return getTagDeclType(BlockDescriptorType);
4701
Alp Toker2dea15b2013-12-17 01:22:38 +00004702 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004703 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004704 RD = buildImplicitRecord("__block_descriptor");
4705 RD->startDefinition();
4706
Mike Stumpd0153282009-10-20 02:12:22 +00004707 QualType FieldTypes[] = {
4708 UnsignedLongTy,
4709 UnsignedLongTy,
4710 };
4711
Craig Topperd6d31ac2013-07-15 08:24:27 +00004712 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004713 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004714 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004715 };
4716
4717 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004718 FieldDecl *Field = FieldDecl::Create(
4719 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004720 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4721 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004722 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004723 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004724 }
4725
Alp Toker2dea15b2013-12-17 01:22:38 +00004726 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004727
Alp Toker2dea15b2013-12-17 01:22:38 +00004728 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004729
4730 return getTagDeclType(BlockDescriptorType);
4731}
4732
Jay Foad39c79802011-01-12 09:06:06 +00004733QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004734 if (BlockDescriptorExtendedType)
4735 return getTagDeclType(BlockDescriptorExtendedType);
4736
Alp Toker2dea15b2013-12-17 01:22:38 +00004737 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004738 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004739 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4740 RD->startDefinition();
4741
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004742 QualType FieldTypes[] = {
4743 UnsignedLongTy,
4744 UnsignedLongTy,
4745 getPointerType(VoidPtrTy),
4746 getPointerType(VoidPtrTy)
4747 };
4748
Craig Topperd6d31ac2013-07-15 08:24:27 +00004749 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004750 "reserved",
4751 "Size",
4752 "CopyFuncPtr",
4753 "DestroyFuncPtr"
4754 };
4755
4756 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004757 FieldDecl *Field = FieldDecl::Create(
4758 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004759 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4760 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004761 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004762 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004763 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004764 }
4765
Alp Toker2dea15b2013-12-17 01:22:38 +00004766 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004767
Alp Toker2dea15b2013-12-17 01:22:38 +00004768 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004769 return getTagDeclType(BlockDescriptorExtendedType);
4770}
4771
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004772/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4773/// requires copy/dispose. Note that this must match the logic
4774/// in buildByrefHelpers.
4775bool ASTContext::BlockRequiresCopying(QualType Ty,
4776 const VarDecl *D) {
4777 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4778 const Expr *copyExpr = getBlockVarCopyInits(D);
4779 if (!copyExpr && record->hasTrivialDestructor()) return false;
4780
Mike Stump94967902009-10-21 18:16:27 +00004781 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004782 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004783
4784 if (!Ty->isObjCRetainableType()) return false;
4785
4786 Qualifiers qs = Ty.getQualifiers();
4787
4788 // If we have lifetime, that dominates.
4789 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4790 assert(getLangOpts().ObjCAutoRefCount);
4791
4792 switch (lifetime) {
4793 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4794
4795 // These are just bits as far as the runtime is concerned.
4796 case Qualifiers::OCL_ExplicitNone:
4797 case Qualifiers::OCL_Autoreleasing:
4798 return false;
4799
4800 // Tell the runtime that this is ARC __weak, called by the
4801 // byref routines.
4802 case Qualifiers::OCL_Weak:
4803 // ARC __strong __block variables need to be retained.
4804 case Qualifiers::OCL_Strong:
4805 return true;
4806 }
4807 llvm_unreachable("fell out of lifetime switch!");
4808 }
4809 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4810 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004811}
4812
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004813bool ASTContext::getByrefLifetime(QualType Ty,
4814 Qualifiers::ObjCLifetime &LifeTime,
4815 bool &HasByrefExtendedLayout) const {
4816
4817 if (!getLangOpts().ObjC1 ||
4818 getLangOpts().getGC() != LangOptions::NonGC)
4819 return false;
4820
4821 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004822 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004823 HasByrefExtendedLayout = true;
4824 LifeTime = Qualifiers::OCL_None;
4825 }
4826 else if (getLangOpts().ObjCAutoRefCount)
4827 LifeTime = Ty.getObjCLifetime();
4828 // MRR.
4829 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4830 LifeTime = Qualifiers::OCL_ExplicitNone;
4831 else
4832 LifeTime = Qualifiers::OCL_None;
4833 return true;
4834}
4835
Douglas Gregorbab8a962011-09-08 01:46:34 +00004836TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4837 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004838 ObjCInstanceTypeDecl =
4839 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004840 return ObjCInstanceTypeDecl;
4841}
4842
Anders Carlsson18acd442007-10-29 06:33:42 +00004843// This returns true if a type has been typedefed to BOOL:
4844// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004845static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004846 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004847 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4848 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004849
Anders Carlssond8499822007-10-29 05:01:08 +00004850 return false;
4851}
4852
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004853/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004854/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004855CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004856 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4857 return CharUnits::Zero();
4858
Ken Dyck40775002010-01-11 17:06:35 +00004859 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004860
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004861 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004862 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004863 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004864 // Treat arrays as pointers, since that's how they're passed in.
4865 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004866 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004867 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004868}
4869
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004870bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4871 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4872 VD->getType()->isIntegralOrEnumerationType() &&
4873 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4874}
4875
Ken Dyck40775002010-01-11 17:06:35 +00004876static inline
4877std::string charUnitsToString(const CharUnits &CU) {
4878 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004879}
4880
John McCall351762c2011-02-07 10:33:21 +00004881/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004882/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004883std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4884 std::string S;
4885
David Chisnall950a9512009-11-17 19:33:30 +00004886 const BlockDecl *Decl = Expr->getBlockDecl();
4887 QualType BlockTy =
4888 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4889 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004890 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004891 getObjCEncodingForMethodParameter(
4892 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4893 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004894 else
Alp Toker314cc812014-01-25 16:55:45 +00004895 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004896 // Compute size of all parameters.
4897 // Start with computing size of a pointer in number of bytes.
4898 // FIXME: There might(should) be a better way of doing this computation!
4899 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004900 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4901 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004902 for (auto PI : Decl->params()) {
4903 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004904 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004905 if (sz.isZero())
4906 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004907 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004908 ParmOffset += sz;
4909 }
4910 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004911 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004912 // Block pointer and offset.
4913 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004914
4915 // Argument types.
4916 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004917 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004918 QualType PType = PVDecl->getOriginalType();
4919 if (const ArrayType *AT =
4920 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4921 // Use array's original type only if it has known number of
4922 // elements.
4923 if (!isa<ConstantArrayType>(AT))
4924 PType = PVDecl->getType();
4925 } else if (PType->isFunctionType())
4926 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004927 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004928 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4929 S, true /*Extended*/);
4930 else
4931 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004932 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004933 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004934 }
John McCall351762c2011-02-07 10:33:21 +00004935
4936 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004937}
4938
Douglas Gregora9d84932011-05-27 01:19:52 +00004939bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004940 std::string& S) {
4941 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004942 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004943 CharUnits ParmOffset;
4944 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004945 for (auto PI : Decl->params()) {
4946 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004947 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004948 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004949 continue;
4950
David Chisnall50e4eba2010-12-30 14:05:53 +00004951 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004952 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004953 ParmOffset += sz;
4954 }
4955 S += charUnitsToString(ParmOffset);
4956 ParmOffset = CharUnits::Zero();
4957
4958 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004959 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004960 QualType PType = PVDecl->getOriginalType();
4961 if (const ArrayType *AT =
4962 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4963 // Use array's original type only if it has known number of
4964 // elements.
4965 if (!isa<ConstantArrayType>(AT))
4966 PType = PVDecl->getType();
4967 } else if (PType->isFunctionType())
4968 PType = PVDecl->getType();
4969 getObjCEncodingForType(PType, S);
4970 S += charUnitsToString(ParmOffset);
4971 ParmOffset += getObjCEncodingTypeSize(PType);
4972 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004973
4974 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004975}
4976
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004977/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4978/// method parameter or return type. If Extended, include class names and
4979/// block object types.
4980void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4981 QualType T, std::string& S,
4982 bool Extended) const {
4983 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4984 getObjCEncodingForTypeQualifier(QT, S);
4985 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00004986 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004987 true /*OutermostType*/,
4988 false /*EncodingProperty*/,
4989 false /*StructField*/,
4990 Extended /*EncodeBlockParameters*/,
4991 Extended /*EncodeClassNames*/);
4992}
4993
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004994/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004995/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004996bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004997 std::string& S,
4998 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004999 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005000 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005001 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5002 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005003 // Compute size of all parameters.
5004 // Start with computing size of a pointer in number of bytes.
5005 // FIXME: There might(should) be a better way of doing this computation!
5006 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005007 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005008 // The first two arguments (self and _cmd) are pointers; account for
5009 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005010 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005011 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005012 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005013 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005014 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005015 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005016 continue;
5017
Ken Dyck40775002010-01-11 17:06:35 +00005018 assert (sz.isPositive() &&
5019 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005020 ParmOffset += sz;
5021 }
Ken Dyck40775002010-01-11 17:06:35 +00005022 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005023 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005024 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005025
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005026 // Argument types.
5027 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005028 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005029 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005030 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005031 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005032 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005033 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5034 // Use array's original type only if it has known number of
5035 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005036 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005037 PType = PVDecl->getType();
5038 } else if (PType->isFunctionType())
5039 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005040 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5041 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005042 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005043 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005044 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005045
5046 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005047}
5048
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005049ObjCPropertyImplDecl *
5050ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5051 const ObjCPropertyDecl *PD,
5052 const Decl *Container) const {
5053 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005054 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005055 if (const ObjCCategoryImplDecl *CID =
5056 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005057 for (auto *PID : CID->property_impls())
5058 if (PID->getPropertyDecl() == PD)
5059 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005060 } else {
5061 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5062 for (auto *PID : OID->property_impls())
5063 if (PID->getPropertyDecl() == PD)
5064 return PID;
5065 }
5066 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005067}
5068
Daniel Dunbar4932b362008-08-28 04:38:10 +00005069/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005070/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005071/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5072/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005073/// Property attributes are stored as a comma-delimited C string. The simple
5074/// attributes readonly and bycopy are encoded as single characters. The
5075/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5076/// encoded as single characters, followed by an identifier. Property types
5077/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005078/// these attributes are defined by the following enumeration:
5079/// @code
5080/// enum PropertyAttributes {
5081/// kPropertyReadOnly = 'R', // property is read-only.
5082/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5083/// kPropertyByref = '&', // property is a reference to the value last assigned
5084/// kPropertyDynamic = 'D', // property is dynamic
5085/// kPropertyGetter = 'G', // followed by getter selector name
5086/// kPropertySetter = 'S', // followed by setter selector name
5087/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005088/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005089/// kPropertyWeak = 'W' // 'weak' property
5090/// kPropertyStrong = 'P' // property GC'able
5091/// kPropertyNonAtomic = 'N' // property non-atomic
5092/// };
5093/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005094void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005095 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005096 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005097 // Collect information from the property implementation decl(s).
5098 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005099 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005100
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005101 if (ObjCPropertyImplDecl *PropertyImpDecl =
5102 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5103 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5104 Dynamic = true;
5105 else
5106 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005107 }
5108
5109 // FIXME: This is not very efficient.
5110 S = "T";
5111
5112 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005113 // GCC has some special rules regarding encoding of properties which
5114 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005115 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005116
5117 if (PD->isReadOnly()) {
5118 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005119 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5120 S += ",C";
5121 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5122 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005123 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5124 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005125 } else {
5126 switch (PD->getSetterKind()) {
5127 case ObjCPropertyDecl::Assign: break;
5128 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005129 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005130 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005131 }
5132 }
5133
5134 // It really isn't clear at all what this means, since properties
5135 // are "dynamic by default".
5136 if (Dynamic)
5137 S += ",D";
5138
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005139 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5140 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005141
Daniel Dunbar4932b362008-08-28 04:38:10 +00005142 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5143 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005144 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005145 }
5146
5147 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5148 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005149 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005150 }
5151
5152 if (SynthesizePID) {
5153 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5154 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005155 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005156 }
5157
5158 // FIXME: OBJCGC: weak & strong
5159}
5160
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005161/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005162/// Another legacy compatibility encoding: 32-bit longs are encoded as
5163/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005164/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5165///
5166void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005167 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005168 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005169 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005170 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005171 else
Jay Foad39c79802011-01-12 09:06:06 +00005172 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005173 PointeeTy = IntTy;
5174 }
5175 }
5176}
5177
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005178void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005179 const FieldDecl *Field,
5180 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005181 // We follow the behavior of gcc, expanding structures which are
5182 // directly pointed to, and expanding embedded structures. Note that
5183 // these rules are sufficient to prevent recursive encoding of the
5184 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005185 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005186 true /* outermost type */, false, false,
5187 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005188}
5189
Joe Groff98ac7d22014-07-07 22:25:15 +00005190void ASTContext::getObjCEncodingForPropertyType(QualType T,
5191 std::string& S) const {
5192 // Encode result type.
5193 // GCC has some special rules regarding encoding of properties which
5194 // closely resembles encoding of ivars.
5195 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5196 true /* outermost type */,
5197 true /* encoding property */);
5198}
5199
John McCall393a78d2012-12-20 02:45:14 +00005200static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5201 BuiltinType::Kind kind) {
5202 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005203 case BuiltinType::Void: return 'v';
5204 case BuiltinType::Bool: return 'B';
5205 case BuiltinType::Char_U:
5206 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005207 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005208 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005209 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005210 case BuiltinType::UInt: return 'I';
5211 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005212 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005213 case BuiltinType::UInt128: return 'T';
5214 case BuiltinType::ULongLong: return 'Q';
5215 case BuiltinType::Char_S:
5216 case BuiltinType::SChar: return 'c';
5217 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005218 case BuiltinType::WChar_S:
5219 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005220 case BuiltinType::Int: return 'i';
5221 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005222 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005223 case BuiltinType::LongLong: return 'q';
5224 case BuiltinType::Int128: return 't';
5225 case BuiltinType::Float: return 'f';
5226 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005227 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005228 case BuiltinType::NullPtr: return '*'; // like char*
5229
5230 case BuiltinType::Half:
5231 // FIXME: potentially need @encodes for these!
5232 return ' ';
5233
5234 case BuiltinType::ObjCId:
5235 case BuiltinType::ObjCClass:
5236 case BuiltinType::ObjCSel:
5237 llvm_unreachable("@encoding ObjC primitive type");
5238
5239 // OpenCL and placeholder types don't need @encodings.
5240 case BuiltinType::OCLImage1d:
5241 case BuiltinType::OCLImage1dArray:
5242 case BuiltinType::OCLImage1dBuffer:
5243 case BuiltinType::OCLImage2d:
5244 case BuiltinType::OCLImage2dArray:
5245 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005246 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005247 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005248 case BuiltinType::Dependent:
5249#define BUILTIN_TYPE(KIND, ID)
5250#define PLACEHOLDER_TYPE(KIND, ID) \
5251 case BuiltinType::KIND:
5252#include "clang/AST/BuiltinTypes.def"
5253 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005254 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005255 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005256}
5257
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005258static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5259 EnumDecl *Enum = ET->getDecl();
5260
5261 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5262 if (!Enum->isFixed())
5263 return 'i';
5264
5265 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005266 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5267 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005268}
5269
Jay Foad39c79802011-01-12 09:06:06 +00005270static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005271 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005272 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005273 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005274 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5275 // The GNU runtime requires more information; bitfields are encoded as b,
5276 // then the offset (in bits) of the first element, then the type of the
5277 // bitfield, then the size in bits. For example, in this structure:
5278 //
5279 // struct
5280 // {
5281 // int integer;
5282 // int flags:2;
5283 // };
5284 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5285 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5286 // information is not especially sensible, but we're stuck with it for
5287 // compatibility with GCC, although providing it breaks anything that
5288 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005289 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005290 const RecordDecl *RD = FD->getParent();
5291 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005292 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005293 if (const EnumType *ET = T->getAs<EnumType>())
5294 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005295 else {
5296 const BuiltinType *BT = T->castAs<BuiltinType>();
5297 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5298 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005299 }
Richard Smithcaf33902011-10-10 18:28:20 +00005300 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005301}
5302
Daniel Dunbar07d07852009-10-18 21:17:35 +00005303// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005304void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5305 bool ExpandPointedToStructures,
5306 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005307 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005308 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005309 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005310 bool StructField,
5311 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005312 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005313 bool EncodePointerToObjCTypedef,
5314 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005315 CanQualType CT = getCanonicalType(T);
5316 switch (CT->getTypeClass()) {
5317 case Type::Builtin:
5318 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005319 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005320 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005321 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5322 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5323 else
5324 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005325 return;
Mike Stump11289f42009-09-09 15:08:12 +00005326
John McCall393a78d2012-12-20 02:45:14 +00005327 case Type::Complex: {
5328 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005329 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005330 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005331 return;
5332 }
John McCall393a78d2012-12-20 02:45:14 +00005333
5334 case Type::Atomic: {
5335 const AtomicType *AT = T->castAs<AtomicType>();
5336 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005337 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005338 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005339 }
John McCall393a78d2012-12-20 02:45:14 +00005340
5341 // encoding for pointer or reference types.
5342 case Type::Pointer:
5343 case Type::LValueReference:
5344 case Type::RValueReference: {
5345 QualType PointeeTy;
5346 if (isa<PointerType>(CT)) {
5347 const PointerType *PT = T->castAs<PointerType>();
5348 if (PT->isObjCSelType()) {
5349 S += ':';
5350 return;
5351 }
5352 PointeeTy = PT->getPointeeType();
5353 } else {
5354 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5355 }
5356
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005357 bool isReadOnly = false;
5358 // For historical/compatibility reasons, the read-only qualifier of the
5359 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5360 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005361 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005362 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005363 if (OutermostType && T.isConstQualified()) {
5364 isReadOnly = true;
5365 S += 'r';
5366 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005367 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005368 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005369 while (P->getAs<PointerType>())
5370 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005371 if (P.isConstQualified()) {
5372 isReadOnly = true;
5373 S += 'r';
5374 }
5375 }
5376 if (isReadOnly) {
5377 // Another legacy compatibility encoding. Some ObjC qualifier and type
5378 // combinations need to be rearranged.
5379 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005380 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005381 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005382 }
Mike Stump11289f42009-09-09 15:08:12 +00005383
Anders Carlssond8499822007-10-29 05:01:08 +00005384 if (PointeeTy->isCharType()) {
5385 // char pointer types should be encoded as '*' unless it is a
5386 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005387 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005388 S += '*';
5389 return;
5390 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005391 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005392 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5393 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5394 S += '#';
5395 return;
5396 }
5397 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5398 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5399 S += '@';
5400 return;
5401 }
5402 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005403 }
Anders Carlssond8499822007-10-29 05:01:08 +00005404 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005405 getLegacyIntegralTypeEncoding(PointeeTy);
5406
Mike Stump11289f42009-09-09 15:08:12 +00005407 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005408 nullptr, false, false, false, false, false, false,
5409 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005410 return;
5411 }
John McCall393a78d2012-12-20 02:45:14 +00005412
5413 case Type::ConstantArray:
5414 case Type::IncompleteArray:
5415 case Type::VariableArray: {
5416 const ArrayType *AT = cast<ArrayType>(CT);
5417
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005418 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005419 // Incomplete arrays are encoded as a pointer to the array element.
5420 S += '^';
5421
Mike Stump11289f42009-09-09 15:08:12 +00005422 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005423 false, ExpandStructures, FD);
5424 } else {
5425 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005426
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005427 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5428 S += llvm::utostr(CAT->getSize().getZExtValue());
5429 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005430 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005431 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5432 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005433 S += '0';
5434 }
Mike Stump11289f42009-09-09 15:08:12 +00005435
5436 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005437 false, ExpandStructures, FD,
5438 false, false, false, false, false, false,
5439 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005440 S += ']';
5441 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005442 return;
5443 }
Mike Stump11289f42009-09-09 15:08:12 +00005444
John McCall393a78d2012-12-20 02:45:14 +00005445 case Type::FunctionNoProto:
5446 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005447 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005448 return;
Mike Stump11289f42009-09-09 15:08:12 +00005449
John McCall393a78d2012-12-20 02:45:14 +00005450 case Type::Record: {
5451 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005452 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005453 // Anonymous structures print as '?'
5454 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5455 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005456 if (ClassTemplateSpecializationDecl *Spec
5457 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5458 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005459 llvm::raw_string_ostream OS(S);
5460 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005461 TemplateArgs.data(),
5462 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005463 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005464 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005465 } else {
5466 S += '?';
5467 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005468 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005469 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005470 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005471 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005472 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005473 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005474 if (FD) {
5475 S += '"';
5476 S += Field->getNameAsString();
5477 S += '"';
5478 }
Mike Stump11289f42009-09-09 15:08:12 +00005479
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005480 // Special case bit-fields.
5481 if (Field->isBitField()) {
5482 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005483 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005484 } else {
5485 QualType qt = Field->getType();
5486 getLegacyIntegralTypeEncoding(qt);
5487 getObjCEncodingForTypeImpl(qt, S, false, true,
5488 FD, /*OutermostType*/false,
5489 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005490 /*StructField*/true,
5491 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005492 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005493 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005494 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005495 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005496 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005497 return;
5498 }
Mike Stump11289f42009-09-09 15:08:12 +00005499
John McCall393a78d2012-12-20 02:45:14 +00005500 case Type::BlockPointer: {
5501 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005502 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005503 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005504 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005505
5506 S += '<';
5507 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005508 getObjCEncodingForTypeImpl(
5509 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5510 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005511 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5512 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005513 // Block self
5514 S += "@?";
5515 // Block parameters
5516 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005517 for (const auto &I : FPT->param_types())
5518 getObjCEncodingForTypeImpl(
5519 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5520 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005521 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5522 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005523 }
5524 S += '>';
5525 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005526 return;
5527 }
Mike Stump11289f42009-09-09 15:08:12 +00005528
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005529 case Type::ObjCObject: {
5530 // hack to match legacy encoding of *id and *Class
5531 QualType Ty = getObjCObjectPointerType(CT);
5532 if (Ty->isObjCIdType()) {
5533 S += "{objc_object=}";
5534 return;
5535 }
5536 else if (Ty->isObjCClassType()) {
5537 S += "{objc_class=}";
5538 return;
5539 }
5540 }
5541
John McCall393a78d2012-12-20 02:45:14 +00005542 case Type::ObjCInterface: {
5543 // Ignore protocol qualifiers when mangling at this level.
5544 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005545
John McCall393a78d2012-12-20 02:45:14 +00005546 // The assumption seems to be that this assert will succeed
5547 // because nested levels will have filtered out 'id' and 'Class'.
5548 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005549 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005550 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005551 S += '{';
5552 const IdentifierInfo *II = OI->getIdentifier();
5553 S += II->getName();
5554 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005555 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005556 DeepCollectObjCIvars(OI, true, Ivars);
5557 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005558 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005559 if (Field->isBitField())
5560 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005561 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005562 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5563 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005564 EncodePointerToObjCTypedef,
5565 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005566 }
5567 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005568 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005569 }
Mike Stump11289f42009-09-09 15:08:12 +00005570
John McCall393a78d2012-12-20 02:45:14 +00005571 case Type::ObjCObjectPointer: {
5572 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005573 if (OPT->isObjCIdType()) {
5574 S += '@';
5575 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005576 }
Mike Stump11289f42009-09-09 15:08:12 +00005577
Steve Narofff0c86112009-10-28 22:03:49 +00005578 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5579 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5580 // Since this is a binary compatibility issue, need to consult with runtime
5581 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005582 S += '#';
5583 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005584 }
Mike Stump11289f42009-09-09 15:08:12 +00005585
Chris Lattnere7cabb92009-07-13 00:10:46 +00005586 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005587 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005588 ExpandPointedToStructures,
5589 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005590 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005591 // Note that we do extended encoding of protocol qualifer list
5592 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005593 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005594 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005595 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005596 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005597 S += '>';
5598 }
5599 S += '"';
5600 }
5601 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005602 }
Mike Stump11289f42009-09-09 15:08:12 +00005603
Chris Lattnere7cabb92009-07-13 00:10:46 +00005604 QualType PointeeTy = OPT->getPointeeType();
5605 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005606 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5607 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005608 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005609 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005610 // {...};
5611 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005612 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005613 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005614 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5615 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5616 DeepCollectObjCIvars(OI, true, Ivars);
5617 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5618 if (cast<FieldDecl>(Ivars[i]) == FD) {
5619 S += '{';
5620 S += OI->getIdentifier()->getName();
5621 S += '}';
5622 return;
5623 }
5624 }
5625 }
Mike Stump11289f42009-09-09 15:08:12 +00005626 getObjCEncodingForTypeImpl(PointeeTy, S,
5627 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005628 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005629 false, false, false, false, false,
5630 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005631 return;
5632 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005633
5634 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005635 if (OPT->getInterfaceDecl() &&
5636 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005637 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005638 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005639 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005640 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005641 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005642 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005643 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005644 S += '"';
5645 }
5646 return;
5647 }
Mike Stump11289f42009-09-09 15:08:12 +00005648
John McCalla9e6e8d2010-05-17 23:56:34 +00005649 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005650 // FIXME: we shoul do better than that. 'M' is available.
5651 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005652 // This matches gcc's encoding, even though technically it is insufficient.
5653 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005654 case Type::Vector:
5655 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005656 // Until we have a coherent encoding of these three types, issue warning.
5657 { if (NotEncodedT)
5658 *NotEncodedT = T;
5659 return;
5660 }
5661
5662 // We could see an undeduced auto type here during error recovery.
5663 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005664 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005665 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005666
Richard Smith27d807c2013-04-30 13:56:41 +00005667
John McCall393a78d2012-12-20 02:45:14 +00005668#define ABSTRACT_TYPE(KIND, BASE)
5669#define TYPE(KIND, BASE)
5670#define DEPENDENT_TYPE(KIND, BASE) \
5671 case Type::KIND:
5672#define NON_CANONICAL_TYPE(KIND, BASE) \
5673 case Type::KIND:
5674#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5675 case Type::KIND:
5676#include "clang/AST/TypeNodes.def"
5677 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005678 }
John McCall393a78d2012-12-20 02:45:14 +00005679 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005680}
5681
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005682void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5683 std::string &S,
5684 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005685 bool includeVBases,
5686 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005687 assert(RDecl && "Expected non-null RecordDecl");
5688 assert(!RDecl->isUnion() && "Should not be called for unions");
5689 if (!RDecl->getDefinition())
5690 return;
5691
5692 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5693 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5694 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5695
5696 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005697 for (const auto &BI : CXXRec->bases()) {
5698 if (!BI.isVirtual()) {
5699 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005700 if (base->isEmpty())
5701 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005702 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005703 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5704 std::make_pair(offs, base));
5705 }
5706 }
5707 }
5708
5709 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005710 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005711 uint64_t offs = layout.getFieldOffset(i);
5712 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005713 std::make_pair(offs, Field));
5714 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005715 }
5716
5717 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005718 for (const auto &BI : CXXRec->vbases()) {
5719 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005720 if (base->isEmpty())
5721 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005722 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005723 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5724 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005725 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5726 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005727 }
5728 }
5729
5730 CharUnits size;
5731 if (CXXRec) {
5732 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5733 } else {
5734 size = layout.getSize();
5735 }
5736
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005737#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005738 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005739#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005740 std::multimap<uint64_t, NamedDecl *>::iterator
5741 CurLayObj = FieldOrBaseOffsets.begin();
5742
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005743 if (CXXRec && CXXRec->isDynamicClass() &&
5744 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005745 if (FD) {
5746 S += "\"_vptr$";
5747 std::string recname = CXXRec->getNameAsString();
5748 if (recname.empty()) recname = "?";
5749 S += recname;
5750 S += '"';
5751 }
5752 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005753#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005754 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005755#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005756 }
5757
5758 if (!RDecl->hasFlexibleArrayMember()) {
5759 // Mark the end of the structure.
5760 uint64_t offs = toBits(size);
5761 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005762 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005763 }
5764
5765 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005766#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005767 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005768 if (CurOffs < CurLayObj->first) {
5769 uint64_t padding = CurLayObj->first - CurOffs;
5770 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5771 // packing/alignment of members is different that normal, in which case
5772 // the encoding will be out-of-sync with the real layout.
5773 // If the runtime switches to just consider the size of types without
5774 // taking into account alignment, we could make padding explicit in the
5775 // encoding (e.g. using arrays of chars). The encoding strings would be
5776 // longer then though.
5777 CurOffs += padding;
5778 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005779#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005780
5781 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005782 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005783 break; // reached end of structure.
5784
5785 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5786 // We expand the bases without their virtual bases since those are going
5787 // in the initial structure. Note that this differs from gcc which
5788 // expands virtual bases each time one is encountered in the hierarchy,
5789 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005790 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5791 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005792 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005793#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005794 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005795#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005796 } else {
5797 FieldDecl *field = cast<FieldDecl>(dcl);
5798 if (FD) {
5799 S += '"';
5800 S += field->getNameAsString();
5801 S += '"';
5802 }
5803
5804 if (field->isBitField()) {
5805 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005806#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005807 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005808#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005809 } else {
5810 QualType qt = field->getType();
5811 getLegacyIntegralTypeEncoding(qt);
5812 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5813 /*OutermostType*/false,
5814 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005815 /*StructField*/true,
5816 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005817#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005818 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005819#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005820 }
5821 }
5822 }
5823}
5824
Mike Stump11289f42009-09-09 15:08:12 +00005825void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005826 std::string& S) const {
5827 if (QT & Decl::OBJC_TQ_In)
5828 S += 'n';
5829 if (QT & Decl::OBJC_TQ_Inout)
5830 S += 'N';
5831 if (QT & Decl::OBJC_TQ_Out)
5832 S += 'o';
5833 if (QT & Decl::OBJC_TQ_Bycopy)
5834 S += 'O';
5835 if (QT & Decl::OBJC_TQ_Byref)
5836 S += 'R';
5837 if (QT & Decl::OBJC_TQ_Oneway)
5838 S += 'V';
5839}
5840
Douglas Gregor3ea72692011-08-12 05:46:01 +00005841TypedefDecl *ASTContext::getObjCIdDecl() const {
5842 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005843 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005844 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005845 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005846 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005847 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005848}
5849
Douglas Gregor52e02802011-08-12 06:17:30 +00005850TypedefDecl *ASTContext::getObjCSelDecl() const {
5851 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005852 QualType T = getPointerType(ObjCBuiltinSelTy);
5853 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005854 }
5855 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005856}
5857
Douglas Gregor0a586182011-08-12 05:59:41 +00005858TypedefDecl *ASTContext::getObjCClassDecl() const {
5859 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005860 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005861 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005862 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005863 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005864 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005865}
5866
Douglas Gregord53ae832012-01-17 18:09:05 +00005867ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5868 if (!ObjCProtocolClassDecl) {
5869 ObjCProtocolClassDecl
5870 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5871 SourceLocation(),
5872 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005873 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005874 SourceLocation(), true);
5875 }
5876
5877 return ObjCProtocolClassDecl;
5878}
5879
Meador Inge5d3fb222012-06-16 03:34:49 +00005880//===----------------------------------------------------------------------===//
5881// __builtin_va_list Construction Functions
5882//===----------------------------------------------------------------------===//
5883
5884static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5885 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005886 QualType T = Context->getPointerType(Context->CharTy);
5887 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005888}
5889
5890static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5891 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005892 QualType T = Context->getPointerType(Context->VoidTy);
5893 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005894}
5895
Tim Northover9bb857a2013-01-31 12:13:10 +00005896static TypedefDecl *
5897CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005898 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005899 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005900 if (Context->getLangOpts().CPlusPlus) {
5901 // namespace std { struct __va_list {
5902 NamespaceDecl *NS;
5903 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5904 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005905 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005906 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005907 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005908 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005909 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005910 }
5911
5912 VaListTagDecl->startDefinition();
5913
5914 const size_t NumFields = 5;
5915 QualType FieldTypes[NumFields];
5916 const char *FieldNames[NumFields];
5917
5918 // void *__stack;
5919 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5920 FieldNames[0] = "__stack";
5921
5922 // void *__gr_top;
5923 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5924 FieldNames[1] = "__gr_top";
5925
5926 // void *__vr_top;
5927 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5928 FieldNames[2] = "__vr_top";
5929
5930 // int __gr_offs;
5931 FieldTypes[3] = Context->IntTy;
5932 FieldNames[3] = "__gr_offs";
5933
5934 // int __vr_offs;
5935 FieldTypes[4] = Context->IntTy;
5936 FieldNames[4] = "__vr_offs";
5937
5938 // Create fields
5939 for (unsigned i = 0; i < NumFields; ++i) {
5940 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5941 VaListTagDecl,
5942 SourceLocation(),
5943 SourceLocation(),
5944 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005945 FieldTypes[i], /*TInfo=*/nullptr,
5946 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005947 /*Mutable=*/false,
5948 ICIS_NoInit);
5949 Field->setAccess(AS_public);
5950 VaListTagDecl->addDecl(Field);
5951 }
5952 VaListTagDecl->completeDefinition();
5953 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5954 Context->VaListTagTy = VaListTagType;
5955
5956 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005957 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005958}
5959
Meador Inge5d3fb222012-06-16 03:34:49 +00005960static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5961 // typedef struct __va_list_tag {
5962 RecordDecl *VaListTagDecl;
5963
Alp Toker2dea15b2013-12-17 01:22:38 +00005964 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005965 VaListTagDecl->startDefinition();
5966
5967 const size_t NumFields = 5;
5968 QualType FieldTypes[NumFields];
5969 const char *FieldNames[NumFields];
5970
5971 // unsigned char gpr;
5972 FieldTypes[0] = Context->UnsignedCharTy;
5973 FieldNames[0] = "gpr";
5974
5975 // unsigned char fpr;
5976 FieldTypes[1] = Context->UnsignedCharTy;
5977 FieldNames[1] = "fpr";
5978
5979 // unsigned short reserved;
5980 FieldTypes[2] = Context->UnsignedShortTy;
5981 FieldNames[2] = "reserved";
5982
5983 // void* overflow_arg_area;
5984 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5985 FieldNames[3] = "overflow_arg_area";
5986
5987 // void* reg_save_area;
5988 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5989 FieldNames[4] = "reg_save_area";
5990
5991 // Create fields
5992 for (unsigned i = 0; i < NumFields; ++i) {
5993 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5994 SourceLocation(),
5995 SourceLocation(),
5996 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005997 FieldTypes[i], /*TInfo=*/nullptr,
5998 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00005999 /*Mutable=*/false,
6000 ICIS_NoInit);
6001 Field->setAccess(AS_public);
6002 VaListTagDecl->addDecl(Field);
6003 }
6004 VaListTagDecl->completeDefinition();
6005 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006006 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006007
6008 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006009 TypedefDecl *VaListTagTypedefDecl =
6010 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6011
Meador Inge5d3fb222012-06-16 03:34:49 +00006012 QualType VaListTagTypedefType =
6013 Context->getTypedefType(VaListTagTypedefDecl);
6014
6015 // typedef __va_list_tag __builtin_va_list[1];
6016 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6017 QualType VaListTagArrayType
6018 = Context->getConstantArrayType(VaListTagTypedefType,
6019 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006020 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006021}
6022
6023static TypedefDecl *
6024CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6025 // typedef struct __va_list_tag {
6026 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006027 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006028 VaListTagDecl->startDefinition();
6029
6030 const size_t NumFields = 4;
6031 QualType FieldTypes[NumFields];
6032 const char *FieldNames[NumFields];
6033
6034 // unsigned gp_offset;
6035 FieldTypes[0] = Context->UnsignedIntTy;
6036 FieldNames[0] = "gp_offset";
6037
6038 // unsigned fp_offset;
6039 FieldTypes[1] = Context->UnsignedIntTy;
6040 FieldNames[1] = "fp_offset";
6041
6042 // void* overflow_arg_area;
6043 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6044 FieldNames[2] = "overflow_arg_area";
6045
6046 // void* reg_save_area;
6047 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6048 FieldNames[3] = "reg_save_area";
6049
6050 // Create fields
6051 for (unsigned i = 0; i < NumFields; ++i) {
6052 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6053 VaListTagDecl,
6054 SourceLocation(),
6055 SourceLocation(),
6056 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006057 FieldTypes[i], /*TInfo=*/nullptr,
6058 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006059 /*Mutable=*/false,
6060 ICIS_NoInit);
6061 Field->setAccess(AS_public);
6062 VaListTagDecl->addDecl(Field);
6063 }
6064 VaListTagDecl->completeDefinition();
6065 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006066 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006067
6068 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006069 TypedefDecl *VaListTagTypedefDecl =
6070 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6071
Meador Inge5d3fb222012-06-16 03:34:49 +00006072 QualType VaListTagTypedefType =
6073 Context->getTypedefType(VaListTagTypedefDecl);
6074
6075 // typedef __va_list_tag __builtin_va_list[1];
6076 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6077 QualType VaListTagArrayType
6078 = Context->getConstantArrayType(VaListTagTypedefType,
6079 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006080 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006081}
6082
6083static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6084 // typedef int __builtin_va_list[4];
6085 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6086 QualType IntArrayType
6087 = Context->getConstantArrayType(Context->IntTy,
6088 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006089 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006090}
6091
Logan Chien57086ce2012-10-10 06:56:20 +00006092static TypedefDecl *
6093CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006094 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006095 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006096 if (Context->getLangOpts().CPlusPlus) {
6097 // namespace std { struct __va_list {
6098 NamespaceDecl *NS;
6099 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6100 Context->getTranslationUnitDecl(),
6101 /*Inline*/false, SourceLocation(),
6102 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006103 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006104 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006105 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006106 }
6107
6108 VaListDecl->startDefinition();
6109
6110 // void * __ap;
6111 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6112 VaListDecl,
6113 SourceLocation(),
6114 SourceLocation(),
6115 &Context->Idents.get("__ap"),
6116 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006117 /*TInfo=*/nullptr,
6118 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006119 /*Mutable=*/false,
6120 ICIS_NoInit);
6121 Field->setAccess(AS_public);
6122 VaListDecl->addDecl(Field);
6123
6124 // };
6125 VaListDecl->completeDefinition();
6126
6127 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006128 QualType T = Context->getRecordType(VaListDecl);
6129 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006130}
6131
Ulrich Weigand47445072013-05-06 16:26:41 +00006132static TypedefDecl *
6133CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6134 // typedef struct __va_list_tag {
6135 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006136 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006137 VaListTagDecl->startDefinition();
6138
6139 const size_t NumFields = 4;
6140 QualType FieldTypes[NumFields];
6141 const char *FieldNames[NumFields];
6142
6143 // long __gpr;
6144 FieldTypes[0] = Context->LongTy;
6145 FieldNames[0] = "__gpr";
6146
6147 // long __fpr;
6148 FieldTypes[1] = Context->LongTy;
6149 FieldNames[1] = "__fpr";
6150
6151 // void *__overflow_arg_area;
6152 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6153 FieldNames[2] = "__overflow_arg_area";
6154
6155 // void *__reg_save_area;
6156 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6157 FieldNames[3] = "__reg_save_area";
6158
6159 // Create fields
6160 for (unsigned i = 0; i < NumFields; ++i) {
6161 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6162 VaListTagDecl,
6163 SourceLocation(),
6164 SourceLocation(),
6165 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006166 FieldTypes[i], /*TInfo=*/nullptr,
6167 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006168 /*Mutable=*/false,
6169 ICIS_NoInit);
6170 Field->setAccess(AS_public);
6171 VaListTagDecl->addDecl(Field);
6172 }
6173 VaListTagDecl->completeDefinition();
6174 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6175 Context->VaListTagTy = VaListTagType;
6176
6177 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006178 TypedefDecl *VaListTagTypedefDecl =
6179 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006180 QualType VaListTagTypedefType =
6181 Context->getTypedefType(VaListTagTypedefDecl);
6182
6183 // typedef __va_list_tag __builtin_va_list[1];
6184 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6185 QualType VaListTagArrayType
6186 = Context->getConstantArrayType(VaListTagTypedefType,
6187 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006188
Alp Toker56b5cc92013-12-15 10:36:26 +00006189 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006190}
6191
Meador Inge5d3fb222012-06-16 03:34:49 +00006192static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6193 TargetInfo::BuiltinVaListKind Kind) {
6194 switch (Kind) {
6195 case TargetInfo::CharPtrBuiltinVaList:
6196 return CreateCharPtrBuiltinVaListDecl(Context);
6197 case TargetInfo::VoidPtrBuiltinVaList:
6198 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006199 case TargetInfo::AArch64ABIBuiltinVaList:
6200 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006201 case TargetInfo::PowerABIBuiltinVaList:
6202 return CreatePowerABIBuiltinVaListDecl(Context);
6203 case TargetInfo::X86_64ABIBuiltinVaList:
6204 return CreateX86_64ABIBuiltinVaListDecl(Context);
6205 case TargetInfo::PNaClABIBuiltinVaList:
6206 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006207 case TargetInfo::AAPCSABIBuiltinVaList:
6208 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006209 case TargetInfo::SystemZBuiltinVaList:
6210 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006211 }
6212
6213 llvm_unreachable("Unhandled __builtin_va_list type kind");
6214}
6215
6216TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006217 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006218 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006219 assert(BuiltinVaListDecl->isImplicit());
6220 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006221
6222 return BuiltinVaListDecl;
6223}
6224
Meador Ingecfb60902012-07-01 15:57:25 +00006225QualType ASTContext::getVaListTagType() const {
6226 // Force the creation of VaListTagTy by building the __builtin_va_list
6227 // declaration.
6228 if (VaListTagTy.isNull())
6229 (void) getBuiltinVaListDecl();
6230
6231 return VaListTagTy;
6232}
6233
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006234void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006235 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006236 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006237
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006238 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006239}
6240
John McCalld28ae272009-12-02 08:04:21 +00006241/// \brief Retrieve the template name that corresponds to a non-empty
6242/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006243TemplateName
6244ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6245 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006246 unsigned size = End - Begin;
6247 assert(size > 1 && "set is not overloaded!");
6248
6249 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6250 size * sizeof(FunctionTemplateDecl*));
6251 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6252
6253 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006254 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006255 NamedDecl *D = *I;
6256 assert(isa<FunctionTemplateDecl>(D) ||
6257 (isa<UsingShadowDecl>(D) &&
6258 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6259 *Storage++ = D;
6260 }
6261
6262 return TemplateName(OT);
6263}
6264
Douglas Gregordc572a32009-03-30 22:58:21 +00006265/// \brief Retrieve the template name that represents a qualified
6266/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006267TemplateName
6268ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6269 bool TemplateKeyword,
6270 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006271 assert(NNS && "Missing nested-name-specifier in qualified template name");
6272
Douglas Gregorc42075a2010-02-04 18:10:26 +00006273 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006274 llvm::FoldingSetNodeID ID;
6275 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6276
Craig Topper36250ad2014-05-12 05:36:57 +00006277 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006278 QualifiedTemplateName *QTN =
6279 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6280 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006281 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6282 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006283 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6284 }
6285
6286 return TemplateName(QTN);
6287}
6288
6289/// \brief Retrieve the template name that represents a dependent
6290/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006291TemplateName
6292ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6293 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006294 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006295 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006296
6297 llvm::FoldingSetNodeID ID;
6298 DependentTemplateName::Profile(ID, NNS, Name);
6299
Craig Topper36250ad2014-05-12 05:36:57 +00006300 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006301 DependentTemplateName *QTN =
6302 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6303
6304 if (QTN)
6305 return TemplateName(QTN);
6306
6307 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6308 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006309 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6310 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006311 } else {
6312 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006313 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6314 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006315 DependentTemplateName *CheckQTN =
6316 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6317 assert(!CheckQTN && "Dependent type name canonicalization broken");
6318 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006319 }
6320
6321 DependentTemplateNames.InsertNode(QTN, InsertPos);
6322 return TemplateName(QTN);
6323}
6324
Douglas Gregor71395fa2009-11-04 00:56:37 +00006325/// \brief Retrieve the template name that represents a dependent
6326/// template name such as \c MetaFun::template operator+.
6327TemplateName
6328ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006329 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006330 assert((!NNS || NNS->isDependent()) &&
6331 "Nested name specifier must be dependent");
6332
6333 llvm::FoldingSetNodeID ID;
6334 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006335
6336 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006337 DependentTemplateName *QTN
6338 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006339
6340 if (QTN)
6341 return TemplateName(QTN);
6342
6343 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6344 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006345 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6346 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006347 } else {
6348 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006349 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6350 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006351
6352 DependentTemplateName *CheckQTN
6353 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6354 assert(!CheckQTN && "Dependent template name canonicalization broken");
6355 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006356 }
6357
6358 DependentTemplateNames.InsertNode(QTN, InsertPos);
6359 return TemplateName(QTN);
6360}
6361
Douglas Gregor5590be02011-01-15 06:45:20 +00006362TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006363ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6364 TemplateName replacement) const {
6365 llvm::FoldingSetNodeID ID;
6366 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006367
6368 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006369 SubstTemplateTemplateParmStorage *subst
6370 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6371
6372 if (!subst) {
6373 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6374 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6375 }
6376
6377 return TemplateName(subst);
6378}
6379
6380TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006381ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6382 const TemplateArgument &ArgPack) const {
6383 ASTContext &Self = const_cast<ASTContext &>(*this);
6384 llvm::FoldingSetNodeID ID;
6385 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006386
6387 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006388 SubstTemplateTemplateParmPackStorage *Subst
6389 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6390
6391 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006392 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006393 ArgPack.pack_size(),
6394 ArgPack.pack_begin());
6395 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6396 }
6397
6398 return TemplateName(Subst);
6399}
6400
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006401/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006402/// TargetInfo, produce the corresponding type. The unsigned @p Type
6403/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006404CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006405 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006406 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006407 case TargetInfo::SignedChar: return SignedCharTy;
6408 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006409 case TargetInfo::SignedShort: return ShortTy;
6410 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6411 case TargetInfo::SignedInt: return IntTy;
6412 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6413 case TargetInfo::SignedLong: return LongTy;
6414 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6415 case TargetInfo::SignedLongLong: return LongLongTy;
6416 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6417 }
6418
David Blaikie83d382b2011-09-23 05:06:16 +00006419 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006420}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006421
6422//===----------------------------------------------------------------------===//
6423// Type Predicates.
6424//===----------------------------------------------------------------------===//
6425
Fariborz Jahanian96207692009-02-18 21:49:28 +00006426/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6427/// garbage collection attribute.
6428///
John McCall553d45a2011-01-12 00:34:59 +00006429Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006430 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006431 return Qualifiers::GCNone;
6432
David Blaikiebbafb8a2012-03-11 07:00:24 +00006433 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006434 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6435
6436 // Default behaviour under objective-C's gc is for ObjC pointers
6437 // (or pointers to them) be treated as though they were declared
6438 // as __strong.
6439 if (GCAttrs == Qualifiers::GCNone) {
6440 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6441 return Qualifiers::Strong;
6442 else if (Ty->isPointerType())
6443 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6444 } else {
6445 // It's not valid to set GC attributes on anything that isn't a
6446 // pointer.
6447#ifndef NDEBUG
6448 QualType CT = Ty->getCanonicalTypeInternal();
6449 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6450 CT = AT->getElementType();
6451 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6452#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006453 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006454 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006455}
6456
Chris Lattner49af6a42008-04-07 06:51:04 +00006457//===----------------------------------------------------------------------===//
6458// Type Compatibility Testing
6459//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006460
Mike Stump11289f42009-09-09 15:08:12 +00006461/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006462/// compatible.
6463static bool areCompatVectorTypes(const VectorType *LHS,
6464 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006465 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006466 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006467 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006468}
6469
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006470bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6471 QualType SecondVec) {
6472 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6473 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6474
6475 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6476 return true;
6477
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006478 // Treat Neon vector types and most AltiVec vector types as if they are the
6479 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006480 const VectorType *First = FirstVec->getAs<VectorType>();
6481 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006482 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006483 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006484 First->getVectorKind() != VectorType::AltiVecPixel &&
6485 First->getVectorKind() != VectorType::AltiVecBool &&
6486 Second->getVectorKind() != VectorType::AltiVecPixel &&
6487 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006488 return true;
6489
6490 return false;
6491}
6492
Steve Naroff8e6aee52009-07-23 01:01:38 +00006493//===----------------------------------------------------------------------===//
6494// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6495//===----------------------------------------------------------------------===//
6496
6497/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6498/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006499bool
6500ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6501 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006502 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006503 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006504 for (auto *PI : rProto->protocols())
6505 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006506 return true;
6507 return false;
6508}
6509
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006510/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6511/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006512bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6513 QualType rhs) {
6514 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6515 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6516 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6517
Aaron Ballman83731462014-03-17 16:14:00 +00006518 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006519 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006520 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006521 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6522 match = true;
6523 break;
6524 }
6525 }
6526 if (!match)
6527 return false;
6528 }
6529 return true;
6530}
6531
Steve Naroff8e6aee52009-07-23 01:01:38 +00006532/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6533/// ObjCQualifiedIDType.
6534bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6535 bool compare) {
6536 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006537 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006538 lhs->isObjCIdType() || lhs->isObjCClassType())
6539 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006540 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006541 rhs->isObjCIdType() || rhs->isObjCClassType())
6542 return true;
6543
6544 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006545 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006546
Steve Naroff8e6aee52009-07-23 01:01:38 +00006547 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006548
Steve Naroff8e6aee52009-07-23 01:01:38 +00006549 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006550 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006551 // make sure we check the class hierarchy.
6552 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006553 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006554 // when comparing an id<P> on lhs with a static type on rhs,
6555 // see if static class implements all of id's protocols, directly or
6556 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006557 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006558 return false;
6559 }
6560 }
6561 // If there are no qualifiers and no interface, we have an 'id'.
6562 return true;
6563 }
Mike Stump11289f42009-09-09 15:08:12 +00006564 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006565 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006566 bool match = false;
6567
6568 // when comparing an id<P> on lhs with a static type on rhs,
6569 // see if static class implements all of id's protocols, directly or
6570 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006571 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006572 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6573 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6574 match = true;
6575 break;
6576 }
6577 }
Mike Stump11289f42009-09-09 15:08:12 +00006578 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006579 // make sure we check the class hierarchy.
6580 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006581 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006582 // when comparing an id<P> on lhs with a static type on rhs,
6583 // see if static class implements all of id's protocols, directly or
6584 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006585 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006586 match = true;
6587 break;
6588 }
6589 }
6590 }
6591 if (!match)
6592 return false;
6593 }
Mike Stump11289f42009-09-09 15:08:12 +00006594
Steve Naroff8e6aee52009-07-23 01:01:38 +00006595 return true;
6596 }
Mike Stump11289f42009-09-09 15:08:12 +00006597
Steve Naroff8e6aee52009-07-23 01:01:38 +00006598 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6599 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6600
Mike Stump11289f42009-09-09 15:08:12 +00006601 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006602 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006603 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006604 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006605 bool match = false;
6606
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006607 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006608 // see if static class implements all of id's protocols, directly or
6609 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006610 // First, lhs protocols in the qualifier list must be found, direct
6611 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006612 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006613 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6614 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6615 match = true;
6616 break;
6617 }
6618 }
6619 if (!match)
6620 return false;
6621 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006622
6623 // Static class's protocols, or its super class or category protocols
6624 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6625 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6626 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6627 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6628 // This is rather dubious but matches gcc's behavior. If lhs has
6629 // no type qualifier and its class has no static protocol(s)
6630 // assume that it is mismatch.
6631 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6632 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006633 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006634 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006635 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006636 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6637 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6638 match = true;
6639 break;
6640 }
6641 }
6642 if (!match)
6643 return false;
6644 }
6645 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006646 return true;
6647 }
6648 return false;
6649}
6650
Eli Friedman47f77112008-08-22 00:56:42 +00006651/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006652/// compatible for assignment from RHS to LHS. This handles validation of any
6653/// protocol qualifiers on the LHS or RHS.
6654///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006655bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6656 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006657 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6658 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6659
Steve Naroff1329fa02009-07-15 18:40:39 +00006660 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006661 if (LHS->isObjCUnqualifiedIdOrClass() ||
6662 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006663 return true;
6664
John McCall8b07ec22010-05-15 11:32:37 +00006665 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006666 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6667 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006668 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006669
6670 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6671 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6672 QualType(RHSOPT,0));
6673
John McCall8b07ec22010-05-15 11:32:37 +00006674 // If we have 2 user-defined types, fall into that path.
6675 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006676 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006677
Steve Naroff8e6aee52009-07-23 01:01:38 +00006678 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006679}
6680
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006681/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006682/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006683/// arguments in block literals. When passed as arguments, passing 'A*' where
6684/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6685/// not OK. For the return type, the opposite is not OK.
6686bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6687 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006688 const ObjCObjectPointerType *RHSOPT,
6689 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006690 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006691 return true;
6692
6693 if (LHSOPT->isObjCBuiltinType()) {
6694 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6695 }
6696
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006697 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006698 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6699 QualType(RHSOPT,0),
6700 false);
6701
6702 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6703 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6704 if (LHS && RHS) { // We have 2 user-defined types.
6705 if (LHS != RHS) {
6706 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006707 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006708 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006709 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006710 }
6711 else
6712 return true;
6713 }
6714 return false;
6715}
6716
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006717/// getIntersectionOfProtocols - This routine finds the intersection of set
6718/// of protocols inherited from two distinct objective-c pointer objects.
6719/// It is used to build composite qualifier list of the composite type of
6720/// the conditional expression involving two objective-c pointer objects.
6721static
6722void getIntersectionOfProtocols(ASTContext &Context,
6723 const ObjCObjectPointerType *LHSOPT,
6724 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006725 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006726
John McCall8b07ec22010-05-15 11:32:37 +00006727 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6728 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6729 assert(LHS->getInterface() && "LHS must have an interface base");
6730 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006731
6732 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6733 unsigned LHSNumProtocols = LHS->getNumProtocols();
6734 if (LHSNumProtocols > 0)
6735 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6736 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006737 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006738 Context.CollectInheritedProtocols(LHS->getInterface(),
6739 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006740 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6741 LHSInheritedProtocols.end());
6742 }
6743
6744 unsigned RHSNumProtocols = RHS->getNumProtocols();
6745 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006746 ObjCProtocolDecl **RHSProtocols =
6747 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006748 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6749 if (InheritedProtocolSet.count(RHSProtocols[i]))
6750 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006751 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006752 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006753 Context.CollectInheritedProtocols(RHS->getInterface(),
6754 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006755 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6756 if (InheritedProtocolSet.count(ProtDecl))
6757 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006758 }
6759}
6760
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006761/// areCommonBaseCompatible - Returns common base class of the two classes if
6762/// one found. Note that this is O'2 algorithm. But it will be called as the
6763/// last type comparison in a ?-exp of ObjC pointer types before a
6764/// warning is issued. So, its invokation is extremely rare.
6765QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006766 const ObjCObjectPointerType *Lptr,
6767 const ObjCObjectPointerType *Rptr) {
6768 const ObjCObjectType *LHS = Lptr->getObjectType();
6769 const ObjCObjectType *RHS = Rptr->getObjectType();
6770 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6771 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006772 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006773 return QualType();
6774
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006775 do {
John McCall8b07ec22010-05-15 11:32:37 +00006776 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006777 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006778 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006779 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6780
6781 QualType Result = QualType(LHS, 0);
6782 if (!Protocols.empty())
6783 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6784 Result = getObjCObjectPointerType(Result);
6785 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006786 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006787 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006788
6789 return QualType();
6790}
6791
John McCall8b07ec22010-05-15 11:32:37 +00006792bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6793 const ObjCObjectType *RHS) {
6794 assert(LHS->getInterface() && "LHS is not an interface type");
6795 assert(RHS->getInterface() && "RHS is not an interface type");
6796
Chris Lattner49af6a42008-04-07 06:51:04 +00006797 // Verify that the base decls are compatible: the RHS must be a subclass of
6798 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006799 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006800 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006801
Chris Lattner49af6a42008-04-07 06:51:04 +00006802 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6803 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006804 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006805 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006806
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006807 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6808 // More detailed analysis is required.
6809 // OK, if LHS is same or a superclass of RHS *and*
6810 // this LHS, or as RHS's super class is assignment compatible with LHS.
6811 bool IsSuperClass =
6812 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6813 if (IsSuperClass) {
6814 // OK if conversion of LHS to SuperClass results in narrowing of types
6815 // ; i.e., SuperClass may implement at least one of the protocols
6816 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6817 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6818 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6819 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6820 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6821 // qualifiers.
6822 for (auto *RHSPI : RHS->quals())
6823 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6824 // If there is no protocols associated with RHS, it is not a match.
6825 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006826 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006827
6828 for (const auto *LHSProto : LHS->quals()) {
6829 bool SuperImplementsProtocol = false;
6830 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6831 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6832 SuperImplementsProtocol = true;
6833 break;
6834 }
6835 if (!SuperImplementsProtocol)
6836 return false;
6837 }
6838 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006839 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006840 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006841}
6842
Steve Naroffb7605152009-02-12 17:52:19 +00006843bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6844 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006845 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6846 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006847
Steve Naroff7cae42b2009-07-10 23:34:53 +00006848 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006849 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006850
6851 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6852 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006853}
6854
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006855bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6856 return canAssignObjCInterfaces(
6857 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6858 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6859}
6860
Mike Stump11289f42009-09-09 15:08:12 +00006861/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006862/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006863/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006864/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006865bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6866 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006867 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006868 return hasSameType(LHS, RHS);
6869
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006870 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006871}
6872
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006873bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006874 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006875}
6876
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006877bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6878 return !mergeTypes(LHS, RHS, true).isNull();
6879}
6880
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006881/// mergeTransparentUnionType - if T is a transparent union type and a member
6882/// of T is compatible with SubType, return the merged type, else return
6883/// QualType()
6884QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6885 bool OfBlockPointer,
6886 bool Unqualified) {
6887 if (const RecordType *UT = T->getAsUnionType()) {
6888 RecordDecl *UD = UT->getDecl();
6889 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006890 for (const auto *I : UD->fields()) {
6891 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006892 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6893 if (!MT.isNull())
6894 return MT;
6895 }
6896 }
6897 }
6898
6899 return QualType();
6900}
6901
Alp Toker9cacbab2014-01-20 20:26:09 +00006902/// mergeFunctionParameterTypes - merge two types which appear as function
6903/// parameter types
6904QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6905 bool OfBlockPointer,
6906 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006907 // GNU extension: two types are compatible if they appear as a function
6908 // argument, one of the types is a transparent union type and the other
6909 // type is compatible with a union member
6910 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6911 Unqualified);
6912 if (!lmerge.isNull())
6913 return lmerge;
6914
6915 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6916 Unqualified);
6917 if (!rmerge.isNull())
6918 return rmerge;
6919
6920 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6921}
6922
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006923QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006924 bool OfBlockPointer,
6925 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006926 const FunctionType *lbase = lhs->getAs<FunctionType>();
6927 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006928 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6929 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006930 bool allLTypes = true;
6931 bool allRTypes = true;
6932
6933 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006934 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006935 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006936 QualType RHS = rbase->getReturnType();
6937 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006938 bool UnqualifiedResult = Unqualified;
6939 if (!UnqualifiedResult)
6940 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006941 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006942 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006943 else
Alp Toker314cc812014-01-25 16:55:45 +00006944 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006945 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006946 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006947
6948 if (Unqualified)
6949 retType = retType.getUnqualifiedType();
6950
Alp Toker314cc812014-01-25 16:55:45 +00006951 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6952 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006953 if (Unqualified) {
6954 LRetType = LRetType.getUnqualifiedType();
6955 RRetType = RRetType.getUnqualifiedType();
6956 }
6957
6958 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006959 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006960 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006961 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006962
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006963 // FIXME: double check this
6964 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6965 // rbase->getRegParmAttr() != 0 &&
6966 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006967 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6968 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006969
Douglas Gregor8c940862010-01-18 17:14:39 +00006970 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006971 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006972 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006973
John McCall8c6b56f2010-12-15 01:06:38 +00006974 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006975 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6976 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006977 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6978 return QualType();
6979
John McCall31168b02011-06-15 23:02:42 +00006980 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6981 return QualType();
6982
John McCall8c6b56f2010-12-15 01:06:38 +00006983 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6984 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006985
Rafael Espindola8778c282012-11-29 16:09:03 +00006986 if (lbaseInfo.getNoReturn() != NoReturn)
6987 allLTypes = false;
6988 if (rbaseInfo.getNoReturn() != NoReturn)
6989 allRTypes = false;
6990
John McCall31168b02011-06-15 23:02:42 +00006991 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006992
Eli Friedman47f77112008-08-22 00:56:42 +00006993 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006994 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6995 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006996 // Compatible functions must have the same number of parameters
6997 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006998 return QualType();
6999
7000 // Variadic and non-variadic functions aren't compatible
7001 if (lproto->isVariadic() != rproto->isVariadic())
7002 return QualType();
7003
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007004 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7005 return QualType();
7006
Fariborz Jahanian97676972011-09-28 21:52:05 +00007007 if (LangOpts.ObjCAutoRefCount &&
7008 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7009 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007010
7011 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007012 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007013 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7014 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7015 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7016 QualType paramType = mergeFunctionParameterTypes(
7017 lParamType, rParamType, OfBlockPointer, Unqualified);
7018 if (paramType.isNull())
7019 return QualType();
7020
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007021 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007022 paramType = paramType.getUnqualifiedType();
7023
7024 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007025 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007026 lParamType = lParamType.getUnqualifiedType();
7027 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007028 }
Alp Toker601b22c2014-01-21 23:35:24 +00007029
7030 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007031 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007032 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007033 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007034 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007035
Eli Friedman47f77112008-08-22 00:56:42 +00007036 if (allLTypes) return lhs;
7037 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007038
7039 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7040 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007041 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007042 }
7043
7044 if (lproto) allRTypes = false;
7045 if (rproto) allLTypes = false;
7046
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007047 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007048 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007049 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007050 if (proto->isVariadic()) return QualType();
7051 // Check that the types are compatible with the types that
7052 // would result from default argument promotions (C99 6.7.5.3p15).
7053 // The only types actually affected are promotable integer
7054 // types and floats, which would be passed as a different
7055 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007056 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7057 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007058
Eli Friedman448ce402012-08-30 00:44:15 +00007059 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007060 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007061 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7062 paramTy = Enum->getDecl()->getIntegerType();
7063 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007064 return QualType();
7065 }
Alp Toker601b22c2014-01-21 23:35:24 +00007066
7067 if (paramTy->isPromotableIntegerType() ||
7068 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007069 return QualType();
7070 }
7071
7072 if (allLTypes) return lhs;
7073 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007074
7075 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7076 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007077 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007078 }
7079
7080 if (allLTypes) return lhs;
7081 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007082 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007083}
7084
John McCall433c2e62013-03-21 00:10:07 +00007085/// Given that we have an enum type and a non-enum type, try to merge them.
7086static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7087 QualType other, bool isBlockReturnType) {
7088 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7089 // a signed integer type, or an unsigned integer type.
7090 // Compatibility is based on the underlying type, not the promotion
7091 // type.
7092 QualType underlyingType = ET->getDecl()->getIntegerType();
7093 if (underlyingType.isNull()) return QualType();
7094 if (Context.hasSameType(underlyingType, other))
7095 return other;
7096
7097 // In block return types, we're more permissive and accept any
7098 // integral type of the same size.
7099 if (isBlockReturnType && other->isIntegerType() &&
7100 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7101 return other;
7102
7103 return QualType();
7104}
7105
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007106QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007107 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007108 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007109 // C++ [expr]: If an expression initially has the type "reference to T", the
7110 // type is adjusted to "T" prior to any further analysis, the expression
7111 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007112 // expression is an lvalue unless the reference is an rvalue reference and
7113 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007114 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7115 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007116
7117 if (Unqualified) {
7118 LHS = LHS.getUnqualifiedType();
7119 RHS = RHS.getUnqualifiedType();
7120 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007121
Eli Friedman47f77112008-08-22 00:56:42 +00007122 QualType LHSCan = getCanonicalType(LHS),
7123 RHSCan = getCanonicalType(RHS);
7124
7125 // If two types are identical, they are compatible.
7126 if (LHSCan == RHSCan)
7127 return LHS;
7128
John McCall8ccfcb52009-09-24 19:53:00 +00007129 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007130 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7131 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007132 if (LQuals != RQuals) {
7133 // If any of these qualifiers are different, we have a type
7134 // mismatch.
7135 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007136 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7137 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007138 return QualType();
7139
7140 // Exactly one GC qualifier difference is allowed: __strong is
7141 // okay if the other type has no GC qualifier but is an Objective
7142 // C object pointer (i.e. implicitly strong by default). We fix
7143 // this by pretending that the unqualified type was actually
7144 // qualified __strong.
7145 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7146 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7147 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7148
7149 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7150 return QualType();
7151
7152 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7153 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7154 }
7155 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7156 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7157 }
Eli Friedman47f77112008-08-22 00:56:42 +00007158 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007159 }
7160
7161 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007162
Eli Friedmandcca6332009-06-01 01:22:52 +00007163 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7164 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007165
Chris Lattnerfd652912008-01-14 05:45:46 +00007166 // We want to consider the two function types to be the same for these
7167 // comparisons, just force one to the other.
7168 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7169 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007170
7171 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007172 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7173 LHSClass = Type::ConstantArray;
7174 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7175 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007176
John McCall8b07ec22010-05-15 11:32:37 +00007177 // ObjCInterfaces are just specialized ObjCObjects.
7178 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7179 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7180
Nate Begemance4d7fc2008-04-18 23:10:10 +00007181 // Canonicalize ExtVector -> Vector.
7182 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7183 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007184
Chris Lattner95554662008-04-07 05:43:21 +00007185 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007186 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007187 // Note that we only have special rules for turning block enum
7188 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007189 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007190 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007191 }
John McCall9dd450b2009-09-21 23:43:11 +00007192 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007193 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007194 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007195 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007196 if (OfBlockPointer && !BlockReturnType) {
7197 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7198 return LHS;
7199 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7200 return RHS;
7201 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007202
Eli Friedman47f77112008-08-22 00:56:42 +00007203 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007204 }
Eli Friedman47f77112008-08-22 00:56:42 +00007205
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007206 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007207 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007208#define TYPE(Class, Base)
7209#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007210#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007211#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7212#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7213#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007214 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007215
Richard Smith27d807c2013-04-30 13:56:41 +00007216 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007217 case Type::LValueReference:
7218 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007219 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007220 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007221
John McCall8b07ec22010-05-15 11:32:37 +00007222 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007223 case Type::IncompleteArray:
7224 case Type::VariableArray:
7225 case Type::FunctionProto:
7226 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007227 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007228
Chris Lattnerfd652912008-01-14 05:45:46 +00007229 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007230 {
7231 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007232 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7233 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007234 if (Unqualified) {
7235 LHSPointee = LHSPointee.getUnqualifiedType();
7236 RHSPointee = RHSPointee.getUnqualifiedType();
7237 }
7238 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7239 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007240 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007241 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007242 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007243 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007244 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007245 return getPointerType(ResultType);
7246 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007247 case Type::BlockPointer:
7248 {
7249 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007250 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7251 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007252 if (Unqualified) {
7253 LHSPointee = LHSPointee.getUnqualifiedType();
7254 RHSPointee = RHSPointee.getUnqualifiedType();
7255 }
7256 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7257 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007258 if (ResultType.isNull()) return QualType();
7259 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7260 return LHS;
7261 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7262 return RHS;
7263 return getBlockPointerType(ResultType);
7264 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007265 case Type::Atomic:
7266 {
7267 // Merge two pointer types, while trying to preserve typedef info
7268 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7269 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7270 if (Unqualified) {
7271 LHSValue = LHSValue.getUnqualifiedType();
7272 RHSValue = RHSValue.getUnqualifiedType();
7273 }
7274 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7275 Unqualified);
7276 if (ResultType.isNull()) return QualType();
7277 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7278 return LHS;
7279 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7280 return RHS;
7281 return getAtomicType(ResultType);
7282 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007283 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007284 {
7285 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7286 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7287 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7288 return QualType();
7289
7290 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7291 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007292 if (Unqualified) {
7293 LHSElem = LHSElem.getUnqualifiedType();
7294 RHSElem = RHSElem.getUnqualifiedType();
7295 }
7296
7297 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007298 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007299 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7300 return LHS;
7301 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7302 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007303 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7304 ArrayType::ArraySizeModifier(), 0);
7305 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7306 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007307 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7308 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007309 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7310 return LHS;
7311 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7312 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007313 if (LVAT) {
7314 // FIXME: This isn't correct! But tricky to implement because
7315 // the array's size has to be the size of LHS, but the type
7316 // has to be different.
7317 return LHS;
7318 }
7319 if (RVAT) {
7320 // FIXME: This isn't correct! But tricky to implement because
7321 // the array's size has to be the size of RHS, but the type
7322 // has to be different.
7323 return RHS;
7324 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007325 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7326 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007327 return getIncompleteArrayType(ResultType,
7328 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007329 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007330 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007331 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007332 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007333 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007334 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007335 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007336 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007337 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007338 case Type::Complex:
7339 // Distinct complex types are incompatible.
7340 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007341 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007342 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007343 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7344 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007345 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007346 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007347 case Type::ObjCObject: {
7348 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007349 // FIXME: This should be type compatibility, e.g. whether
7350 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007351 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7352 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7353 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007354 return LHS;
7355
Eli Friedman47f77112008-08-22 00:56:42 +00007356 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007357 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007358 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007359 if (OfBlockPointer) {
7360 if (canAssignObjCInterfacesInBlockPointer(
7361 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007362 RHS->getAs<ObjCObjectPointerType>(),
7363 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007364 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007365 return QualType();
7366 }
John McCall9dd450b2009-09-21 23:43:11 +00007367 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7368 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007369 return LHS;
7370
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007371 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007372 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007373 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007374
David Blaikie8a40f702012-01-17 06:56:22 +00007375 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007376}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007377
Fariborz Jahanian97676972011-09-28 21:52:05 +00007378bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7379 const FunctionProtoType *FromFunctionType,
7380 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007381 if (FromFunctionType->hasAnyConsumedParams() !=
7382 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007383 return false;
7384 FunctionProtoType::ExtProtoInfo FromEPI =
7385 FromFunctionType->getExtProtoInfo();
7386 FunctionProtoType::ExtProtoInfo ToEPI =
7387 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007388 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007389 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7390 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007391 return false;
7392 }
7393 return true;
7394}
7395
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007396/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7397/// 'RHS' attributes and returns the merged version; including for function
7398/// return types.
7399QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7400 QualType LHSCan = getCanonicalType(LHS),
7401 RHSCan = getCanonicalType(RHS);
7402 // If two types are identical, they are compatible.
7403 if (LHSCan == RHSCan)
7404 return LHS;
7405 if (RHSCan->isFunctionType()) {
7406 if (!LHSCan->isFunctionType())
7407 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007408 QualType OldReturnType =
7409 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007410 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007411 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007412 QualType ResReturnType =
7413 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7414 if (ResReturnType.isNull())
7415 return QualType();
7416 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7417 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7418 // In either case, use OldReturnType to build the new function type.
7419 const FunctionType *F = LHS->getAs<FunctionType>();
7420 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007421 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7422 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007423 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007424 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007425 return ResultType;
7426 }
7427 }
7428 return QualType();
7429 }
7430
7431 // If the qualifiers are different, the types can still be merged.
7432 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7433 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7434 if (LQuals != RQuals) {
7435 // If any of these qualifiers are different, we have a type mismatch.
7436 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7437 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7438 return QualType();
7439
7440 // Exactly one GC qualifier difference is allowed: __strong is
7441 // okay if the other type has no GC qualifier but is an Objective
7442 // C object pointer (i.e. implicitly strong by default). We fix
7443 // this by pretending that the unqualified type was actually
7444 // qualified __strong.
7445 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7446 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7447 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7448
7449 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7450 return QualType();
7451
7452 if (GC_L == Qualifiers::Strong)
7453 return LHS;
7454 if (GC_R == Qualifiers::Strong)
7455 return RHS;
7456 return QualType();
7457 }
7458
7459 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7460 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7461 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7462 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7463 if (ResQT == LHSBaseQT)
7464 return LHS;
7465 if (ResQT == RHSBaseQT)
7466 return RHS;
7467 }
7468 return QualType();
7469}
7470
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007471//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007472// Integer Predicates
7473//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007474
Jay Foad39c79802011-01-12 09:06:06 +00007475unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007476 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007477 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007478 if (T->isBooleanType())
7479 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007480 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007481 return (unsigned)getTypeSize(T);
7482}
7483
Abramo Bagnara13640492012-09-09 10:21:24 +00007484QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007485 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007486
7487 // Turn <4 x signed int> -> <4 x unsigned int>
7488 if (const VectorType *VTy = T->getAs<VectorType>())
7489 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007490 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007491
7492 // For enums, we return the unsigned version of the base type.
7493 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007494 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007495
7496 const BuiltinType *BTy = T->getAs<BuiltinType>();
7497 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007498 switch (BTy->getKind()) {
7499 case BuiltinType::Char_S:
7500 case BuiltinType::SChar:
7501 return UnsignedCharTy;
7502 case BuiltinType::Short:
7503 return UnsignedShortTy;
7504 case BuiltinType::Int:
7505 return UnsignedIntTy;
7506 case BuiltinType::Long:
7507 return UnsignedLongTy;
7508 case BuiltinType::LongLong:
7509 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007510 case BuiltinType::Int128:
7511 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007512 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007513 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007514 }
7515}
7516
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007517ASTMutationListener::~ASTMutationListener() { }
7518
Richard Smith1fa5d642013-05-11 05:45:24 +00007519void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7520 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007521
7522//===----------------------------------------------------------------------===//
7523// Builtin Type Computation
7524//===----------------------------------------------------------------------===//
7525
7526/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007527/// pointer over the consumed characters. This returns the resultant type. If
7528/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7529/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7530/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007531///
7532/// RequiresICE is filled in on return to indicate whether the value is required
7533/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007534static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007535 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007536 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007537 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007538 // Modifiers.
7539 int HowLong = 0;
7540 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007541 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007542
Chris Lattnerdc226c22010-10-01 22:42:38 +00007543 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007544 bool Done = false;
7545 while (!Done) {
7546 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007547 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007548 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007549 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007550 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007551 case 'S':
7552 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7553 assert(!Signed && "Can't use 'S' modifier multiple times!");
7554 Signed = true;
7555 break;
7556 case 'U':
7557 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007558 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007559 Unsigned = true;
7560 break;
7561 case 'L':
7562 assert(HowLong <= 2 && "Can't have LLLL modifier");
7563 ++HowLong;
7564 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007565 case 'W':
7566 // This modifier represents int64 type.
7567 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7568 switch (Context.getTargetInfo().getInt64Type()) {
7569 default:
7570 llvm_unreachable("Unexpected integer type");
7571 case TargetInfo::SignedLong:
7572 HowLong = 1;
7573 break;
7574 case TargetInfo::SignedLongLong:
7575 HowLong = 2;
7576 break;
7577 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007578 }
7579 }
7580
7581 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007582
Chris Lattnerecd79c62009-06-14 00:45:47 +00007583 // Read the base type.
7584 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007585 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007586 case 'v':
7587 assert(HowLong == 0 && !Signed && !Unsigned &&
7588 "Bad modifiers used with 'v'!");
7589 Type = Context.VoidTy;
7590 break;
Jack Carter24bef982013-08-15 15:16:57 +00007591 case 'h':
7592 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007593 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007594 Type = Context.HalfTy;
7595 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007596 case 'f':
7597 assert(HowLong == 0 && !Signed && !Unsigned &&
7598 "Bad modifiers used with 'f'!");
7599 Type = Context.FloatTy;
7600 break;
7601 case 'd':
7602 assert(HowLong < 2 && !Signed && !Unsigned &&
7603 "Bad modifiers used with 'd'!");
7604 if (HowLong)
7605 Type = Context.LongDoubleTy;
7606 else
7607 Type = Context.DoubleTy;
7608 break;
7609 case 's':
7610 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7611 if (Unsigned)
7612 Type = Context.UnsignedShortTy;
7613 else
7614 Type = Context.ShortTy;
7615 break;
7616 case 'i':
7617 if (HowLong == 3)
7618 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7619 else if (HowLong == 2)
7620 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7621 else if (HowLong == 1)
7622 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7623 else
7624 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7625 break;
7626 case 'c':
7627 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7628 if (Signed)
7629 Type = Context.SignedCharTy;
7630 else if (Unsigned)
7631 Type = Context.UnsignedCharTy;
7632 else
7633 Type = Context.CharTy;
7634 break;
7635 case 'b': // boolean
7636 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7637 Type = Context.BoolTy;
7638 break;
7639 case 'z': // size_t.
7640 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7641 Type = Context.getSizeType();
7642 break;
7643 case 'F':
7644 Type = Context.getCFConstantStringType();
7645 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007646 case 'G':
7647 Type = Context.getObjCIdType();
7648 break;
7649 case 'H':
7650 Type = Context.getObjCSelType();
7651 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007652 case 'M':
7653 Type = Context.getObjCSuperType();
7654 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007655 case 'a':
7656 Type = Context.getBuiltinVaListType();
7657 assert(!Type.isNull() && "builtin va list type not initialized!");
7658 break;
7659 case 'A':
7660 // This is a "reference" to a va_list; however, what exactly
7661 // this means depends on how va_list is defined. There are two
7662 // different kinds of va_list: ones passed by value, and ones
7663 // passed by reference. An example of a by-value va_list is
7664 // x86, where va_list is a char*. An example of by-ref va_list
7665 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7666 // we want this argument to be a char*&; for x86-64, we want
7667 // it to be a __va_list_tag*.
7668 Type = Context.getBuiltinVaListType();
7669 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007670 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007671 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007672 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007673 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007674 break;
7675 case 'V': {
7676 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007677 unsigned NumElements = strtoul(Str, &End, 10);
7678 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007679 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007680
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007681 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7682 RequiresICE, false);
7683 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007684
7685 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007686 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007687 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007688 break;
7689 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007690 case 'E': {
7691 char *End;
7692
7693 unsigned NumElements = strtoul(Str, &End, 10);
7694 assert(End != Str && "Missing vector size");
7695
7696 Str = End;
7697
7698 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7699 false);
7700 Type = Context.getExtVectorType(ElementType, NumElements);
7701 break;
7702 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007703 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007704 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7705 false);
7706 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007707 Type = Context.getComplexType(ElementType);
7708 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007709 }
7710 case 'Y' : {
7711 Type = Context.getPointerDiffType();
7712 break;
7713 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007714 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007715 Type = Context.getFILEType();
7716 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007717 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007718 return QualType();
7719 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007720 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007721 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007722 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007723 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007724 else
7725 Type = Context.getjmp_bufType();
7726
Mike Stump2adb4da2009-07-28 23:47:15 +00007727 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007728 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007729 return QualType();
7730 }
7731 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007732 case 'K':
7733 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7734 Type = Context.getucontext_tType();
7735
7736 if (Type.isNull()) {
7737 Error = ASTContext::GE_Missing_ucontext;
7738 return QualType();
7739 }
7740 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007741 case 'p':
7742 Type = Context.getProcessIDType();
7743 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007744 }
Mike Stump11289f42009-09-09 15:08:12 +00007745
Chris Lattnerdc226c22010-10-01 22:42:38 +00007746 // If there are modifiers and if we're allowed to parse them, go for it.
7747 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007748 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007749 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007750 default: Done = true; --Str; break;
7751 case '*':
7752 case '&': {
7753 // Both pointers and references can have their pointee types
7754 // qualified with an address space.
7755 char *End;
7756 unsigned AddrSpace = strtoul(Str, &End, 10);
7757 if (End != Str && AddrSpace != 0) {
7758 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7759 Str = End;
7760 }
7761 if (c == '*')
7762 Type = Context.getPointerType(Type);
7763 else
7764 Type = Context.getLValueReferenceType(Type);
7765 break;
7766 }
7767 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7768 case 'C':
7769 Type = Type.withConst();
7770 break;
7771 case 'D':
7772 Type = Context.getVolatileType(Type);
7773 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007774 case 'R':
7775 Type = Type.withRestrict();
7776 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007777 }
7778 }
Chris Lattner84733392010-10-01 07:13:18 +00007779
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007780 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007781 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007782
Chris Lattnerecd79c62009-06-14 00:45:47 +00007783 return Type;
7784}
7785
7786/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007787QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007788 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007789 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007790 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007791
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007792 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007793
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007794 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007795 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007796 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7797 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007798 if (Error != GE_None)
7799 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007800
7801 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7802
Chris Lattnerecd79c62009-06-14 00:45:47 +00007803 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007804 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007805 if (Error != GE_None)
7806 return QualType();
7807
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007808 // If this argument is required to be an IntegerConstantExpression and the
7809 // caller cares, fill in the bitmask we return.
7810 if (RequiresICE && IntegerConstantArgs)
7811 *IntegerConstantArgs |= 1 << ArgTypes.size();
7812
Chris Lattnerecd79c62009-06-14 00:45:47 +00007813 // Do array -> pointer decay. The builtin should use the decayed type.
7814 if (Ty->isArrayType())
7815 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007816
Chris Lattnerecd79c62009-06-14 00:45:47 +00007817 ArgTypes.push_back(Ty);
7818 }
7819
7820 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7821 "'.' should only occur at end of builtin type list!");
7822
Reid Kleckner78af0702013-08-27 23:08:25 +00007823 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007824 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7825
7826 bool Variadic = (TypeStr[0] == '.');
7827
7828 // We really shouldn't be making a no-proto type here, especially in C++.
7829 if (ArgTypes.empty() && Variadic)
7830 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007831
John McCalldb40c7f2010-12-14 08:05:40 +00007832 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007833 EPI.ExtInfo = EI;
7834 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007835
Jordan Rose5c382722013-03-08 21:51:21 +00007836 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007837}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007838
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007839static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7840 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007841 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007842 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007843
Rafael Espindola3ae00052013-05-13 00:12:11 +00007844 GVALinkage External = GVA_StrongExternal;
7845 switch (FD->getTemplateSpecializationKind()) {
7846 case TSK_Undeclared:
7847 case TSK_ExplicitSpecialization:
7848 External = GVA_StrongExternal;
7849 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007850
Rafael Espindola3ae00052013-05-13 00:12:11 +00007851 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007852 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007853
David Majnemerc3d07332014-05-15 06:25:57 +00007854 // C++11 [temp.explicit]p10:
7855 // [ Note: The intent is that an inline function that is the subject of
7856 // an explicit instantiation declaration will still be implicitly
7857 // instantiated when used so that the body can be considered for
7858 // inlining, but that no out-of-line copy of the inline function would be
7859 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007860 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007861 return GVA_AvailableExternally;
7862
Rafael Espindola3ae00052013-05-13 00:12:11 +00007863 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007864 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007865 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007866 }
7867
7868 if (!FD->isInlined())
7869 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007870
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007871 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7872 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007873 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007874 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7875
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007876 // GNU or C99 inline semantics. Determine whether this symbol should be
7877 // externally visible.
7878 if (FD->isInlineDefinitionExternallyVisible())
7879 return External;
7880
7881 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007882 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007883 }
7884
David Majnemer54e3ba52014-04-02 23:17:29 +00007885 // Functions specified with extern and inline in -fms-compatibility mode
7886 // forcibly get emitted. While the body of the function cannot be later
7887 // replaced, the function definition cannot be discarded.
7888 if (FD->getMostRecentDecl()->isMSExternInline())
7889 return GVA_StrongODR;
7890
David Majnemer27d69db2014-04-28 22:17:59 +00007891 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007892}
7893
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007894static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7895 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7896 // dllexport/dllimport on inline functions.
7897 if (D->hasAttr<DLLImportAttr>()) {
7898 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7899 return GVA_AvailableExternally;
7900 } else if (D->hasAttr<DLLExportAttr>()) {
7901 if (L == GVA_DiscardableODR)
7902 return GVA_StrongODR;
7903 }
7904 return L;
7905}
7906
7907GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7908 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7909 FD);
7910}
7911
7912static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7913 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007914 if (!VD->isExternallyVisible())
7915 return GVA_Internal;
7916
David Majnemer27d69db2014-04-28 22:17:59 +00007917 if (VD->isStaticLocal()) {
7918 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7919 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7920 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7921 LexicalContext = LexicalContext->getLexicalParent();
7922
7923 // Let the static local variable inherit it's linkage from the nearest
7924 // enclosing function.
7925 if (LexicalContext)
7926 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007927 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007928
7929 // GVA_StrongODR function linkage is stronger than what we need,
7930 // downgrade to GVA_DiscardableODR.
7931 // This allows us to discard the variable if we never end up needing it.
7932 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7933 : StaticLocalLinkage;
7934 }
7935
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007936 // MSVC treats in-class initialized static data members as definitions.
7937 // By giving them non-strong linkage, out-of-line definitions won't
7938 // cause link errors.
7939 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7940 return GVA_DiscardableODR;
7941
Richard Smith8809a0c2013-09-27 20:14:12 +00007942 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007943 case TSK_Undeclared:
7944 case TSK_ExplicitSpecialization:
7945 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007946
Rafael Espindola3ae00052013-05-13 00:12:11 +00007947 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007948 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007949
David Majnemer27d69db2014-04-28 22:17:59 +00007950 case TSK_ExplicitInstantiationDeclaration:
7951 return GVA_AvailableExternally;
7952
Rafael Espindola3ae00052013-05-13 00:12:11 +00007953 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007954 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007955 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007956
7957 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007958}
7959
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007960GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7961 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7962 VD);
7963}
7964
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007965bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007966 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7967 if (!VD->isFileVarDecl())
7968 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007969 // Global named register variables (GNU extension) are never emitted.
7970 if (VD->getStorageClass() == SC_Register)
7971 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007972 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7973 // We never need to emit an uninstantiated function template.
7974 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7975 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00007976 } else if (isa<OMPThreadPrivateDecl>(D))
7977 return true;
7978 else
Richard Smith5205a8c2013-04-01 20:22:16 +00007979 return false;
7980
7981 // If this is a member of a class template, we do not need to emit it.
7982 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007983 return false;
7984
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007985 // Weak references don't produce any output by themselves.
7986 if (D->hasAttr<WeakRefAttr>())
7987 return false;
7988
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007989 // Aliases and used decls are required.
7990 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7991 return true;
7992
7993 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7994 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007995 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007996 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007997
7998 // Constructors and destructors are required.
7999 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8000 return true;
8001
John McCall6bd2a892013-01-25 22:31:03 +00008002 // The key function for a class is required. This rule only comes
8003 // into play when inline functions can be key functions, though.
8004 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8005 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8006 const CXXRecordDecl *RD = MD->getParent();
8007 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8008 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8009 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8010 return true;
8011 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008012 }
8013 }
8014
8015 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8016
8017 // static, static inline, always_inline, and extern inline functions can
8018 // always be deferred. Normal inline functions can be deferred in C99/C++.
8019 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008020 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8021 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008022 return false;
8023 return true;
8024 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008025
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008026 const VarDecl *VD = cast<VarDecl>(D);
8027 assert(VD->isFileVarDecl() && "Expected file scoped var");
8028
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008029 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8030 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008031 return false;
8032
Richard Smitha0e5e542012-11-12 21:38:00 +00008033 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008034 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008035 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8036 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008037 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008038
Richard Smitha0e5e542012-11-12 21:38:00 +00008039 // Variables that have destruction with side-effects are required.
8040 if (VD->getType().isDestructedType())
8041 return true;
8042
8043 // Variables that have initialization with side-effects are required.
8044 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8045 return true;
8046
8047 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008048}
Charles Davis53c59df2010-08-16 03:33:14 +00008049
Reid Kleckner78af0702013-08-27 23:08:25 +00008050CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8051 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008052 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008053 if (IsCXXMethod)
8054 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008055
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008056 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8057
8058 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008059}
8060
Jay Foad39c79802011-01-12 09:06:06 +00008061bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008062 // Pass through to the C++ ABI object
8063 return ABI->isNearlyEmpty(RD);
8064}
8065
Reid Kleckner96f8f932014-02-05 17:27:08 +00008066VTableContextBase *ASTContext::getVTableContext() {
8067 if (!VTContext.get()) {
8068 if (Target->getCXXABI().isMicrosoft())
8069 VTContext.reset(new MicrosoftVTableContext(*this));
8070 else
8071 VTContext.reset(new ItaniumVTableContext(*this));
8072 }
8073 return VTContext.get();
8074}
8075
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008076MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008077 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008078 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008079 case TargetCXXABI::GenericItanium:
8080 case TargetCXXABI::GenericARM:
8081 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008082 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008083 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008084 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008085 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008086 }
David Blaikie83d382b2011-09-23 05:06:16 +00008087 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008088}
8089
Charles Davis53c59df2010-08-16 03:33:14 +00008090CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008091
8092size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008093 return ASTRecordLayouts.getMemorySize() +
8094 llvm::capacity_in_bytes(ObjCLayouts) +
8095 llvm::capacity_in_bytes(KeyFunctions) +
8096 llvm::capacity_in_bytes(ObjCImpls) +
8097 llvm::capacity_in_bytes(BlockVarCopyInits) +
8098 llvm::capacity_in_bytes(DeclAttrs) +
8099 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8100 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8101 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8102 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8103 llvm::capacity_in_bytes(OverriddenMethods) +
8104 llvm::capacity_in_bytes(Types) +
8105 llvm::capacity_in_bytes(VariableArrayTypes) +
8106 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008107}
Ted Kremenek540017e2011-10-06 05:00:56 +00008108
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008109/// getIntTypeForBitwidth -
8110/// sets integer QualTy according to specified details:
8111/// bitwidth, signed/unsigned.
8112/// Returns empty type if there is no appropriate target types.
8113QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8114 unsigned Signed) const {
8115 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8116 CanQualType QualTy = getFromTargetType(Ty);
8117 if (!QualTy && DestWidth == 128)
8118 return Signed ? Int128Ty : UnsignedInt128Ty;
8119 return QualTy;
8120}
8121
8122/// getRealTypeForBitwidth -
8123/// sets floating point QualTy according to specified bitwidth.
8124/// Returns empty type if there is no appropriate target types.
8125QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8126 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8127 switch (Ty) {
8128 case TargetInfo::Float:
8129 return FloatTy;
8130 case TargetInfo::Double:
8131 return DoubleTy;
8132 case TargetInfo::LongDouble:
8133 return LongDoubleTy;
8134 case TargetInfo::NoFloat:
8135 return QualType();
8136 }
8137
8138 llvm_unreachable("Unhandled TargetInfo::RealType value");
8139}
8140
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008141void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8142 if (Number > 1)
8143 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008144}
8145
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008146unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8147 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8148 MangleNumbers.find(ND);
8149 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008150}
8151
David Majnemer2206bf52014-03-05 08:57:59 +00008152void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8153 if (Number > 1)
8154 StaticLocalNumbers[VD] = Number;
8155}
8156
8157unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8158 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8159 StaticLocalNumbers.find(VD);
8160 return I != StaticLocalNumbers.end() ? I->second : 1;
8161}
8162
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008163MangleNumberingContext &
8164ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008165 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8166 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8167 if (!MCtx)
8168 MCtx = createMangleNumberingContext();
8169 return *MCtx;
8170}
8171
8172MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8173 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008174}
8175
Ted Kremenek540017e2011-10-06 05:00:56 +00008176void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8177 ParamIndices[D] = index;
8178}
8179
8180unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8181 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8182 assert(I != ParamIndices.end() &&
8183 "ParmIndices lacks entry set by ParmVarDecl");
8184 return I->second;
8185}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008186
Richard Smithe6c01442013-06-05 00:46:14 +00008187APValue *
8188ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8189 bool MayCreate) {
8190 assert(E && E->getStorageDuration() == SD_Static &&
8191 "don't need to cache the computed value for this temporary");
8192 if (MayCreate)
8193 return &MaterializedTemporaryValues[E];
8194
8195 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8196 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008197 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008198}
8199
Fariborz Jahanian615de762013-05-28 17:37:39 +00008200bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8201 const llvm::Triple &T = getTargetInfo().getTriple();
8202 if (!T.isOSDarwin())
8203 return false;
8204
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008205 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8206 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8207 return false;
8208
Fariborz Jahanian615de762013-05-28 17:37:39 +00008209 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8210 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8211 uint64_t Size = sizeChars.getQuantity();
8212 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8213 unsigned Align = alignChars.getQuantity();
8214 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8215 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8216}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008217
8218namespace {
8219
8220 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8221 /// parents as defined by the \c RecursiveASTVisitor.
8222 ///
8223 /// Note that the relationship described here is purely in terms of AST
8224 /// traversal - there are other relationships (for example declaration context)
8225 /// in the AST that are better modeled by special matchers.
8226 ///
8227 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8228 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8229
8230 public:
8231 /// \brief Builds and returns the translation unit's parent map.
8232 ///
8233 /// The caller takes ownership of the returned \c ParentMap.
8234 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8235 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8236 Visitor.TraverseDecl(&TU);
8237 return Visitor.Parents;
8238 }
8239
8240 private:
8241 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8242
8243 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8244 }
8245
8246 bool shouldVisitTemplateInstantiations() const {
8247 return true;
8248 }
8249 bool shouldVisitImplicitCode() const {
8250 return true;
8251 }
8252 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8253 // are not triggered during data recursion.
8254 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8255 return false;
8256 }
8257
8258 template <typename T>
8259 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008260 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008261 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008262 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008263 // FIXME: Currently we add the same parent multiple times, but only
8264 // when no memoization data is available for the type.
8265 // For example when we visit all subexpressions of template
8266 // instantiations; this is suboptimal, but benign: the only way to
8267 // visit those is with hasAncestor / hasParent, and those do not create
8268 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008269 // The plan is to enable DynTypedNode to be storable in a map or hash
8270 // map. The main problem there is to implement hash functions /
8271 // comparison operators for all types that DynTypedNode supports that
8272 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008273 auto &NodeOrVector = (*Parents)[Node];
8274 if (NodeOrVector.isNull()) {
8275 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008276 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008277 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8278 auto *Node =
8279 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8280 auto *Vector = new ASTContext::ParentVector(1, *Node);
8281 NodeOrVector = Vector;
8282 delete Node;
8283 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008284 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008285
8286 auto *Vector =
8287 NodeOrVector.template get<ASTContext::ParentVector *>();
8288 // Skip duplicates for types that have memoization data.
8289 // We must check that the type has memoization data before calling
8290 // std::find() because DynTypedNode::operator== can't compare all
8291 // types.
8292 bool Found = ParentStack.back().getMemoizationData() &&
8293 std::find(Vector->begin(), Vector->end(),
8294 ParentStack.back()) != Vector->end();
8295 if (!Found)
8296 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008297 }
8298 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008299 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8300 bool Result = (this ->* traverse) (Node);
8301 ParentStack.pop_back();
8302 return Result;
8303 }
8304
8305 bool TraverseDecl(Decl *DeclNode) {
8306 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8307 }
8308
8309 bool TraverseStmt(Stmt *StmtNode) {
8310 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8311 }
8312
8313 ASTContext::ParentMap *Parents;
8314 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8315
8316 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8317 };
8318
8319} // end namespace
8320
Benjamin Kramer07935292014-10-04 17:01:26 +00008321ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008322ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8323 assert(Node.getMemoizationData() &&
8324 "Invariant broken: only nodes that support memoization may be "
8325 "used in the parent map.");
8326 if (!AllParents) {
8327 // We always need to run over the whole translation unit, as
8328 // hasAncestor can escape any subtree.
8329 AllParents.reset(
8330 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8331 }
8332 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8333 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008334 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008335 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008336 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8337 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008338 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008339 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008340}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008341
8342bool
8343ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8344 const ObjCMethodDecl *MethodImpl) {
8345 // No point trying to match an unavailable/deprecated mothod.
8346 if (MethodDecl->hasAttr<UnavailableAttr>()
8347 || MethodDecl->hasAttr<DeprecatedAttr>())
8348 return false;
8349 if (MethodDecl->getObjCDeclQualifier() !=
8350 MethodImpl->getObjCDeclQualifier())
8351 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008352 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008353 return false;
8354
8355 if (MethodDecl->param_size() != MethodImpl->param_size())
8356 return false;
8357
8358 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8359 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8360 EF = MethodDecl->param_end();
8361 IM != EM && IF != EF; ++IM, ++IF) {
8362 const ParmVarDecl *DeclVar = (*IF);
8363 const ParmVarDecl *ImplVar = (*IM);
8364 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8365 return false;
8366 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8367 return false;
8368 }
8369 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8370
8371}
Richard Smith053f6c62014-05-16 23:01:30 +00008372
8373// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8374// doesn't include ASTContext.h
8375template
8376clang::LazyGenerationalUpdatePtr<
8377 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8378clang::LazyGenerationalUpdatePtr<
8379 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8380 const clang::ASTContext &Ctx, Decl *Value);